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

前端 未结 3 2027
耶瑟儿~
耶瑟儿~ 2020-12-21 01:46

In math, you are allowed to take cubic roots of negative numbers, because a negative number multiplied by two other negative numbers results in a negative number. Raising so

3条回答
  •  借酒劲吻你
    2020-12-21 02:22

    The type coercion rules documented by builtin pow apply here, since you're using a float for the exponent.

    Just make sure that either the base or the exponent is a complex instance and it works:

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

    To find all three roots, consider numpy:

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

    The list [1, 0, 0, 27] here refers to the coefficients of the equation 1x³ + 0x² + 0x + 27.

提交回复
热议问题