Iterative Algorithm 8-Approximate Iterative Method for Definite Integral

Find definite integral

I = \ int_0 ^ 1 sin x dx

[Analysis]
definite integral

I = \ int_0 ^ 1 sin x dx

The geometric meaning of is to find the area of ​​the curved top trapezoid surrounded by the curve f(x) and y=0, x=a, x=b. In order to obtain the value of the definite integral, it is necessary to divide the continuous object into sub-objects that are easy to solve, and then use the iterative method to repeatedly operate the expression. There are two ways to find definite integrals: rectangular method and trapezoidal method.

The following mainly takes the trapezoidal method as an example to explain in detail:

The image of the function y=f(x) is shown in the figure

It can be seen from the figure that a curved-top trapezoid can be divided into many small curved-top trapezoids of length h, and each small curved-top trapezoid can be approximately regarded as a trapezoid. The area of ​​the i-th curved-top trapezoid is:

s= \frac{h}{2} * [f(a+i*h) + f(a+(i+1)*h)]

Substitute h=(ba)/n into:

s= \sum_{i=0}^{n} \frac{h}{2} * [f(a+i*h) + f(a+ (i+1)*h)]

Among them, a is the lower limit, b is the upper limit, and n is the number of small curved top trapezoids. Expanding the above formula, there are:

s \approx \frac{h}{2} [f(a) + f(a+h) + f(a+h)+ f(a+2h)+ f(a+2h) +...+ f(a+(n-2)h)+ f(a+(n-1)h) + f(b)] \\ = \frac{h}{2} [f(a)+ f(b) +2 \sum_{i=1}^{n-1} f(a+ih)]
Change the above formula to iterative form:

\\ s= \frac{h}{2} [f(a)+ f(b)] \\ s=s+ h* (a+i*h)
The algorithm steps are:
(1) Find h=(ba)/n according to the lower bound a, upper bound b, and the number of trapezoids;
(2) Find the initial s=h/2 (f(a)+f(b) );
(3) From i=1 to n-1, accumulate h*(a+i*h) to s;

s is the required definite integral.

code:

#include<stdio.h>
#include<math.h>
#include <iostream>
#define N 1000
double f(double x);
double Integral(double a, double b, int n);
void main()
{
	double a, b, value;
	printf("输入积分下限和下限:");
	scanf("%lf,%lf", &a, &b);
	value = Integral(a, b, N);
	printf("sin(x)在区间[%lg,%lg]的积分为:%lf\n", a, b, value);

	system("pause");
}
double f(double x)
/*函数*/
{
	return sin(x);
}
double Integral(double a, double b, int n)
/*迭代次数*/
{
	double s, h;
	int i;
	h = (b - a) / n;
	s = 0.5*h*(f(a) + f(b));
	for (i = 1; i < n; i++)
		s = s + f(a + i*h)*h;
	return s;
}


result:

 

Guess you like

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