简介
代码
#include<bits/stdc++.h>
using namespace std;
double f(double x)
{
// cout<<"f(x): "<<x*x*x+2*x*x+10*x-20<<endl;
return x*x*x+2*x*x+10*x-20;
}
double f_(double x){
// cout<<"f_x: "<<x*x+4*x+10<<endl;
return x*x*3+4*x+10;
}
int main()
{
double x;
cout<<"输入计算的初值点"<<endl;
cin>>x;
int maxx;
cout<<"输入最大迭代次数"<<endl;
cin>>maxx;
for(int i=0;i<maxx;i++)
{
cout<<"i: "<<i<<" x: "<<x<<endl;
// cout<<x<<" "<<f(x)<<" "<<f_(x)<<endl;
x = x - f(x)/f_(x);
}
return 0;
}
结果(默认函数为:x * x * x+2 * x * x+10 * x - 20 ):
Newton下山法
代码
#include<bits/stdc++.h>
using namespace std;
double f(double x)
{
// cout<<"f(x): "<<x*x*x+2*x*x+10*x-20<<endl;
return x*x*x+2*x*x+10*x-20;
}
double f_(double x){
// cout<<"f_x: "<<x*x+4*x+10<<endl;
return x*x*3+4*x+10;
}
int main()
{
double x;
cout<<"输入计算的初值点"<<endl;
cin>>x;
int maxx;
cout<<"输入最大迭代次数"<<endl;
cin>>maxx;
double k ;
cout<< "输入精度要求" <<endl;
cin>>k ;
cout<<"i: "<<0<<" x: "<<x<<endl;
for(int i=0;i<maxx;i++)
{
// cout<<x<<" "<<f(x)<<" "<<f_(x)<<endl;
double z = 1.0,y;
for(int j=0;;j++)
{
y = x - z*f(x)/f_(x);
z = z*0.5;
if(fabs(f(y))<fabs(f(x))) break;
}
if(fabs(y-x)<k ) { x = y;cout<<"i: "<<i<<" x: "<<x<<endl; break; }
x = y;
cout<<"i: "<<i<<" x: "<<x<<endl;
}
return 0;
}
结果(默认函数为:x * x * x+2 * x * x+10 * x - 20 ):