/*牛顿迭代法求线性方程组的解*/
#include<stdio.h>
#include<math.h>
#define maxrept 1000
/*函数f(x)*/
float f(float x)
{
return(x-exp(-x));
}
/*函数f(x)导数*/
float df(float x)
{
return(1+exp(-x));
}
/*牛顿迭代函数*/
float iterate(float x)
{
float x1;
x1=x-f(x)/df(x);
return(x1);
}
void main()
{
float x0,x1,eps,d;
int k=0;
printf("/n please input x0=");
scanf("%f",&x0);
printf("/n please input eps=");
scanf("%f",&eps);
printf("/n k x=k/n");
printf("/n %d %f/n",k,x0);
do
{
k++;
x1=iterate(x0);
printf(" %d %f/n",k,x1);
d=fabs(x1-x0);
x0=x1;
}while((d>=eps)&(k<maxrept));
if(k<maxrept)
printf("the root of f(x)=0 is x=%lf,k=%d/n",x1,k);
else
printf("/n the iteration is failed!/n");
}
/*牛顿下山法*/
#include<stdio.h>
#include<math.h>
#define maxrept 1000
/*函数f(x)*/
float f(float x)
{
return(x-exp(-x));
}
/*函数f(x)导数*/
float df(float x)
{
return(1+exp(-x));
}
/*牛顿迭代函数*/
float iterate(float x,int k)
{
float x1,n=pow(0.5,k);
x1=x-n*f(x)/df(x);
return(x1);
}
void main()
{
float x0,x1,eps,d,n=1.0;
int k=0;
printf("/n please input x0=");
scanf("%f",&x0);
printf("/n please input eps=");
scanf("%f",&eps);
printf("/n k x=k/n");
printf("/n %d %f/n",k,x0);
do
{ k++;
x1=iterate(x0,k);
printf(" %d %f/n",k,x1);
d=fabs(x1-x0);
x0=x1;
}while((d>=eps)&(k<maxrept));
if(k<maxrept)
printf("the root of f(x)=0 is x=%lf,k=%d/n",x1,k);
else
printf("/n the iteration is failed!/n");
}