Iterative Algorithm 7-Newton Iterative Method of Approximate Iterative Method

Use Newton's method to find the roots of the equation x^4-3x^3+1.5x^2-4=0.

【definition】

Newton's iteration method is a commonly used algorithm for finding approximate roots of equations or equations.

1. Derivation process
Assuming that the approximate root of the known equation f(x)=0 is x0, the Taylor expansion at x0 is:

f(x)= f(x_0) + f'(x_0)(x-x_0) + \frac{f''(x_0)}{2!} (x-x_0)^2 + ......

Taking the linear part, that is, the first two terms of the Taylor expansion, as the nonlinear equation f(x)=0 approximate equation, then:

f(x_0) + f'(x_0) (x-x_0) =0

If f(x)\neq 0, then the solution of the equation is

x_1 = x_0 - \frac{f(x)}{f'(x_0)}

This results in an iteration sequence:

x_{n+1} = x_n - \frac{f(x)}{f'(x_0)}

Next, you can use the iterative formula to find an approximate solution to the equation.


1. Algorithm description

Use iterative formulas

x_{n+1} = x_n - \frac{f(x)}{f'(x_0)}  

The algorithm steps to find the approximate root of the equation f(x)=0 are as follows:

(1) Choose the approximate root of an equation and assign it to the variable x0.
(2) Store the value of x0 in variable x1, then calculate f(x1), and store the result in variable x0.
(3) When the absolute value of the difference between x0 and x1 is not less than the specified accuracy, repeat (2); otherwise, the algorithm ends.

If the equation has roots and the approximate root sequence calculated by the above method converges, the x0 obtained according to the above method is considered to be the root of the equation.
code:

#include<stdio.h>
#include<math.h>
#include <iostream>
#define EPS 1e-6
double f(double x);
double f1(double x);
int Newton(double *x, int iteration);
void main()
{
	double x;
	int iteration;
	printf("输入初始迭代值x0:");
	scanf("%lf", &x);
	printf("输入迭代的最大次数:");
	scanf("%d", &iteration);
	if (1 == Newton(&x, iteration))
		printf("该值附近的根为:%lf\n", x);
	else
		printf("迭代失败!\n");

	system("pause");
}
double f(double x)
/*函数*/
{
	return x*x*x*x - 3 * x*x*x + 1.5*x*x - 4.0;
}
double f1(double x)
/*导函数*/
{
	return 4 * x*x*x - 9 * x*x + 3 * x;
}
int Newton(double *x, int iteration)
/*迭代次数*/
{
	double x1, x0;
	int i;
	x0 = *x; /*初始方程的近似根*/
	for (i = 0; i < iteration; i++) /*iteration是迭代次数*/
	{
		if (f1(x0) == 0.0)/*如果倒数为0,则返回0(该方法失效)*/
		{
			printf("迭代过程中导数为0!\n");
			return 0;
		}
		x1 = x0 - f(x0) / f1(x0);/*开始牛顿迭代计算*/
		if (fabs(x1 - x0) < EPS || fabs(f(x1)) < EPS) /*达到结束条件*/
		{
			*x = x1; /*返回结果*/
			return 1;
		}
		else /*未达到结束条件*/
			x0 = x1; /*准备下一次迭代*/
	}
	printf("超过最大的迭代次数!\n"); /*迭代次数达到规定的最大值,仍没有达到精度*/
	return 0;
}


result:

 

Guess you like

Origin blog.csdn.net/baidu_36669549/article/details/104123319