Newton iterative method for root equation
Problem description
writing functions root equation by Newton's iterative method, equation ax ^ 3 + bx ^ 2 + cx + d = 0
coefficients a, b, c, d by the main function of the input, find x a real root a vicinity of after the root is determined, the main function output
equation of Newton iteration method is:
X = X0 - F (X0) / F '(X0) is provided to the iterative | x-x0 | <= 10 ^ 5 end
analysis
Newton iterative method is then taken x0, on this basis find root of the equation than x0 closer, a step iteration to find closer equation root approximation root
Let r is f (x) = root 0, select x0 initial approximation as r, through the point (x0, f (x0)) to make the curve y = f (x) tangent L
L The equation y = f (x0) + f '(x0) (x-x0)
L x-axis is obtained abscissa intersection x1 = x0 - f (x0) / f '(x0)
called x1 is a first approximation of r, over point (x1, F (x1)) to make the curve y = f (x) tangent, and find the tangent and the abscissa the x axis x2 = x1-f (x1) / f '(x2) r called secondary approximation, the above process is repeated to give an approximation of r above process is the Newton iteration xn method solving process
algorithm design
program flow analysis:
| --1 1 looking in the vicinity of any real number is taken as the initial value x0 = 1.5 i.e. 1.5 x0.
| --2 f calculated at that time by the initial value x0 in the equation. value (X0) and f '(x0) program described by the equation of the variable f value after fd derivative described by the equation
|. --3 calculated delta = f H / fd
|. --4 calculate the next x, x0 = x - H
|. --5 replace the original x0 with x newly generated prepare for the next iteration
. | --6 if | x-x0 |> = le -5 go to step 3 to continue otherwise go to step. 7
|. 7 ì ask x is the equation ax ^ 3 + bx ^ 2 + cx + d = 0, root, outputs
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
float solution(float a, float b, float c, float d); //函数功能是用牛顿迭代法求方程的根
float a,b,c,d,x; //x用来记录求得的方程根, abcd代表所求方程的系数
printf("请求输入方程的系数:");
scanf("%f %f %f %f", &a, &b, &c, &d);
x = solution(a, b, c, d);
printf("所求方程的根为x = %f", x);
return 0;
}
float solution(float a, float b, float c, float d)
{
float x0, x = 1.5, f, fd, h; //f用来描述方程的值, fd用来描述方程求导之后的值
do
{
x0 = x; //用来求得的x的值代替x0原来的值
f = a*x0*x0*x0 + b*x0*x0 + c*x0 + d;
fd = 3*a*x0*x0 + b*x0 + c;
h = f/fd;
x = x0 - h;
} while (fabs(x-x0) >= 1e-5);
return x;
}
/* !< input */
2 -4 3 -6
/* !< output */