Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
776 views
in Technique[技术] by (71.8m points)

math - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

(-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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...