Search code examples
pythonmathpow

negative pow in python


I have this problem

>>> import math
>>> math.pow(-1.07,1.3)  
Traceback (most recent call last):  
  File "<stdin>", line 1, in <module>  
ValueError: math domain error

any suggestion ?


Solution

  • (-1.07)1.3 will not be a real number, thus the Math domain error.

    If you need a complex number, ab must be rewritten into eb ln a, e.g.

    >>> import cmath
    >>> cmath.exp(1.3 * cmath.log(-1.07))
    (-0.6418264288034731-0.8833982926856789j)
    

    If you just want to return NaN, catch that exception.

    >>> import math
    >>> def pow_with_nan(x, y):
    ...   try:
    ...     return math.pow(x, y)
    ...   except ValueError:
    ...     return float('nan')
    ...
    >>> pow_with_nan(1.3, -1.07)   # 1.3 ** -1.07
    0.755232399659047
    >>> pow_with_nan(-1.07, 1.3)   # (-1.07) ** 1.3
    nan
    

    BTW, in Python usually the built-in a ** b is used for raising power, not math.pow(a, b).

    >>> 1.3 ** -1.07
    0.755232399659047
    >>> (-1.07) ** 1.3
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: negative number cannot be raised to a fractional power
    >>> (-1.07+0j) ** 1.3
    (-0.6418264288034731-0.8833982926856789j)