数值错误:数学域

2024-04-26 10:32:48 发布

您现在位置: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)

当我运行它时,它显示以下错误:

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

我把它缩小到日志,因为当我删除日志并添加一个不同的函数时,它就工作了。我想是因为基地受到了某种干扰,我想不出是怎么回事。有人能提出解决办法吗?


Tags: 方法fromimportnumpyloglendefzeros
2条回答

你在尝试做一个非正数的对数。

对数在被赋予一个数和它被提升到的幂之后计算出基数。log(0)意味着提升到2幂的东西是0。指数永远不会导致0,这意味着log(0)没有答案,因此抛出math domain error

*注意:0^0可以导致0,但也可以同时导致1。这个问题争论得很激烈。

您的代码正在对小于或等于零的数字执行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]值来自何处,但希望这会引导您走上正确的轨道。

相关问题 更多 >