python中的负功率 [英] negative pow in python

查看:28
本文介绍了python中的负功率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题

<预><代码>>>>导入数学>>>math.pow(-1.07,1.3)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中ValueError:数学域错误

有什么建议吗?

解决方案

(-1.07)1.3 将不是实数,从而导致数学域错误.

如果需要复数,ab必须改写成eb ln a,例如

<预><代码>>>>导入 cmath>>>cmath.exp(1.3 * cmath.log(-1.07))(-0.6418264288034731-0.8833982926856789j)

如果您只想返回 NaN,请捕获该异常.

<预><代码>>>>导入数学>>>def pow_with_nan(x, y):... 尝试:...返回 math.pow(x, y)... 除了 ValueError:... return float('nan')...>>>pow_with_nan(1.3, -1.07) # 1.3 ** -1.070.755232399659047>>>pow_with_nan(-1.07, 1.3) # (-1.07) ** 1.3南

顺便说一句,在 Python 中通常内置的 a ** b 用于提高功率,而不是 math.pow(a, b).

<预><代码>>>>1.3 ** -1.070.755232399659047>>>(-1.07) ** 1.3回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中ValueError:负数不能被提升到分数幂>>>(-1.07+0j) ** 1.3(-0.6418264288034731-0.8833982926856789j)

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 ?

解决方案

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

这篇关于python中的负功率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆