Why is (-27) ** (1.0 / 3.0) not -3.0 in Python?

In math, you are allowed to take the cubic roots of negative numbers, because a negative number times two other negative numbers results in a negative number. Reducing something to a fractional power of 1 / n is the same as the nth root. Therefore, the cubic root of -27 or (-27) ** (1.0 / 3.0) comes out to -3.

But in Python 2, when I enter (-27) ** (1.0 / 3.0), this gives me an error:

Traceback (most recent call last):
  File "python", line 1, in <module>
ValueError: negative number cannot be raised to a fractional power

Python 3 does not throw an exception, but it gives a complex number that doesn't look something like -3:

>>> (-27)**(1.0/3.0)
(1.5000000000000004+2.598076211353316j)

Why am I not getting a result that gives mathematical meaning? And is there a workaround for this?

+4
source share
3 answers

-27 ( ), (-27)**(1.0/3.0) , " -27".

-, 1.0/3.0 - .

0.333333333333333314829616256247390992939472198486328125

Python .

-, ** , - . . , n- ; , (-27) ^ (1/3) , , -3.

Python 2 , , , , , , , :

def real_nth_root(x, n):
    # approximate
    # if n is even, x must be non-negative, and we'll pick the non-negative root.
    if n % 2 == 0 and x < 0:
        raise ValueError("No real root.")
    return (abs(x) ** (1.0/n)) * (-1 if x < 0 else 1)

exp log, :

import cmath
def principal_nth_root(x, n):
    # still approximate
    return cmath.exp(cmath.log(x)/n)

complex ( exp-log ):

>>> complex(-27)**(1.0/3.0)
(1.5000000000000004+2.598076211353316j)

Python 3 , n - y == 1.0/n:

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

, , pow , float .

, , :

>>> (-27+0j)**(1.0/3.0)
(1.5000000000000004+2.598076211353316j)
>>> (-27)**(complex(1.0/3.0))
(1.5000000000000004+2.598076211353316j)

, numpy:

>>> import numpy as np
>>> np.roots([1, 0, 0, 27])
array([-3.0+0.j        ,  1.5+2.59807621j,  1.5-2.59807621j])

[1, 0, 0, 27] 1xΒ³ + 0xΒ² + 0x + 27.

+2

I don't think Python, or your version, supports this feature. I embedded the same equation in my Python interpreter (IDLE) and solved it without errors. I am using Python 3.2.

0
source

Source: https://habr.com/ru/post/1685698/


All Articles