有人指教了我一个积分函数,是用c代码表示的。
可我急需把他用vb代码表示出来。希望达人帮忙。//use simpson's rule to integrate the f(x)
double integrate( double (*func)(double),       //func为要积分的函数
         double a,                              //左边界
         double b,                              //右边界
         int n ,                                //n为采样点的个数
  )
{
double step;
int i;
double sum1,sum2,sum ;
int flag = 0;
if ( a > b ) {
flag = 1;
sum=a;//sum is a temp value
a=b;
b=sum;
}
step = (b - a)/n;
sum1 = 0;
sum2 = 0;
sum  = 0;
for (i = 1; i<=n-1; i++){
sum1 += func(a+i*step);
sum2 += func(a + (i - 1/2)*step);
}
sum2 += func(a+(i-1/2)*step);
sum = ( ( func(a) +func(b) )/2 + sum1 + 2*sum2 )*step/3 ;

if ( flag ) return -sum;
else return sum;
}

解决方案 »

  1.   

    double integrate( double (*func)(double),       //func为要积分的函数
             double a,                              //左边界
             double b,                              //右边界
             int n ,                                //n为采样点的个数
      )
    {
    double step;
    int i;
    double sum1,sum2,sum ;
    int flag = 0;
    if ( a > b ) {
    flag = 1;
    sum=a;//sum is a temp value
    a=b;
    b=sum;
    }
    step = (b - a)/n;
    sum1 = 0;
    sum2 = 0;
    sum  = 0;
    for (i = 1; i<=n-1; i++){
    sum1 += func(a+i*step);
    sum2 += func(a + (i - 1/2)*step);
    }
    sum2 += func(a+(i-1/2)*step);
    sum = ( ( func(a) +func(b) )/2 + sum1 + 2*sum2 )*step/3 ;

    if ( flag ) return -sum;
    else return sum;
    }private function integrate( byval a as double, byval b as bouble, byval n as integer ) as double
    dim step as double
    dim i as integer
    dim sum1 as double, sum2 as double, sum as double
    dim flag as integer
    flag = 0
    if a > b then
    flag = 1
    sum = a
    a = b
    b = sum
    end if
    step = ( b - a ) / n
    sum1 = 0
    sum2 = 0
    sum = 0
    for i = 1 to n - 1
    sum1 = sum1 + func( a + i * step )
    sum2 = sum2 + func( a + ( i - 1 / 2 ) * step )
    '这里是一个关键,因为VB不好实现函数指针,所以必须外部定义func函数
    '如果你需要动态的执行不同的过程,需要这样写
    '在本函数的参数中添加byval whichone as integer
    '在这里写
    'if whichone = 1 then
    ' sum1 = sum1 + fun1( ... )
    'end if
    'if whichone = 2 then
    ' sum1 = sum1 + fun2( ... )
    'end if
    '...
    next i
    sum2 = sum2 + func( a + ( i - 1 / 2 ) * step )
    sum = sum + ( ( func( a ) + func( b ) ) / 2 + sum1 + 2 * sum2 ) * step / 3
    '这里和上边一样
    if flag 
    integrate = -sum
    else
    integrate = sum
    end if
    end function