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

标签 c++ count newtons-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 循环条件中,评估的是一个继续条件,而不是一个停止条件。 在上面的代码中,您要告诉编译器的是:继续循环,只要达到i < N 之一。为真或 f(xNext) > error是真的。因此,当您输入 x0 = 0.5 , error = 0.0001N = 100 ,循环所做的是它不会停止,直到两个条件都为假,即当 i 达到 N 并且 f(x) 中的公差小于错误

现在,解决方案就是简单地交换 ||接线员到 &&运算符(operator)。像这样:

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

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

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

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

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

关于c++ - 计算 Newton-Raphson 方法中的迭代次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40096156/

相关文章:

C++:牛顿拉夫森和重载函数

c++ - 将类映射到 mySql 表,而不在 cpp 中使用 ODB 或其他框架

c++ - Linux 控制台操作函数

c++ - 交叉编译错误 "arm-none-eabi-g++ cannot find entry symbol"

list - 如何计算Python中零的数量?

c++ - 二进制表达式 ('double(*)(double' 和 'double' 的无效操作数)

c++ - 在嵌入式系统上从 DOS 切换到 Linux

SQL计数麻烦

sql - 按价格范围分组

c - 尝试在 C 中通过 newton raphson 方法找到近似根?