算法描述
(1)计算步长h =(b-a)/n
(2)计算sum1 = f(a)+f(b)
(3)从 i =1开始计算 h = a+ih,计算f(a+ih)的累加和直到i = n-1得到累加和 sum2
(4)计算 I = h*(sum1+2*sum2)/2,即得出结果积分I
源程序代码及运行结果截图
#include<iostream>
#include<vector>
#include<math.h>
#include<iomanip>
#include<string>
using namespace std;
struct Point
{
Point(float x, float y) {
this->x = x;
this->y = y;
}
Point() {
}
float x; //坐标的x轴
float y; //坐标的y轴
int k = -1; //给每个已知点进行编号,表示第k个点,k = 0,1,2....n
};
//存放已知点编号完成后的动态向量
vector<Point> *vec = NULL;
/*
@param points 要初始化的已知点数组
@param len 数组长度
*/
void init(Point points[], int len)
{
vec = new vector<Point>();
for (int i = 0; i < len; i++)
{
//给每个点进行编号处理
points[i].k = i;
//将每个点放入到向量集合中
vec->push_back(points[i]);
}
}
/*
获取x值对应的函数值
@param x : 自变量x
@return 返回自变量x对应的y值
*/
float getFunctionValue(float x)
{
return sin(x)/x;
}
/*
获取积分值
@param a : 积分变量起始位置
@param b : 积分变量结束位置
@param n : 积分区间等距分为n份
*/
float getResult1(float a, float b, int n)
{
//步长 h
float h = (b - a) / n;
//用于保存结果
float result = 0.0f;
//首先计算f(a)+f(b)
result += getFunctionValue(a) + getFunctionValue(b);
//开始计算2*f(a+i*h),i=1,2,3...n-1的累加值
for (int i = 1; i < n; i++) {
result += getFunctionValue(a+i*h) * 2;
}
//计算最终结果
result = result * h / 2;
return result;
}
/*
获取x值对应的函数值
@param a : 积分变量起始位置
@param b : 积分变量结束位置
@param n : 积分区间等距分为n份
*/
float getResult(float a, float b,int n)
{
//步长 h
float h = (b - a)*1.0f / n;
//用于保存结果
float result = 0.0f;
//首先计算f(a)+f(b)
result += (*vec)[0].y + (*vec)[n].y;
//开始计算f(x0)+2*(f(x1)+f(x2)+...+f(xn-1))+f(xn)的累加值
for (int i = 1; i < n;i++) {
result += (*vec)[i].y * 2;
}
//计算最终结果
result = result * h / 2;
return result ;
}
int main()
{
//测试数据
Point p1(0.0f, 1.0f);
Point p2(0.125f, 0.997f);
Point p3(0.250f, 0.990f);
Point p4(0.375f, 0.977f);
Point p5(0.5f, 0.954f);
Point p6(0.625f, 0.936f);
Point p7(0.750f, 0.909f);
Point p8(0.875f, 0.877f);
Point p9(1.0f, 0.841f);
Point points[9] = { p1,p2,p3,p4,p5,p6,p7,p8,p9 };
init(points, 9);
cout << "复合梯形公式求得f(x)=sinx/x在区间[10^-20,1.0]上的积分I=" << getResult1(1e-20, 1.0f, 8) << endl;
system("pause");
return 0;
}