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

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 close merge delete

Sort by ยป oldest newest most voted

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

more

Thank you!

( 2023-05-08 19:37:09 +0100 )edit

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,

more

Thank you!

( 2023-05-08 19:37:05 +0100 )edit