开发者

solving equations and using values obtained in other calculations - SAGE

开发者 https://www.devze.com 2023-03-11 10:46 出处:网络
the function solve() in SAGE returns symbolic values for the variables i solve the equations for. for e.g:

the function solve() in SAGE returns symbolic values for the variables i solve the equations for. for e.g:

sage: s=solve(eqn,y)
sage: s
[y == -1/2*(sqrt(-596*x^8 - 168*x^7 - 67*x^6 + 240*x^5 + 144*x^4 - 60*x 开发者_如何学Go- 4) + 8*x^4 + 11*x^3 + 12*x^2)/(15*x + 1), y == 1/2*(sqrt(-596*x^8 - 168*x^7 - 67*x^6 + 240*x^5 + 144*x^4 - 60*x - 4) - 8*x^4 - 11*x^3 - 12*x^2)/(15*x + 1)]

My problem is that i need to use the values obtained for y in other calculations, but I cannot assign these values to any other variable. Could someone please help me with this?


(1) You should visit ask.sagemath.org, the Stack Overflow-like forum for Sage users, experts, and developers! </plug>

(2) If you want to use the values of a solve() call in something, then it's probably easiest to use the solution_dict flag:

sage: x,y = var("x, y")
sage: eqn = x**4+5*x*y+3*x-y==17
sage: solve(eqn,y)
[y == -(x^4 + 3*x - 17)/(5*x - 1)]
sage: solve(eqn,y,solution_dict=True)
[{y: -(x^4 + 3*x - 17)/(5*x - 1)}]

This option gives the solutions as a list of dictionaries instead of a list of equations. We can access the results like we would any other dictionary:

sage: sols = solve(eqn,y,solution_dict=True)
sage: sols[0][y]
-(x^4 + 3*x - 17)/(5*x - 1)

and then we can assign that to something else if we like:

sage: z = sols[0][y]
sage: z
-(x^4 + 3*x - 17)/(5*x - 1)

and substitute:

sage: eqn2 = y*(5*x-1)
sage: eqn2.subs(y=z)
-x^4 - 3*x + 17

et cetera. While IMHO the above is more convenient, you could also access the same results without solution_dict via .rhs():

sage: solve(eqn,y)[0].rhs()
-(x^4 + 3*x - 17)/(5*x - 1)


If you have unknown number of variables you can use **kwargs to pass data calculated with solve to next expressions. Here's example:

B_set is an list of variables and its filled in runtime so i dont know names of variables and their quantity at the time of writing the code

solution = solve(system_of_equations, B_set)[0]
pretty_print(solution)

For example this gives me: result of solving system of equations

I cant use this answer for further calculations so lets convert it to usable form

solution = {str(elem.lhs()): elem.rhs() for elem in solution}

Which gives us: result converted to dictionary with string keys

Then we just pass this as **kwargs

approximation = approximation_function(**solution)
pretty_print(approximation)

And that converts this: approximation without values from solution

Into this: approximation with values from solution

Note: if you use dictionary output from solve() you still need to convert keys to string.

0

精彩评论

暂无评论...
验证码 换一张
取 消