5.牛顿迭代公式,求方程的近似解
C/C++ code
#include<stdio.h>
#include<math.h>
#include<conio.h>
#define N 100
#define PS 1e-5
#define TA 1e-5
float Newton(float (*f)(float),float(*f1)(float),float x0 )
{ float x1,d=0;
int k=0;
do
{ x1= x0-f(x0)/f1(x0);
if((k++>N)||(fabs(f1(x1))<  S))
{ printf("\nFailed!");
getch();
exit();
}
d=(fabs(x1)<1?x1-x0  x1-x0)/x1);
x0=x1;
printf("x(%d)=%f\n",k,x0);
}
while((fabs(d))>  S&&fabs(f(x1))>TA) ;
return x1;
}
float f(float x)
{ return x*x*x+x*x-3*x-3; }
float f1(float x)
{ return 3.0*x*x+2*x-3; }
void main()
{ float f(float);
float f1(float);
float x0,y0;
printf("Input x0: ");
scanf("%f",&x0);
printf("x(0)=%f\n",x0);
y0=Newton(f,f1,x0);
printf("\nThe root is x=%f\n",y0);
getch();
}
关于本帖内容欢迎大家踊跃讨论,与在下交流!
|