头文件calculation.h
double newtow_iteration(double x,double eps,double (*f)(double),double (*df)(double)); //牛顿迭代法
double simple_itertion(double x,double eps,double (*f)(double)); //简单迭代法
double BXdoublenode_itertion(double a,double b,double eps,double (*f)(double)); //变形双点弦截法,a,b为左右区间;
calculation.cpp文件
# include
# include
# include
double newtow_iteration(double x,double eps,double (*f)(double),double (*df)(double)) //牛顿迭代法
{
long max=1000; //迭代初值x,精度eps ,f原函数,df导函数
int k=0; //k值记录迭代次数
double x1,x2,fx1,dfx1,d=1.0;
x2=x; //使x2获得迭代初值
while((d>eps)&&(k
{
x1=x2;
fx1=(*f)(x1);
dfx1=(*df)(x1);
if(dfx1<1e-10)
{
printf("F(X)的导数为0:\n");
return 0;
}
else
{
x2=x1-fx1/dfx1;
d=fabs(x2-x1);
k++;
}
}
if(k>max)
{
printf("迭代次数超过最大迭代次数,可能不收敛:\n");
return 0;
}
else
return x1;
}
double simple_itertion(double x,double eps,double (*f)(double)) //简单迭代法
{
long max=1000; //迭代初值x,精度eps ,f原函数
int k=0; //k值记录迭代次数
double x1,x2,d=1.0;
x2=x; //使x2获得迭代初值
while((d>eps)&&(k
{
x1=x2;
x2=f(x1);
d=fabs(x2-x1);
k++;
}
if(k>max)
{
printf("迭代次数超过最大迭代次数,可能不收敛:\n");
return 0;
}
else
return x1;
}
double BXdoublenode_itertion(double a,double b,double eps,double (*f)(double)) //变形双点弦截法,a,b为左右区间
{
long i,maxi=2; //迭代初值x,精度eps ,f原函数
double epsilon,x0,x1,x,fx0,fx1;
x0=a; //使得a,b获得迭代初值
x1=b;
fx0=f(x0);
fx1=f(x1);
for(i=0;i
{
x=x1-fx1*(x1-x0)/(fx1-fx0);
x0=x1;
fx0=fx1;
x1=x;
fx1=f(x1);
if(fx1==0)
break;
if(fabs(x1-x0)<=epsilon)
break;
}
if(i>maxi)
{
printf("迭代次数超过最大迭代次数,可能不收敛:\n");
return 0;
}
else
return x1;
}
test 文件
# include
# include"calculation.h"
# include
int main()
{
double eps=1e-3;
double x,a,b;
char t;
double fun(double),dfun(double),fun1(double),fun2(double);
printf("请输入A,B,C选择计算方法:\nA:牛顿迭代法,B:简单迭代法,C:变形双点弦截法:\n");
scanf("%c",t); //用菜单实现对不同计算方法的选择
switch(t)
{
case 'A':
printf("请输入迭代初值a:\n");
scanf("%lf",&a);
x=a;
x=newtow_iteration(a,eps,fun,dfun);// 调用牛顿迭代法函数
printf("方程f(x)=0的根是:\n%f\n",x);
break;
case 'B':
printf("请输入迭代初值a:\n");
scanf("%lf",&a);
x=a;
x=simple_itertion(a,eps,fun1); //调用简单迭代法函数
printf("方程f(x)=0的根是:\n%f\n",x);
break;
/*case 'C':
printf("请数入迭代初值a,b:");
scanf("%lf,%lf",&a,&b);
x=BXdoublenode_itertion(a,b,eps,fun2);
printf("方程f(x)=0的根是:\n%f\n",x);
break;*/
default:printf("输入的数据错误!");
}
system("pause"); /*在关闭此软件,直接点击DEBUG 运行时,
数入数据以后会出现闪退的情况,百度了一下才知道加上这一句可以解决这个问题*/
return 0;
}
double fun(double x)
{
return x*x*x*x*x+5*x-41;//牛顿迭代法的原函数f(x)
}
double dfun(double x)
{
return 5*x*x*x*x+5; //牛顿迭代法的导函数df(x)
}
double fun1(double x) //简单迭代法的原函数
{
return 1/(x*x*x*x)+3;
}
double fun2(double x)
{
return 2*x*x*x*x*x-3*x*x-7;//变形双点弦截法的原函数
}