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 ?
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.
The pow( ) method can be used to raise any number to any power. If exponent is negative, pow( ) returns 1 / ( base abs(exponent)).
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.
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 ( - ).
(-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)
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With