c++ - c++ 中用于数值积分的局部函数的解决方法

标签 c++ function physics integral

对于与物理相关的计算,我需要在数值上评估一个四维积分,该积分取决于需要改变的几个参数;这样它们就不能被全局定义。我正在使用 Cuba提供以下功能的包:

Cuhre(NDIM, NCOMP, Integrand , USERDATA, NVEC,EPSREL, EPSABS, VERBOSE | LAST,MINEVAL,
 MAXEVAL, KEY,STATEFILE, SPIN,&nregions, &neval, &fail, integral, error, prob);

参数“Integrand”是一个预期以下列方式定义的函数:

int Integrand(const int *ndim, const cubareal xx[],const int *ncomp,
cubareal ff[], void *userdata) ;

我的问题是我想集成一个函数,该函数依赖于我想在程序中变化的连续参数。我的意思是我的被积函数取决于几个额外的参数,比如 a、b、c。

然后我想在本地定义类似 Integrand 函数的东西,即在参数 a、b 和 c 固定的范围内,这样它将具有正确的形式作为参数传递给 Cuhre 函数。

然后我想我也许可以把所有东西都放到一个类中,例如:

 class integrate{
  private: // parameters

  public:
//constructor
int Integrand(...){
  // calculation involving the parameters 
}

  };

并将该函数定义为该类的方法。 然而,这不起作用,因为我不能将非静态对象方法传递给函数,而且,使方法静态化也会迫使我将参数设置为静态,这意味着我将无法在程序中初始化它们。

有什么解决办法吗?

最佳答案

[编辑:正如我从评论中看到的那样,您误解了 userdata 指针,让我向您展示如何使用它:]

struct Parameters
{
    int a, b, c; // TODO: appropriate defaults
};

int integrand
(
    const int* ndim, const cubareal xx[],
    const int* ncomp, cubareal ff[],
    void* userdata
)
{
    Parameters* p = reinterpret_cast<Parameters*>(userdata);
    /* calculations using p->a, p->b, p->c */
}

int main(int argc, char* argv[])
{
    Parameters p;
    /* fill in parameters appropriately, e. g. parsing command line parameters */
    Cuhre(/* other parameters */, &integrand, &p, /* remaining parameters */);
}

我以前的解决方案仍然是替代方案......

.cpp 文件:

namespace
{
    int g_a = 0; // appropriate default values...
    int g_b = 0;
    int g_c = 0;
};

void setIntegrationParameters (int a, int b, int c)
{
    g_a = a;
    g_b = b;
    g_c = c;
}

int integrand
(
    const int* ndim, const cubareal xx[],
    const int* ncomp, cubareal ff[],
    void* userdata
)
{
    /* calculations using g_a, g_b, g_c */
}

.h文件:

void setIntegrationParameters (int a, int b, int c);
int integrand
(
    const int* ndim, const cubareal xx[],
    const int* ncomp, cubareal ff[],
    void* userdata
);

在您的主程序中,您可以 e. G。解析命令行参数以计算 a、b、c,并通过 setIntegrationParameters 将它们设置为集成参数。

(您可以对 C 代码执行完全相同的操作,当然然后使用 C-Casts 和静态全局变量而不是匿名 namespace ...)

关于c++ - c++ 中用于数值积分的局部函数的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36795466/

相关文章:

c++ - 使用基类的静态函数而不指定参数以避免歧义

javascript - 一个函数如何传递给另一个函数?

c# - Farseer 物理... Hello World ...?

c - 如何调用传递给另一个函数的任意 C 函数?

PHP函数建一个默认变量?

javascript - 模拟类似于尘埃粒子的运动

c++ - 使用 std::complex<double> 为 `*` 操作将 int 转换为 double

c++ - 如何复制已经打开的文件?

c++ - 如果每个参数都可转换为特定类型,则启用构造函数

c++ - *nix & C++ 编写非阻塞套接字服务器