Python - 牛顿法

标签 python algorithm function

我是 Python 的新手,我需要做一个牛顿法脚本。

我一直在尝试这样做,但我总是收到错误或没有返回...

这是作业:


函数 newton(f, x, feps, maxit) 需要:

  • 一个函数f(x),
  • 函数 f(x) 的根的初始猜测 x
  • 允许的公差 feps,
  • 以及允许的最大迭代次数maxit

newton 函数应使用以下 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

我应该怎么做才能让它发挥作用?

最佳答案

您在 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/

相关文章:

python - 为什么我的 Tkinter 标签没有更新?

algorithm - 查找 SSE 寄存器中出现频率最高的元素

javascript - 有效检测图像尺寸

function - 如何创建一个为该语言添加新函数的处理库?

javascript - 动态改变功能可以吗?

python - 在同一 python 执行中多次调用 OptionParser.parse_args()

python - YouTube API社区数据用户名

python - 提取 SWIG 包装的 C++ 实例/指针以在 Cython 中使用

java - 用于表达式评估的 Dijkstra 双栈算法

java - 打乱 LinkedList 时出现 ArrayIndexOutOfBoundsException