计算 Newton-Raphson 方法中的迭代次数

Counting iterations in Newton-Raphson's method

我在一个简单的程序中工作,该程序使用 Newton-Raphson 方法计算任何给定函数的根。在这个程序中,我必须打印找到的根和进行的迭代次数。程序本身很好,我可以找到任何给定函数的根,但我无法正确计算迭代次数。它总是超过最大值 5。迭代次数或比它少 1。这是 C++ 中的代码:

#include <iostream>
#include <math.h>
#include <stdlib.h>

using namespace std;

double f(float x)
{
  double function1;
  function1 = exp(x)- 4*pow(x,2); // given function
  return function1;
}

double derivative(float x)
{
  double derivative1;
  derivative1 = exp(x) - 8*x; // derivative of given function
  return derivative1;
}


void newtonMethod(double x0, double error, int N)
{
  double xNext, xPrevious, root;
  int k;

  xPrevious = x0;

  for(int i = 0; i < N || f(xNext) > error; i++)
  {
    xNext = xPrevious - (f(xPrevious)/derivative(xPrevious)); // calculates the next value of x
    xPrevious = xNext;
    root = xNext;
    k = i;
}
cout << endl;
cout << "Iterations made: " << k << endl;
cout << endl;
cout << endl;
cout << endl;
cout << "Root is:  " << root << endl;


}

int main()
{
  double x0, error;
  int N; // max. number of iterations you can do
  cout << "Enter x0: ";
  cin >> x0;
  cout << "Enter the error: ";
  cin >> error;
  cout << "Enter the max. number of iterations: ";
  cin >> N;
  newtonMethod(x0, error, N);
 }

而且我很确定错误出在这段代码中:

;i < N || f(xNext) > error;

如果我 运行 这个程序并输入 N = 100,它显示正确的根但它打印 "Iterations made = 99" 但这是错误的。我该怎么做才能打印正确的迭代次数?例如,对于上面程序中的函数 (e^x - 4x²),如果我输入 x0 = 0.5 和错误 = 0.0001,它应该在第四次迭代时停止。如何解决?

回答您的问题,这就是为什么以下代码不起作用的原因:

;i < N || f(xNext) > error;

只是因为在 for 循环条件中,计算的是 continuing 条件,而不是 stopping健康)状况。 在上面的代码中,您告诉编译器的是:继续循环,只要i < N为真或f(xNext) > error为真。因此,当您输入 x0 = 0.5error = 0.0001N = 100 时,循环所做的是它不会停止,直到两个条件都为假,即当 i 达到 N 并且 f(x) 中的公差小于 error.

现在,解决方案就是将 || 运算符替换为 && 运算符。像这样:

i < N && f(xNext) > error;

但是,您的 xNext 未初始化。因为你的 xNextxPrevious 在每个循环结束时是相等的,所以我会简单地用 xPrevious 代替。此外,正如@Rathat 所写,评估您对 f(x) 的容忍度应该取其绝对值,因此:

i < N && abs(f(xPrevious)) > error;

最后,您应该将迭代次数输出为 k + 1,因为您从 i = 0 开始。

这应该可以解决您的问题。

谢谢大家的回答。我发现除了@yuxiangDev 解释得很好的 for 条件背后的逻辑之外还有什么问题。尽管@RatHat 代码完全正确,但错误出在我使用的 math.h 库中。我尝试使用 <cmath> 并且效果非常好!哈哈