Python ValueError:数学域错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15890503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ValueError: math domain error
提问by ramanunni.pm
I was just testing an example from Numerical Methods in Engineering with Python.
我只是在用 Python测试工程中的数值方法中的一个例子。
from numpy import zeros, array
from math import sin, log
from newtonRaphson2 import *
def f(x):
f = zeros(len(x))
f[0] = sin(x[0]) + x[1]**2 + log(x[2]) - 7.0
f[1] = 3.0*x[0] + 2.0**x[1] - x[2]**3 + 1.0
f[2] = x[0] + x[1] + x[2] -5.0
return f
x = array([1.0, 1.0, 1.0])
print newtonRaphson2(f,x)
When I run it, it shows the following error:
当我运行它时,它显示以下错误:
File "example NR2method.py", line 8, in f
f[0] = sin(x[0]) + x[1]**2 + log(x[2]) - 7.0
ValueError: math domain error
I have narrowed it down to the log as when I remove log and add a different function, it works. I assume it is because of some sort of interference with the base, I can't figure out how. Can anyone suggest a solution?
我已将其缩小到日志,因为当我删除日志并添加不同的功能时,它可以工作。我认为这是因为对基地的某种干扰,我不知道是怎么回事。任何人都可以提出解决方案吗?
采纳答案by Blckknght
Your code is doing a logof a number that is less than or equal to zero. That's mathematically undefined, so Python's logfunction raises an exception. Here's an example:
您的代码正在执行一个log小于或等于零的数字。这在数学上是未定义的,因此 Python 的log函数会引发异常。下面是一个例子:
>>> from math import log
>>> log(-1)
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <module>
log(-1)
ValueError: math domain error
Without knowing what your newtonRaphson2function does, I'm not sure I can guess where the invalid x[2]value is coming from, but hopefully this will lead you on the right track.
在不知道您的newtonRaphson2函数做什么的情况下,我不确定我能猜出无效x[2]值的来源,但希望这会引导您走上正确的轨道。
回答by Eric Xue
You are trying to do a logarithm of something that is not positive.
您正在尝试对非正数做对数。
Logarithms figure out the base after being given a number and the power it was raised to. log(0)means that something raised to the power of 2is 0. An exponent can never result in 0*, which means that log(0)has no answer, thus throwing the math domain error
对数在给定一个数字后计算底数和它的乘方。log(0)意味着某事物的幂2是0。指数永远不会导致0*,这意味着log(0)没有答案,因此抛出math domain error
*Note: 0^0can result in 0, but can also result in 1at the same time. This problem is heavily argued over.
*注:0^0可以导致0,但也可以同时导致1。这个问题争论不休。
回答by Catalina Chircu
You may also use math.log1p.
您也可以使用math.log1p.
According to the official documentation:
根据官方文档:
math.log1p(x)
Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.
math.log1p(x)
返回 1+x(以 e 为底)的自然对数。结果的计算方式对于接近零的 x 是准确的。
You may convert back to the original value using math.expm1which returns eraised to the power x, minus 1.
您可以使用math.expm1返回e的 x 次方减去 1将其转换回原始值。

