【C】牛顿方法求函数在某点附近的零点

原理:

                       

例如:用牛顿法求下面方程在1.5附近的根:

              2*x^3 - 4*x^2 + 3*x -6 = 0

故有:f(x) = 2*x^3 - 4*x^2 + 3*x - 6

        df/dx = 6*x^2 - 8*x + 3

        x := x - f(x)/(df/dx);

C代码实现:

 1 #include <stdio.h>
 2 #include <math.h>
 3 
 4 
 5 /*****************************************NEWTON'S METHODS FOR GETTING THE ROOT OF A FUNCTION*********************************************************/
 6 
 7 /*function f(x)*/
 8 double f(double x)
 9 {
10     return 2*pow(x,3) - 4*pow(x,2) + 3*x - 6;
11 }
12 /*function df/dx that is f'(x) */
13 double df(double x)
14 {
15     return 6*x*x - 8*x + 3;
16 }
17 
18 /*theta is the parameter of function f, and the parameter of function df*/
19 double Newton( double theta,double (*f)(double), double (*df)(double), const double precision )
20 {
21     
22     double x1 = (*f)(theta);
23     double x2;
24     do{
25         x2 = x1 - (*f)(x1)/(*df)(x1);
26     }while( fabs(x2-x1) < precision ? 0: (x1 = x2));
27     return x2;
28 }
29 
30 int main()
31 {
32     double (*pf)(double) = f;
33     double (*pdf)(double) = df;
34     /*test*/
35     printf("%lf",Newton(1.5,pf,pdf,0.0001));
36     return 0;
37 }
原文地址:https://www.cnblogs.com/yongjiuzhizhen/p/4337167.html