本文介绍了python中的负战俘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个问题
>>> import math
>>> math.pow(-1.07,1.3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
有什么建议吗?
推荐答案
(-1.07)将不是实数,因此出现Math域错误.
(-1.07) will not be a real number, thus the Math domain error.
如果需要复数,则必须将a 重写为e ,例如
If you need a complex number, a must be rewritten into e, e.g.
>>> import cmath
>>> cmath.exp(1.3 * cmath.log(-1.07))
(-0.6418264288034731-0.8833982926856789j)
如果您只想返回NaN,请捕获该异常.
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
顺便说一句,在Python中,通常内置的a ** b
用于提高功能,而不是math.pow(a, b)
.
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)
这篇关于python中的负战俘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!