C/C++ - 牛顿方法的迭代计数器
C/C++ - Iteration counter for Newton's Method
我创建了一个运行牛顿方法的函数,用于将解近似为函数(定义为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("nnEnter the accuracy required : ");
scanf("%lf", &newtonaccuracy);
_flushall();
if (converged == 1)
{
printf("nnNewton's Method required %d iterations for accuracy to %lf.n", iter, newtonaccuracy);
printf("nnThe root using Newton's Method is x = %.16lfn", 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("nnNewton'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++中迭代 2D 容器的最干净方法
- C++11 迭代向量的新方法?
- 在C++上实现高斯赛德尔迭代方法
- 使用迭代器替换映射中的常量项的方法
- C++:std::ofstream 方法 open() 在第二次迭代时擦除打开的 ifstream 文件
- 在unordered_multimap中精确迭代一次每个键的有效方法
- 向后迭代 std::array 或 std::vector 的正确方法是什么?
- 创建可以遍历 std::map 值的通用模板迭代器的最简单方法是什么?
- 从基于迭代器的for循环转换后,如何在map::find()中调用方法
- 在 C++17 中实现迭代器和const_iterator的正确方法是什么?
- 如何在不迭代的情况下对数组中的每个元素调用方法
- 编译错误 std::vector<std::shared_ptr<T>>迭代器和擦除方法
- 在 c++ 中迭代对列表的正确方法?
- 如何使用 SFINAE 从 end() 方法返回 (const_) 迭代器
- 如何使用迭代器作为参数方法?
- 迭代快速排序方法的分区算法问题
- 迭代器方法无法从Const_iterator继承
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?
- 是否可以从 const 方法迭代链表
- 龙格-库塔四阶方法迭代时的累积误差