python 中的负 pow
我有这个问题
>>> import math
>>> math.pow(-1.07,1.3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
有什么建议吗?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
(-1.07)1.3 不是实数,因此会出现数学域错误。
如果您需要一个复数,则 ab 必须重写为 eb ln a,例如,
如果您只想返回 NaN,请捕获该异常。
顺便说一句,在 Python 中,通常使用内置的
a ** b
来提高幂,而不是math.pow(a, b)
。(-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.
If you just want to return NaN, catch that exception.
BTW, in Python usually the built-in
a ** b
is used for raising power, notmath.pow(a, b)
.不要使用 pow,并将指数设为复数(添加
0j
)。这是一个例子:不需要数学函数:)
Don't use pow, and make the exponent complex (add
0j
to it). Here is an example:No need for math functions :)
复数(和负数)的非整数幂涉及一个重要的微妙之处。指数函数在实线上单射;即 exp(a) = exp(b) 意味着 a = b。在复平面上情况并非如此。由于 exp(2*pi*i) = 1,因此指数函数是 2*pi*i 周期的。
这就引出了一个问题:我们使用日志函数的哪个分支?该问题是复杂分析的核心问题之一。
Python 正在智能地应对这种情况。除非您明确使用其复数构造函数,否则您将进行实数交易。由于负数的分数幂永远不是真实的,Python 会适当地抛出异常。
Noninteger powers of complex (and negative) numbers involve an important subtlety. The exponential function is injective on the real line; i.e. exp(a) = exp(b) implies a = b. This is NOT so on the complex plane. Since exp(2*pi*i) = 1, the exponential function is 2*pi*i-periodic.
This leads to the problem: Which branch of the log function do we use? Said question is one of the central questions of complex analysis.
Python is responding intelligently to this situation. Unless you explicitly use its complex number constructor, you are going to be trafficking in reals. Since fractional powers of negatives are NEVER real, Python is appropriately throwing an exception.
我正在使用 python 2.5.4,我得到这个:
你使用什么 python 版本?
I am using python 2.5.4 and I get this:
What python version are you using?
从这篇文章的标题来看,幂为负,您是否可能实际上想要 1.3-1.07 而不是 -1.071.3?
From the title of this post indicating that the power is negative, is it possible that you actually wanted 1.3-1.07 rather than -1.071.3?
负基数的幂是复数。
这是一个解释如何修复它的示例:
Powers of negative bases are complex numbers.
Here's an example that explains how to fix it: