IMI
IMI

Reputation: 105

Calculate expression using SymPy in Python

I'm experimenting with SymPy, and I've hit upon an issue I can't work out.

My problem is in converting an expression to a number:

from sympy import *
a=1
b=3
x=15
y=30
v=5
w=10

    t = Symbol('t', positive=True)
k=solve( (a**2)*(y**2) + 2*a*t*v*(y**2) + (b**2)*(x**2) + 2*b*t*w*(x**2) + (t**2)*(v**2)*(y**2) + (t**2)*(w**2)*(x**2)
- ( (a**2)*(b**2) + 2*(a**2)*b*t*w + (a**2)*(t**2)*(w**2) + 2*a*(b**2)*t*v + 4*a*b*(t**2)*v*w + 2*a*(t**3)*v*(w**2) +
(b**2)*(t**2)*(v**2) + 2*b*(t**3)*(v**2)*w + (t**4)*(v**2)*(w**2) ) , t)

The value of k is:

k = {list} : [-1/4 + sqrt(3601 + 120*sqrt(901))/20]

How can I get the value of k as a number, like 7.2, and not an expression?

Upvotes: 3

Views: 91

Answers (1)

jedwards
jedwards

Reputation: 30210

sympy.solve() returns a list, so you'll need to somehow get the expressions out of that list, and you can call <expression>.evalf() to get a floating point representation of the solution:

So either:

print(k[0].evalf())

or

for sol in k:
    print(sol.evalf())

will display: 3.99352431498656

Upvotes: 2

Related Questions