我试图理解为什么下面的代码不返回-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
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
您可以提供函数导数:fprime
-参见docs。这应该使搜索更加稳定。