SciPy的牛顿函数找不到相交点

问题描述 投票:0回答:3

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

如果我将估算值从0更改为-1,它does会正确计算-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

“绘图”

python scipy newtons-method scipy-optimize
3个回答
1
投票

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

检查差异函数的图形:graphx = 0处的函数的导数为0NR是一种迭代方法,不能使用零导数从初始点x0 = 0开始。这就是为什么它继续停留在该位置,而不是收敛到预期点。尝试x0 = -0.1,它会起作用,或者比这更小的作用。任何x > 0都将继续失败,因为在x = 0.667处还有另一个零导数,并且迭代方法将滑入谷底以使用外行语言。

您获得的奇怪的十进制值(而不是0是浮点数的人工产物,该函数的离散值或两者的组合。


1
投票

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.