[算法] 变步长梯形积分求解函数的定积分

算法基本原理

一般的的积分函数的原理,我们通过使用二分法对其进行进一步划分,然后将两边和值近似求解出来并求出相关的平均值,针对于整体也相加起来并求解平均值,这个平均值就是我们需要的内容

算法基本步骤

算法实现代码

Trapzint.h 头文件定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#pragma once
class Function {
public:
virtual double operator ()(double x) const = 0;
virtual ~Function ();
};

class MyFunction : public Function {
public:
virtual double operator ()(double x) const;
};

class Integration {
public:
virtual double operator()(double a, double b, double eps) const = 0;
};

class Trapz :public Integration {
public :
Trapz (const Function &f) : f (f) {}
virtual double operator ()(double a,double b,double eps) const;
private :
const Function &f;
};

Trapzint.cpp 内容实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include "pch.h"
#include "Trapzint.h"
#include <cmath>

double MyFunction::operator()(double x)const {
return log (1.0 + x) / (1.0 + x * x);
}

double Trapz::operator()(double a, double b, double eps) const
{
bool done = false;
int n = 1;
double h = b - a;
double tn = h * (f (a) + f (b)) / 2;
double t2n;
do {
double sum = 0;
for (int k = 0; k < n; k++) {
double x = a + (k + 0.5) * h;
sum += f (x);
}
t2n = (tn + h * sum) / 2.0;
if (fabs (t2n - tn) < eps) {
done = false;
}
else {
tn = t2n;
n *= 2;
h /= 2;
}
} while (!done);
return t2n;
}

Function::~Function ()
{
}

Main 函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// MoveStepintegral.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include "pch.h"
#include <iostream>
#include "Trapzint.h"
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
MyFunction f;
Trapz trapz (f);
//std::cout << "Hello World!\n";
return 0;
}