/*
-------------Romberg积分法计算定积分-------
参考教材:《数值分析》李乃成,梅立泉,科学出版社
《计算方法教程》第二版 凌永祥,陈明逵*/
//误差界eps%被积函数为f(x)=(x^3+sin(x))/x;积分区间为[0.3,0.8]
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(void)
{
/* int i,j,n;
float *d=(float *)malloc(sizeof(float)*N);
float *x=(float *)malloc(sizeof(float)*N);
float *y=(float *)malloc(sizeof(float)*N);
float *u=(float *)malloc(sizeof(float)*N);
free(a);free(b);free(c);free(d);free(x);free(y);free(l);
return 0;
*/
double b=0.8;
double a=0.3;
double h=0.0; //
double eps=1.0e-5;//误差界eps
int kmax=20; //最大递推次数
double T1=0.0,S1=0.0,C1=0.0,R1=0.0,T2=0.0,S2=0.0,C2=0.0,R2=0.0;
double sum;
double *x,*fx;
int i;
h=b-a;
T1=h/2*((pow(a,3)+sin(a))/a+(pow(b,3)+sin(b))/b);
printf("T1:%13.12f\n",T1);
for(int k=0;k<kmax;k++)
{
h=(b-a)/(pow(2,k+1));
x=(double *)malloc(sizeof(double)*int(pow(2,k)));
for(i=0;i<pow(2,k);i++)
{
x[i]=a+(2*i+1)*h;
}
fx=(double *)malloc(sizeof(double)*int(pow(2,k)));
sum=0.0;
for(i=0;i<pow(2,k);i++)
{
fx[i]=(pow(x[i],3)+sin(x[i]))/x[i];
sum+=fx[i];
}
T2=T1/2+sum*h;
printf("T2:%13.12f\n",T2);
S2=T2+(T2-T1)/3;
printf("S%d:%13.12f\n",int(pow(2,k)),S2);
if(k<2)
{
if(k==1)
{
C2=S2+(S2-S1)/15;
printf("C1:%13.12f\n",C2);
}
}
else
{
C2=S2+(S2-S1)/15;
printf("C%d:%13.12f\n",int(pow(2,k-1)),C2);
R2=C2+(C2-C1)/63;
printf("R%d:%13.12f\n",int(pow(2,k-2)),R2);
if(fabs(R2-R1)<eps)
break;
R1=R2;
}
T1=T2;S1=S2;C1=C2;
free(x);free(fx);
}
printf("所求积分I=%13.12f\n",R2);
return 0;
}