牛顿迭代法求方程的根

转自:https://blog.csdn.net/qq_31029351/article/details/53311285
牛顿法求最优解,本质上就是求f(x)=0的过程,求某个点的方根,本质上是求x^n-m=0的过程,如求f(x)=x^2,当f(x)=3,求x的最优解,就是求x^2-3=0的x的解。
牛顿迭代法求方程的根。
这里写图片描述

下面解决ax^3 + bx^2 + cx +b =0;一个根在1附近,约束条件|x - x0| <= 1e-5;
下面步骤讲解。
(1)选取迭代初值。x = 1.5
(2)f = ax0^3 + bx0^2 +cx0 +d fd = 3ax0^2 + 2bx0 + c
(3)增量h = f/fd
(4)循环条件fabs(x - x0) >=1e-5

下面给出具体的程序。

include <stdio.h>
include <math.h>

int main()
{
     flaot solution(float a,flaot b,float c,float d);
     float a;
     float b;
     float c;
     float d;
     scanf("%f%f%f%f",&a,&b,&c,&d);
     printf("the soulution is %f\n",solution(a,b,c,d);

     return 0;
}
float solution(float a, float b, float c,float d)
{
    float x = 1.5;
    float x0;
    float f;
    float fd;

    while(fabs(x - x0)>= 1e-5)
    {
        x0 = x;
        f = a * x0 * x0 * x0  + b * x0 * x0 +c * x0 + d;
        fd = 3 * a * x0 * x0 + 2 * b * x0 +c;
        x = x0 - f / fd;  
    }

    return x;
}

猜你喜欢

转载自blog.csdn.net/WitsMakeMen/article/details/81061217