//实验五 梯形逐次分半算法
#include<iostream>
#include<cmath>
#include<iomanip>
#include <chrono>
#include <ratio>
#define Length 10000
using namespace std::chrono;
using namespace std;
class Trapezoid {
public:
void input();
double getfun1(double x);
double getfun2(double x);
double arithmetic1();
double arithmetic2();
void display();
private:
double a;
double b;
double time1;
double time2;
}T;
void Trapezoid::input() {
double a, b;
cout << "请输入积分下限:";
cin >> a;
cout << "请输入积分上限:";
cin >> b;
this->a = a;
this->b = b;
}
double Trapezoid::getfun1(double x) {
return exp(x);
}
double Trapezoid::getfun2(double x) {
return 1 / x;
}
double Trapezoid::arithmetic1() {
int n = 1, k;
double T[Length];
T[1] = ((b - a) / 2) * (getfun1(a) + getfun1(b));
double value = 17.367255;
auto start = steady_clock::now();
while (abs(T[n] - value) >= 1e-5) {
n++;
double temp = 0.0;
for (k = 1; k <= pow(2, n - 2); k++) {
temp += getfun1(a + ((2 * k - 1) / pow(2, n - 1)) * (b - a));
}
T[n] = 0.5 * T[n - 1] + ((b - a) / pow(2, n - 1)) * temp;
}
auto end = steady_clock::now();
auto tt = duration_cast<microseconds>(end - start);
this->time1 = tt.count();
return T[n];
}
double Trapezoid::arithmetic2() {
int n = 1, k;
double T[Length];
T[1] = ((b - a) / 2) * (getfun2(a) + getfun2(b));
double value = 1.0986122;
auto start = steady_clock::now();
while (abs(T[n] - value) >= 1e-4) {
n++;
double temp = 0.0;
for (k = 1; k <= pow(2, n - 2); k++) {
temp += getfun2(a + ((2 * k - 1) / pow(2, n - 1)) * (b - a));
}
T[n] = 0.5 * T[n - 1] + ((b - a) / pow(2, n - 1)) * temp;
}
auto end = steady_clock::now();
auto tt = duration_cast<microseconds>(end - start);
this->time2 = tt.count();
return T[n];
}
void Trapezoid::display() {
double T1 = arithmetic1();
cout << "从" << a << "到" << b << "关于e^x的定积分为:" << setprecision(7) << T1 << endl;
double T2 = arithmetic2();
cout << "从" << a << "到" << b << "关于1/x的定积分为:" << setprecision(7) << T2 << endl;
cout << endl;
cout << "求e^x的定积分用时:" << this->time1 << "ms" << endl;
cout << "求1/x的定积分用时:" << this->time2 << "ms" << endl;
cout << endl;
if (this->time1 <= this->time2) {
cout << "因此求e^x的定积分用时最短" << endl;
}
else {
cout << "因此求1/x的定积分用时最短" << endl;
}
}
int main() {
T.input();
T.display();
system("pause");
return 0;
}
梯形逐次分半算法的实现
于 2020-11-29 16:28:48 首次发布