Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difficulty in using sympy solver in python

Tags:

python

sympy

Please run the following code

    from sympy.solvers import solve
    from sympy import Symbol
    x = Symbol('x')
    R2 = solve(-109*x**5/3870720+4157*x**4/1935360-3607*x**3/69120+23069*x**2/60480+5491*x/2520+38-67,x)
    print R2

The output of the code is

[2*CRootOf(109*x**5 - 4157*x**4 + 50498*x**3 - 184552*x**2 - 527136*x + 3507840, 0), 2*CRootOf(109*x**5 - 4157*x**4 + 50498*x**3 - 184552*x**2 - 527136*x + 3507840, 1), 2*CRootOf(109*x**5 - 4157*x**4 + 50498*x**3 - 184552*x**2 - 527136*x + 3507840, 2), 2*CRootOf(109*x**5 - 4157*x**4 + 50498*x**3 - 184552*x**2 - 527136*x + 3507840, 3), 2*CRootOf(109*x**5 - 4157*x**4 + 50498*x**3 - 184552*x**2 - 527136*x + 3507840, 4)]

Can someone explain what the answer represent and how to get the output in conventional form i.e. say if the answer is 0.1,0.2,0.3,0.1,0.4 sympy usually outputs the answer as [0.1,0.2,0.3,0.1,0.4]

like image 598
vikas_hada Avatar asked Apr 23 '16 13:04

vikas_hada


2 Answers

To get numerical approximations in an answer, you can use N(). Since you have multiple solutions, you can loop through the list. I have used an easier equation since yours takes a while ...

Try this:

from sympy.solvers import solve

from sympy import Symbol, N
x = Symbol('x')
#R2 = solve(-109*x**5/3870720+4157*x**4/1935360-3607*x**3/69120+23069*x**2/60480+5491*x/2520+38-67,x)
R2 = solve(x**2+2*x-4,x)
print R2
print [N(solution) for solution in R2]

[EDIT]: As mentioned in the comments below, the fifth order equation can only be solved after upgrading sympy (to 1.0 in my case).

like image 163
tfv Avatar answered Oct 21 '22 01:10

tfv


SymPy's solve only gives symbolic solutions. CRootOf is a way of symbolically representing roots of polynomials whose roots can't be represented by radicals. If you are only interested in numeric solutions, you can use N on each of the terms as suggested by @tfv, or use nsolve, which solves the equation numerically. In general symbolic solve may be overkill if you only care about numeric solutions.

like image 2
asmeurer Avatar answered Oct 21 '22 00:10

asmeurer