我是 Python 新手,我需要做一个 Newton Method 脚本。
我一直在尝试这样做,但我不断收到错误或没有返回......
这是作业:
一个函数newton(f, x, feps, maxit)
这需要:
f(x)
, x
对于函数 f(x) 的根,feps
, maxit
. 牛顿函数应使用以下 Newton-Raphson 算法:
while |f(x)| > feps, do
x = x - f(x) / fprime(x)
在哪里
fprime(x)
是位置 x
处的一阶导数 (df(x)/dx) 的近似值.您应该使用本实验训练部分的导数函数。确保将导数函数定义从 training7.py 复制到 lab7.py 中(有更优雅的方法,但出于评估的目的,这是我们推荐的最直接的方法)。
如果
maxit
|f(x)| 需要或更少的迭代变得小于 feps
,则应返回 x 的值:In [ ]: def f(x):
....: return x ** 2 - 2
....:
In [ ]: newton(f, 1.0, 0.2, 15)
Out[ ]: 1.4166666666783148
In [ ]: newton(f, 1.0, 0.2, 15) - math.sqrt(2)
Out[ ]: 0.002453104305219611
In [ ]: newton(f, 1.0, 0.001, 15)
Out[ ]: 1.4142156862748523
In [ ]: newton(f, 1.0, 0.001, 15) - math.sqrt(2)
Out[ ]: 2.1239017571339502e-06
In [ ]: newton(f, 1.0, 0.000001, 15) - math.sqrt(2)
Out[ ]: 1.5949463971764999e-12
这是我试图做的,但这是完全错误的:
def derivative(f, x):
"""A function derivative(f, x) which computes a numerical approximation of
the first derivative of the function f(x) using central differences."""
R = (f(x + (10 ** -6) / 2.0) - f(x - (10 ** -6) / 2.0)) / (10 ** -6)
return R
def newton(f, x, feps):
"""A function newton(f, x, feps, maxit) which takes a function f(x) and
an initial guess x for the root of the function f(x), an allowed tolerance
feps and the maximum number of iterations that are allowed maxit. The
newton function should use the following Newton-Raphson algorithm:
while |f(x)| > feps, do
x = x - f(x) / fprime(x)
where fprime(x) is an approximation of the first derivative (df(x)/dx) at
position x."""
while abs(f(x) > feps):
fprime(x) = derivative(f, x)
Result = x - f(x) / fprime(x)
return Result
我应该怎么做才能让它工作?
最佳答案
您在 while 循环的第一步后返回结果
while abs(f(x) > feps):
fprime(x) = derivative(f, x)
Result = x - f(x) / fprime(x)
return Result
像这样做
while abs(f(x) > feps):
fprime(x) = derivative(f, x)
Result = x - f(x) / fprime(x)
return Result
附言但我不确定您的代码是否有效
fprime(x) = derivative(f, x)
- 这不是 python 的正确语法我认为这段代码必须更正确
while abs(f(x) > feps):
x = x - f(x) / derivative(f, x)
return x
对于牛顿法,您必须得到类似递归的结果并检查最佳近似值。
f(x)
Xn+1 = Xn - -----
f'(x)
当你最适合你的时候,你会在循环中检查
附言对不起我的伪数学代码
关于Python - 牛顿法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20048235/