C language classic iterative algorithm solving function definite integral (detailed)

One, iterative algorithm

1. Tossing iteration The
iterative method is also called the tossing method, which is a process of recursively using old variable values ​​to obtain new values. The iterative method is a basic method for solving problems with computers. It uses the characteristics of fast computing speed and suitable for repetitive operations to allow the computer to perform a set of operations repeatedly, each time it is executed, the old value of the variable is used to derive one The new value.

2. It is different from recursion.
Iterative method and recursion method are somewhat similar, but their difference lies in:
iterative method uses while loop to solve, and recursive method uses for loop to achieve.
The iterative method obtains a solution or a set of solutions at the end of the iteration. The loop control variable of the recursive method changes once to obtain a solution, and the loop ends to obtain a series of solutions.
The number of iterations of the iterative method is unknown in advance, and the number of iterations of the recursive method is known in advance.

Two, trapezoidal method to solve definite integral

1. Test code

#include <stdio.h>
#include <math.h>
#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);
}

//需要积分的函数 
double f(double x)
{
    
    
	return sin(x);
}

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

2. Test result
Only the sin(x) function is used here. If you need the definite integral of other functions, you only need to change the function expression. Of course, the replacement function must be achievable.
01
02
03

Reference: "The Function and Algorithm of Program Language C/C++"

Guess you like

Origin blog.csdn.net/Viewinfinitely/article/details/112979032
Recommended