Ask Your Question
4

Extract solutions from solve

asked 2012-02-22 04:27:44 -0500

Rejeesh gravatar image

updated 2012-02-22 05:39:50 -0500

kcrisman gravatar image

I am new to sage. So, sorry if my question is trivial.

How can I get the values of a solve operation. Say I have

x = var('x');
f = x^2 - 5*x + 6;
z = solve(f = 0, x);
show(z);

gives me something like

[x == 2, x == 3]

How can I take the value 2 or 3 from that?

Also, when I was trying to solve another equation (quiet a long one), I get the solution as

[0 = something something.....]

What does that zero mean?

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
5

answered 2012-02-22 05:45:00 -0500

kcrisman gravatar image

I am new to sage. So, sorry if my question is trivial.

Not at all! Likely you could have found this by doing a little more reconnaissance, but hopefully others in the same boat will now find this instead.

Incidentally, x is the only predefined variable, so your first line is not needed. Also, the semicolons are not necessary to suppress output.

I hope this example answers your questions.

sage: f = x^2 - 5*x + 6
sage: z = solve(f,x) # f==0 is implicit
sage: z
[x == 3, x == 2]
sage: z[0]
x == 3
sage: z[1]
x == 2
sage: z[0].rhs()
3
sage: z[0].lhs()
x

Essentially, Sage returns Python lists, and this is how to extract stuff from them. It returns a symbolic equality, and then the rhs() method gets the "right hand side".

There is another way to get solutions as Python dicts, but that is slightly more advanced so maybe someone else can comment on that.

edit flag offensive delete link more

Comments

@kcrisman Thanks a lot for that. Those semicolons come from C (and maybe a bit from Octave/Matlab). I just can't think of a world without semicolons. And like you said, a bit of Google and some docs would have answered me.

Rejeesh gravatar imageRejeesh ( 2012-02-22 06:21:59 -0500 )edit

No problem! In fact, semicolons *do* have a purpose in Python. Compare two lines `2+2` and `2+3` with `2+2; 2+3` in a notebook cell.

kcrisman gravatar imagekcrisman ( 2012-02-23 01:20:03 -0500 )edit
5

answered 2012-02-23 17:09:49 -0500

mhampton gravatar image

Sometimes - especially in more complicated multivariate cases - using the option solution_dict = True is convenient. It doesn't really help here, but for your example:

x = var('x')
f = x^2 - 5*x + 6
z = solve(f, x, solution_dict=True)
for solution in z:
    print x.subs(solution)

3
2
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2012-02-22 04:27:44 -0500

Seen: 2,776 times

Last updated: Feb 23 '12