Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

negative pow in python

Tags:

python

math

pow

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 ?

like image 289
JuanPablo Avatar asked Nov 06 '10 19:11

JuanPablo


People also ask

How do you do a negative power in Python?

Answer. Yes, in Python, exponentiation does work with negative exponent values, the same way it would apply in mathematics. When performing exponentiation with a negative exponent, it is the same as getting the inverse of exponentiation done with the exponent as a positive value.

Does Math POW work with negative numbers?

The pow( ) method can be used to raise any number to any power. If exponent is negative, pow( ) returns 1 / ( base abs(exponent)).

Is there a negative function in Python?

negative() in Python. numpy. negative() function is used when we want to compute the negative of array elements. It returns element-wise negative value of an array or negative value of a scalar.

What is the negative symbol in Python?

A unary mathematical expression consists of only one component or element, and in Python the plus and minus signs can be used as a single element paired with a value to return the value's identity ( + ), or change the sign of the value ( - ).


2 Answers

(-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)
like image 79
kennytm Avatar answered Oct 23 '22 04:10

kennytm


Don't use pow, and make the exponent complex (add 0j to it). Here is an example:

In [15]: (-1.07)**(1.3+0j)
Out[15]: (-0.64182642880347307-0.88339829268567893j)

No need for math functions :)

like image 9
Gabi Purcaru Avatar answered Oct 23 '22 03:10

Gabi Purcaru