简体   繁体   中英

solve cubic equations ,sympy

I have a project that one step of the process of it is to solve R(k,d,a), where k means kth step.

My friend suggest me to do this in sympy ,but I don't know how to do it.

from sympy import *
k= symbols('k')
d= symbols('d')
a= symbols('a')
R= function('R')(k,d,a)
print R`

In fact I don't know how to define a function in sympy with class method... and this expression is failure.

def R(k,d,a):

k:# of nth process

d:parameter in order to initializing

R(0,d,a) should be given

    if k==0:
       return 100*d
    r=d*(1-(1-(d/R(k-1,d,a))**2)**0.5)**0.5
    B=-3/2*d
    D=(R(k-1,d,a))**3*(3*a*d/R(k-1,d,a)-2)+r**2*(r-3/2*d)

here I define R(k,d,a) with R(k-1,d,a),is it appropriate?

x^3+Bx^2+Cx+D=0 ,where c=0

x represent R(k,d,a) here.

    x=symbols('x')
    y=solve (x**3+x**2*B+D,x)
    return max(y)

Here I want a list of y,and asking y in real number.

Later return the biggest one.

But I don't know how to realize it.

Finally,for each k ,I will need the other function to give a value that R(k,d,a) will be a parameter in it.I think I can do it by my self with for loop,it is not hard for me.

What is the hardest is how to get R(k,d,a).

I don't need complex root .But if I want ,how can I get them ? Thank you for watching!

What you have looks basically OK. Three suggestions, however:

  1. make sure your function always returns a SymPy value, eg don't return 100*d since d might be an int; return S(100)*d ;
  2. wherever you have division make sure that it is not suffering from Python trunction wherein 1/2 -> 0. eg write B = -S(3)/2*d instead of what you have (and use that B in your expression for D , writing (r+B) at the end of it;
  3. max will not be able to sort the roots if complex roots are present so it would be better to select the real ones by hand: y=[i for i in solve (x**3+x**2*B+D,x) if i.is_real] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM