所以我有一个程序在函数 x^2 + y^2 < 1 上实现自适应 2D 梯形规则,但似乎递归不起作用——这里的程序是(工作)1D 的修改形式梯形方法,所以我不确定代码在哪里发生故障,它应该返回 PI:
double trapezoidal(d_fp_d f,
double a, double b,
double c, double d) { //helper function
return 0.25*(b-a)*(d-c)*
(f(a, c)+f(a, d) +
f(b, c)+f(b, d));
}
double atrap( double a, double b, double c, double d, d_fp_d f, double tol )
{// helper function
return atrap1(a, b, c, d, f, tol );
}
double atrap1( double a, double b, double c, double d, d_fp_d f, double tol)
{
//implements 2D trap rule
static int level = 0;
const static int minLevel = 4;
const static int maxLevel = 30;
++level;
double m1 = (a + b)/2.0;
double m2 = (c + d)/2.0;
double coarse = trapezoidal(f,a,b,c,d);
double fine =
trapezoidal(f, a, m1, c, m2)
+ trapezoidal(f, a, m1, m2, d)
+ trapezoidal(f, m1, b, c, m2)
+ trapezoidal(f, m1, b, m2, d);
++fnEvals;
if( level< minLevel
|| ( abs( fine - coarse ) > 3.0*tol && level < maxLevel ) ){
fine = atrap1( a, m1, c, m2, f,tol/4.0)
+ atrap1( a, m1, m2, d, f, tol/4.0)
+ atrap1(m1, b, c, m2, f, tol/4.0)
+ atrap1(m1, b, m2, d, f,tol/4.0);
}
--level;
return fine;
}
函数由下式给出
double ucircle( double x, double y)
{
return x*x + y*y < 1 ? 1.0 : 0.0;
}
我的主要功能是
int main()
{
double a, b, c, d;
cout << "Enter a: " <<endl;
cin >> a;
cout << "Enter b: " <<endl;
cin >> b;
cout << "Enter c: " <<endl;
cin >> c;
cout << "Enter d: " <<endl;
cin >> d;
cout << "The approximate integral is: " << atrap( a, b, c, d, ucircle, 1.0e-5) << endl;
return 0;
}