【发布时间】:2013-11-18 12:49:41
【问题描述】:
我是 Python 新手,我需要编写一个牛顿法脚本。
我一直在尝试这样做,但我不断收到错误或没有返回...
这是作业:
一个函数newton(f, x, feps, maxit),它需要:
- 一个函数
f(x), - 对函数 f(x) 根的初始猜测
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(有更优雅的方法,但出于评估的目的,这是我们推荐的最直接的方法)。
如果 |f(x)| 需要 maxit 或更少的迭代次数要小于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
我应该怎么做才能让它工作?
【问题讨论】:
-
什么错误?是作业吗?
-
请注意,无论发生什么,newton() 方法都会在一个 while 循环后返回!
-
仅供参考,stackoverflow 不是作业解答网站。如果您遇到错误,请准确指出错误是什么。追溯总是好的。限定“完全错误”的含义。或许提供一些输入、预期输出以及您的算法产生的结果。
-
那么,这是一个关于如何实现算法的问题(这使它成为一个家庭作业问题,而不是一个很好的候选者),还是一个关于为什么你在 Python 中具体实现算法的问题不起作用(也许不是一个好问题,但更好)?如果是前者,请询问您的 TA。 :) 如果是后者,您能否提供以下内容:函数 f 的代码(您将其省略,但它是最重要的部分!),以及您使用的 Python 版本是什么?
-
你在这条线上到底在做什么?
fprime(x) = derivative(f, x)据我所知,这对 Python 来说是无效的语法,因为您不能分配给函数调用。也许您只想拥有x = x - f(x) / derivative(f, x)。然后当 while 循环完成时,返回 x?根据算法,您应该修改 x 在您当前的newton函数中没有做的事情。