Ask Your Question
0

How to extract one solution from the long output of solve(eq)

asked 2023-05-03 21:59:56 +0100

8moeb8 gravatar image

I am solving a system of symbolic equations with a lot of variables, but I only want to know the solution of say, x_1. How can I extract that information from "sage.structure.sequence.Sequence_generic"? It seems that the output has length only 1, so s[0] does not work.

Thank you!

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
0

answered 2023-05-04 08:19:58 +0100

achrzesz gravatar image

You can use the names of variables:

var('x_1 x_2')
s=solve([x_1^2+x_2^2==1,x_1-x_2==1/2],x_1,x_2,solution_dict=True)
s

[{x_1: -1/4*sqrt(7) + 1/4, x_2: -1/4*sqrt(7) - 1/4},
 {x_1: 1/4*sqrt(7) + 1/4, x_2: 1/4*sqrt(7) - 1/4}]

s[0]                  # first solution

{x_1: -1/4*sqrt(7) + 1/4, x_2: -1/4*sqrt(7) - 1/4}

s[0][x_1]             # x_1 component of the first solution

-1/4*sqrt(7) + 1/4
edit flag offensive delete link more

Comments

Thank you!

8moeb8 gravatar image8moeb8 ( 2023-05-08 19:37:09 +0100 )edit
0

answered 2023-05-04 09:26:18 +0100

Emmanuel Charpentier gravatar image

updated 2023-05-04 09:34:00 +0100

It seems that the output has length only 1, so s[0] does not work.

That's a solve idiosyncrasy :

Each solution of a(n) (system of) equation(s) for n>1 variables is either a list of n equations (default) or a dictionary with n keys (when using solution_dict=True). solve returns a list of such solutions, i. e. either a list of n-long lists or a list of n-long dictionaries.

However, when solving a(n) (system of) equation(s) for one variable and not using solution_dict=True, solve "simplifies" what should be a list of 1-long lists in a list of equations, each of them being a solution for this variable.

This (disputable) simplification has been baked in Sage since Sage's early developers decoded to follow Maxima's conventions (dating from the early 1960's...) and is now a geological axiom. Complain fiercely...

Workaround : use solution_dict=True, whose return values are more consistent (and usually easier to use, anyway...).

HTH,

edit flag offensive delete link more

Comments

Thank you!

8moeb8 gravatar image8moeb8 ( 2023-05-08 19:37:05 +0100 )edit

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: 2023-05-03 21:59:56 +0100

Seen: 527 times

Last updated: May 04 '23