#include<iostream>
#include<math.h>
using namespace std;
//1.编制Newton法解方程f(x) = 0的通用程序
float func_x(float x); //函数声明
float diff_func(float x);
int main()
{
float x0, e1, x1,tol;
int cont = 1;
cout << "Please input a root and a limit value:" << endl;
cin >> x0 >> e1; //输入迭代初值和误差极限
x1 = x0 - func_x(x0) / diff_func(x0);
tol = fabs(x1 - x0);
while (tol > e1) //大于误差极限继续进行迭代
{
cout << "The " << cont << " times of NewtonIteration root is: " << x1 << endl;
x0 = x1;
x1 = x0 - func_x(x0) / diff_func(x0); //迭代算法
tol = fabs(x1 - x0);
cont++; //迭代次数计算
}
cout << "The final root of Iteration is: " << x0 << endl;
return 0;
}
float func_x(float x) //原函数
{
float a = 1.0;
return (a/3 * x * x * x - x);
}
float diff_func(float x) //函数求导
{
return (x * x - 1);
}
Newton迭代法的C++实现
猜你喜欢
转载自blog.csdn.net/qq_42373896/article/details/121032543
今日推荐
周排行