SciPy的牛顿函数没有找到交点

SciPy's Newton function does not find the intersection point

我试图理解为什么下面的代码不是 return -1.17 而是 returns -6.67e-09。这个数字实际上告诉我什么?

如果我将估计值从 0 更改为 -1,它 会正确计算 -1.17。但是,如果我必须为 100 多个不同的函数执行此操作,我将不得不为每个函数编写一个 while 循环,这会使计算过程非常缓慢。

这是简单的计算方式还是我缺少这种情况下的特定参数?

from scipy.optimize import newton


def f(x):
    return x**2-3


def g(x):
    return x**3

def insection():
    def difference(x):
        return g(x) - f(x)
    insection_point_value = newton(difference, 0)

    return insection_point_value 

print(insection())
Returns: -6.665555511432543e-09
Has to be: -1.1745594102929802

您可以提供函数导数:fprime - 参见 docs。这应该会使搜索更加稳定。

Newton-Raphson 方法是一种为实值函数的根找到良好近似值的方法(在您的例子中:f(x) =x**3 - x**2 + 3)。这是一种迭代算法,在很大程度上依赖于起点(x0 我是说)。

所以,我建议使用多个起点,然后求出最常见的根。这段代码解释了我的意思:

>>> from scipy.optimize import newton
>>> from collections import Counter


>>> # using [-10, -9, -8, ..., 8, 9, 10] as starting point(s)
>>> roots = newton(lambda x: x**3 - x**2 +3, range(-11, 11))

>>> # find the most common root
>>> root, count = Counter(roots).most_common(1)[0]
>>> root
-1.17455941029298
>>> count
17

这意味着在22个起点中,有17个收敛到-1.17

Newton-Raphson 方法(NR) 对您提供的初始值高度敏感。

查看差分函数图:
函数在 x = 0 处的导数是 0NR 是一种迭代方法,无法使用零导数从初始点 x0 = 0 前进。这就是为什么它继续停留在那里,而不是向预期的点汇聚。试试 x0 = -0.1 就可以了,或者任何低于此的方法。
任何x > 0都会继续失败,因为在x = 0.667处还有一个零导数,迭代的方法会滑入山谷,通俗点说。

您得到的奇怪的十进制值(而不是 0)是浮点数学、函数的离散值或两者的组合的产物。