Restrict python to use only the real number space

Viewed 172

In python when doing something like x=(-10)**(1/3) i get a complex number. I instead want to only see the one real x value which in this case would be approx -2.15. Now I do understand that I could import a math library like mpmath and generate all solutions (3 in the case), loop through them and find the one thats real. Im looking for a more elegant solution as I want to be able to create a program thats able to take in any sort of function and plug numbers into it.

here's a bit of code demonstrating what im trying to do

f= lambda x:x**(1/3)
print(f(-10))

in this case i get a complex number representing one of the 3 possible roots, but i only want the real root

2 Answers

The real cube root of a negative number is the negative value of the positive number's cube root:

>>> def cube_root(x):
...     return -pow(-x,1/3) if x < 0 else pow(x,1/3)
...
>>> cube_root(10)
2.154434690031884
>>> cube_root(-10)
-2.154434690031884

I think this should be enough :)

def f(x):
    if x < 0: return -pow(-x, 1/3)
    return pow(x, 1/3)
Related