自适应梯形公式.cpp

来自「Gauss,加速迭代,拉格朗日插值法,龙贝格算法,牛顿迭代算法」· C++ 代码 · 共 36 行

CPP
36
字号
#include<iostream>
#include<math.h>
using namespace std;
int n;
float AutoTrap(float(*f)(float),float a,float b)
{
	int i;
	float x,s,h=b-a;
	float t1,t2=h/2*((*f)(a)+(*f)(b));
	n=1;
	do
	{
		s=0;
		t1=t2;
		for(i=0;i<n;i++)
		{
			x=a+i*h+h/2;
			s+=(*f)(x);
		}
		t2=(t1+s*h)/2;
		n*=2; h/=2;
	}
	while(fabs(t2-t1)>0.5e-5);
	return t2;
}
float f(float x)
{
	return 1/(x*2);
}
void main()
{
	float s;
	s=AutoTrap(f,2,8);
	cout<<"二分"<<n/2<<"次后误差绝对值不超过5e-4"<<endl;
	cout<<"T(f)="<<s<<endl;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?