real numbers become complex in python -


the code :

a = b/a b = c/a c = d/a  q = (a**2-3*b)/9 r = (2*a**3-9*a*b+27*c)/54  m = r**2-q**3  p = (3*b-a**2)/3 q = (2*a**3-9*a*b+27*c)/27  delta = (q/2)**2+(p/3)**3  if m <= 0 :     math import sqrt,acos,cos,pi      z = acos(r/sqrt(q**3))     x1 = -(2*sqrt(q)*cos(z/3))-a/3     x2 = -(2*sqrt(q)*cos((z+2*pi)/3))-a/3     x3 = -(2*sqrt(q)*cos((z-2*pi)/3))-a/3   elif delta > 0 :     math import sqrt     import cmath      u = ((-q/2)+sqrt(delta))**(1/3)     v = ((q/2)+sqrt(delta))**(1/3)      x1 = u-v-a/3     x2 = -(1/2)*(u-v)-a/3+(u+v)*(sqrt(3)/2)*cmath.sqrt(-1)     x3 = -(1/2)*(u-v)-a/3-(u+v)*(sqrt(3)/2)*cmath.sqrt(-1) 

it gives me wrong answers when enter :

a = 1 b = 1 c = -1 d = -1 m == 0      

but skips m , goes delta

and results :

x1 = 1.0 x2 = (-1+4.8e-09j) x3 = (-1-4.8e-09j) 

i don't know wrong ? suppose go m , x1 , x2 , x3 become real calculating in m

negative number raised fractional power either gives complex number (in python 3.x) (even odd power 1/3 or 1/5) or value error in python 2.x (valueerror: negative number cannot raised fractional power).

example -

>>> (-27)**(1/3) (1.5000000000000004+2.598076211353316j) 

you need handle case yourself, example, if doing power of (1/3) , have handle -

x = -27 if x < 0:     pow = -((-x) **(1/3)) elif x > 0:     pow = x **(1/3) else:     pow = 0 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -