python - How to get the real cube root of a negative number in Python3? -
python 3.4 seemingly randomly decides whether returns real or complex root of number using **
operator:
>>> (863.719-2500) -1636.281 >>> -1636.281**(1/3) -11.783816270504108 >>> (863.719-2500)**(1/3) (5.891908135252055+10.205084243784958j)
is there way ensure real root when cube rooting rather 1 of complex ones?
in second case cube root getting evaluated first minus sign getting applied, hence real root.
that -1636.281**(1/3)
becomes -(1636.281**(1/3))
. , can use similar logic real cubic roots well.
but actually, when doing cubic root of negative numbers complex numbers in python.
>>> -1636.281**(1/3) -11.783816270504108 >>> (-1636.281)**(1/3) (5.891908135252055+10.205084243784958j)
if want real numbers can add code -
def cube(x): if x >= 0: return x**(1/3) elif x < 0: return -(abs(x)**(1/3))
Comments
Post a Comment