分段错误:11 - 4D数值积分误差(C ++)

时间:2017-08-17 15:24:03

标签: c++ segmentation-fault numeric numerical-methods numerical-integration

我编写了三维集成代码,它调用高斯求积法例程进行积分,如下所示:

#include <iostream>
#include <cmath>
using namespace std;

float qgaus(float (*func)(float), float a, float b)
{
    int j;
    float xr,xm,dx,s;
    static float x[]={0.0,0.1488743389,0.4333953941,
        0.6794095682,0.8650633666,0.9739065285}; 
    static float w[]={0.0,0.2955242247,0.2692667193, 
        0.2190863625,0.1494513491,0.0666713443};

    xm = 0.5*(b+a); 
    xr = 0.5*(b-a);
    s = 0;

    for (j=1;j<=5;j++) 
    {
        dx=xr*x[j];
        s += w[j]*((*func)(xm+dx)+(*func)(xm-dx)); 
    }
    return s *= xr; 
}

float func(float x,float y,float z)
{
    float f = x*y*z;
    return f;
}

float yy1(float x)
{
    float y = x;
    return y;
}

float yy2(float x)
{
    float y = 2*x;
    return y;
}

float z1(float x,float y)
{
    float z = 5*x*y;
    return z;
}

float z2(float x,float y)
{
    float z = 10*x*x*y;
    return z;
}

static float xsav,ysav;
static float (*nrfunc)(float,float,float);

float quad3d(float (*func)(float, float, float), float x1, float x2)
{
    float qgaus(float (*func)(float), float a, float b); 
    float f1(float x);

    nrfunc=func;
    return qgaus(f1,x1,x2); 
}

float f1(float x) 
{
    float qgaus(float (*func)(float), float a, float b); 
    float f2(float y);
    float yy1(float),yy2(float);

    xsav=x;
    return qgaus(f2,yy1(x),yy2(x)); 
}

float f2(float y)  
{
    float qgaus(float (*func)(float), float a, float b); 
    float f3(float z);
    float z1(float,float),z2(float,float);

    ysav = y;
    return qgaus(f3,z1(xsav,y),z2(xsav,y)); 
}

float f3(float z)  
{
    return (*nrfunc)(xsav,ysav,z); 
}

int main ()
{
    float R;
    R = quad3d(func, 0, 1);
    cout << R << endl;
}

此代码适用于我测试过的任何三维函数。我试图修改它以通过用4d替换3d例程来计算四维函数:

static float wsav,xsav,ysav;
static float (*nrfunc)(float,float,float,float);

float quad4d(float (*func)(float, float, float, float), float w1, float w2)
{
    float qtrap(float (*func)(float), float a, float b); 
    float f1(float w);

    nrfunc=func;
    return qtrap(f1,w1,w2); 
}

float f1(float w) 
{
    float qtrap(float (*func)(float), float a, float b); 
    float f2(float x);
    float x1(float),x2(float);

    wsav = w;
    return qtrap(f2,x1(w),x2(w)); 
}

float f2(float x) 
{
    float qtrap(float (*func)(float), float a, float b); 
    float f3(float y);
    float yy1(float,float),yy2(float,float);

    xsav = x;
    return qtrap(f2,yy1(wsav,x),yy2(wsav,x)); 
}

float f3(float y)  
{
    float qtrap(float (*func)(float), float a, float b); 
    float f4(float z);
    float z1(float,float,float),z2(float,float,float);

    ysav = y;
    return qtrap(f3,z1(wsav,xsav,y),z2(wsav,xsav,y)); 
}

float f4(float z)  
{
    float t = (*nrfunc)(wsav,xsav,ysav,z); 
    return t;
}

此代码编译正确,但在运行时会输出“Segmentation fault:11”。根据我的理解,这意味着数组存在某种问题或内存分配错误,但似乎没有意义,因为3d情况没有问题。任何有关这方面的帮助将不胜感激。

0 个答案:

没有答案