构造函数中x_high为积分的上界,x_low为积分的下界,segment为分割的区间数(例如10),error为你需要结果的精度(如果你要求结果精确到小数点后四位,则error=0.0001),function为要积分的函数。
class Integrate
{
private double result=0.0;
private double oldresult=0.0;
void operate(double x_high,double x_low,int segment,double error,Functions function)
{
int j=-1;
do
{
oldresult=result;
j++;
int multi=1;
int k=0;
while(k<j)
{
multi=multi*2;
k++;
}
double w=(x_high-x_low)/(double)(segment*multi);
double sum=0.0;
for(int i=1;(x_low+i*w)<x_high;i++)
{
if(i%2==1)
sum=sum+4*function.operate(x_low+i*w);
if(i%2==0)
sum=sum+2*function.operate(x_low+i*w);
}
result=(w/3)*(function.operate(x_low)+sum+function.operate(x_high));
}while(Math.abs(result-oldresult)>error);
}
double getResult()
{
return result;
}
}