以下内容是从维基百科Newton's method文章中的伪代码移植而来的:
#! /usr/bin/env python3
# https://en.wikipedia.org/wiki/Newton's_method
import sys
x0 = 1
f = lambda x: x ** 2 - 2
fprime = lambda x: 2 * x
tolerance = 1e-10
epsilon = sys.float_info.epsilon
maxIterations = 20
for i in range(maxIterations):
denominator = fprime(x0)
if abs(denominator) < epsilon:
print('WARNING: Denominator is too small')
break
newtonX = x0 - f(x0) / denominator
if abs(newtonX - x0) < tolerance:
print('The root is', newtonX)
break
x0 = newtonX
else:
print('WARNING: Not able to find solution within the desired tolerance of', tolerance)
print('The last computed approximate root was', newtonX)
问题
在python3.x中,如果给定某种形式的f
,是否有一种自动计算fprime
形式的方法?在
您可以用多种方法近似
fprime
。最简单的方法之一是:这里的想法是围绕点}在该区域上的变化近似为线性。我使用的算法称为中点法。你可以通过对大多数函数使用高阶多项式拟合来获得更精确的结果,但这将是更昂贵的计算。在
f
取样x
。取样区域(由dx
决定)应足够小,使{当然,如果你知道解析导数,你总是会更准确和高效。在
近似
f
在x
处的导数的一种常见方法是使用有限差分:h
的最佳选择取决于x
和{h = x*1e-15
的东西可能适合您的应用程序。另请参见implementing the derivative in C/C++。在可以使用secant method来避免近似f'。它的收敛速度没有牛顿的快,但它的计算成本更低,而且避免了计算导数的问题。在
回答
将函数
formula
和derivative
直接定义为import
之后。在使用
^{pr2}$formula
重新定义f
,方法是按照幂递增的顺序插入函数的系数。在重新定义
fprime
,以便使用函数derivative
和formula
自动创建它。在这应该可以解决Python3.x中从
f
自动计算fprime
的需求摘要
这是在自动计算
fprime
时生成原始答案的最终解决方案。在相关问题 更多 >
编程相关推荐