牛顿迭代法可以用来求取函数的零点,具体参见百度百科吧。。。
实验:求取一元三次方程的零点
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int Solve(double *para);
double NewtonIteration(double theta,double *para);
#define ITER_MAX 1000
int main(int argc,char *argv[])
{
//This program is to tackle the cubic equation.
if(argc!=5)
{
printf("Error:input parameters must be 4.\n");
return 0;
}
double parameters[4];
for(int i=0;i<4;i++)
parameters[i]=atof(argv[i+1]);
printf("Equation:%f*x^3+%f*x^2+%f*x+%f\n",parameters[0],parameters[1],parameters[2],parameters[3]);
Solve(parameters);
return 1;
}
int Solve(double *para)
{
double theta=100; //initial
for(int i=0;i<ITER_MAX;i++)
{
//Newton Iteration
theta=NewtonIteration(theta,para);
}
printf("Answer:%f\n",theta);
return 1;
}
double NewtonIteration(double theta,double *para)
{
double ftheta,fthetaDiff;
ftheta=pow(theta,3)*para[0]+pow(theta,2)*para[1]+theta*para[2]+para[3];
fthetaDiff=pow(theta,2)*para[0]*3+pow(theta,1)*para[1]*2+para[2];
theta-=ftheta/fthetaDiff;
return theta;
}
结果:
输入:
4 3 2 1