Find definite integral
[Analysis]
definite integral
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:
Substitute h=(ba)/n into:
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:
Change the above formula to iterative form:
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: