evaluating an expression

This post is a wiki. Anyone with karma >750 is welcome to improve it.

Hello,

started to use open source mathematical software. And i have some questions since i can not find in google what i am searching for (maybe i am a bad searcher :S).

The thing is if i write in maple (with predefined F, M, q and Q):

Sum('F[ix]', 'i' = 1 .. n) = 0; '-2*F*cos(45*deg)-3*Q+4*RB*cos(45*deg)-RB*sin(45*deg)-M = 0'; evalf[4](solve(%, RB))


I get

RB := 19.51


And in Sage:

solve(-2*F*cos(45*deg)-3*Q+4*RB*cos(45*deg)-RB*sin(45*deg)-M,RB)


i get:

[23/3*sqrt(2) + 26/3 == 23/3*sqrt(2) + 26/3]


Now i do not find any equivalent to evalf in sage. Could someone help me, please?

edit retag close merge delete

Sort by » oldest newest most voted

Hi! I think you must have assigned one too many of your variables (like assigning a value to RB) to come up with your last expression. Also, I don't see what predefined, lowercase q you're referring to.

In any case, here's roughly what I'd do. First, define the variables and the equation, and then solve it:

sage: var("F, Q, M, RB")
(F, Q, M, RB)
sage: deg = pi/180;
sage:
sage: eq = -2*F*cos(45*deg)-3*Q+4*RB*cos(45*deg)-RB*sin(45*deg)-M == 0
sage: eq
-sqrt(2)*F + 3/2*sqrt(2)*RB - M - 3*Q == 0
sage:
sage: solve(eq,RB)
[RB == 1/3*sqrt(2)*M + sqrt(2)*Q + 2/3*F]
sage: for sol in solve(eq,RB):
....:         print sol.rhs()
....:
1/3*sqrt(2)*M + sqrt(2)*Q + 2/3*F


Then solve it. By default, solve returns a list of equations, so you can loop over them like I did or index into them using [0], [1], [2], etc. I prefer the solution_dict style:

sage: solve(eq,RB, solution_dict=True)
[{RB: 1/3*sqrt(2)*M + sqrt(2)*Q + 2/3*F}]
sage: sols = solve(eq,RB, solution_dict=True)
sage: sols[0][RB]
1/3*sqrt(2)*M + sqrt(2)*Q + 2/3*F


in which you get a list of dictionaries, with each dictionary corresponding to a possible solution, and then you simply use the variable name as the index. We can then extract a solution:

sage: rb = sols[0][RB]
sage: rbval = rb.subs(M=23, Q=6, F=1/4)
sage: rbval
41/3*sqrt(2) + 1/6


and I've substituted some basically random M, Q, and F values into it. This can then be evaluated numerically (the evalf equivalent) by using the numerical_approx method:

sage: rbval.n()
19.4942520190990
sage: rbval.numerical_approx()
19.4942520190990
sage: rbval.n(100)
19.494252019098965666956412564


There are lots of ways to turn a symbolic expression into a "number", though. See my answer to this question on a similar subject.

Does that make sense?

more