梯形逐次分半算法的实现

//实验五 梯形逐次分半算法
#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;
}

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值