c++ - C/C++ - 牛顿法的迭代计数器

标签 c++ c function printf

我创建了一个运行牛顿法的函数,用于逼近函数(定义为 f)的解。我的函数返回更好的根近似值就好了,但是它不会正确显示函数中执行的迭代次数。

这是我的代码:

#include <stdio.h> 
#include <math.h> 
#include <cstdlib>
#include <iostream>

double newton(double x_0, double newtonaccuracy);

double f(double x);

double f_prime(double x);

int main() 
{
   double x_0;  

   double newtonaccuracy;  

   int converged;  

   int iter;

   printf("Enter the initial estimate for x : ");

   scanf("%lf", &x_0);

   _flushall();

   printf("\n\nEnter the accuracy required : ");

   scanf("%lf", &newtonaccuracy);

   _flushall();


   if (converged == 1) 
      {
        printf("\n\nNewton's Method required %d iterations for accuracy to %lf.\n", iter, newtonaccuracy);

        printf("\n\nThe root using Newton's Method is x = %.16lf\n", newton(x_0, newtonaccuracy));
      } 

   else 
      {
        printf("Newton algorithm didn't converge after %d steps.\n", iter);
      }



      system("PAUSE");
} 


double newton(double x_0, double newtonaccuracy) 
{
   double x = x_0;

   double x_prev;

   int iter = 0;


   do 
   {
      iter++;


      x_prev = x;

      x = x_prev - f(x_prev)/f_prime(x_prev);

   } 
   while (fabs(x - x_prev) > newtonaccuracy && iter < 100);

   if (fabs(x - x_prev) <= newtonaccuracy)
   {
      int converged = 1;
   }  
   else
   {
      int converged = 0; 
   }   




    return x;
}  


double f(double x) {
       return ( cos(2*x) - x );
}  

double f_prime(double x) 
{
   return ( -2*sin(2*x)-1 ); 
}  

要尽可能具体,它是行:

printf("\n\nNewton's Method required %d iterations for accuracy to %lf.\n", iter, newtonaccuracy);

这给我带来了麻烦。每次我运行这个程序时,它都会说“牛顿法需要 2686764 次迭代......”但是这不可能是真的,前提是我已经正确编码(我的代码允许的最大迭代次数是 100)。

最佳答案

main 中使用的变量 iter 没有初始化,也没有在 newton 函数中使用,这里你使用了一个局部变量 iter 。您需要通过引用将 iter 传递给 newton,或者想办法从函数中返回它。

这是一个通过引用获取一些参数并修改它们的函数示例:

double foo(double& initial_value, int& iterations)
{
  initial_value *= 3.14159;
  iterations = 42;
  return initial_value/2.;
}

调用方:

double x + 12345.;
int iter = 0;
double y = foo(initial_value, iter);

关于c++ - C/C++ - 牛顿法的迭代计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13432710/

相关文章:

c - 没有 GdkModifierType 的 gtk_widget_add_accelerator

c - 过去的手动优化(C语言)

r - 如何让 lapply 输出从函数获得的 2 个对象

c++ - 当我尝试使用按钮添加 QTabWidget 时 Appcrash

c - 随机词生成器中的奇怪输出

javascript - 返回一个使用父函数中声明的 var 的函数

python - 在用户定义的函数中访问全局框架

C++11/Boost 随机库,在循环的指定点开始生成

c++ - 如何在 C++ 中使用构造函数(只是构造函数)初始化类中的大型私有(private)数组?

c++ - 计算 3 维中的相机 LookAt 位置 (DirectX)