我只是在测试 Numerical Methods in Engineering with 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)
当我运行它时,它显示以下错误:
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
我已将其缩小到日志,因为当我删除日志并添加不同的功能时,它可以工作。我认为这是因为对基地的某种干扰,我不知道是怎么回事。任何人都可以提出解决方案吗?
最佳答案
您的代码正在对小于或等于零的数字执行 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
在不知道您的 newtonRaphson2
函数做什么的情况下,我不确定我能猜出无效的 x[2]
值的来源,但希望这会导致你在正确的轨道上。
关于python - 值错误 : math domain error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15890503/