我有这个问题
>>> import math
>>> math.pow(-1.07,1.3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
Run Code Online (Sandbox Code Playgroud)
有什么建议吗?
ken*_*ytm 24
(-1.07)1.3将不是实数,因此Math域错误.
如果您需要复数,则必须将b重写为e b ln a,例如
>>> import cmath
>>> cmath.exp(1.3 * cmath.log(-1.07))
(-0.6418264288034731-0.8833982926856789j)
Run Code Online (Sandbox Code Playgroud)
如果您只想返回NaN,请捕获该异常.
>>> 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
Run Code Online (Sandbox Code Playgroud)
顺便说一下,在Python中,内置通常a ** b用于提高功率,而不是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)
Run Code Online (Sandbox Code Playgroud)
不要使用pow,并使指数复杂(添加0j到它).这是一个例子:
In [15]: (-1.07)**(1.3+0j)
Out[15]: (-0.64182642880347307-0.88339829268567893j)
Run Code Online (Sandbox Code Playgroud)
不需要数学函数:)