我一直在使用 GSL 集成包 (gsl_integration.h) 来尝试在某个限制 [a,b] 之间针对 x 集成一些多变量函数 f(x,y,z)。在此示例中,我有一个玩具模型:f(x,y,z) = xyz
我想使用函数输出此积分的结果
double integral(double a, double b, double y, double z){}
在此之前我可以保持 y 和 z 任意。到目前为止,我的尝试主要涉及将 y、z 设置为等于某个预定义函数中的常量,然后使用
gsl_integration_qags
函数来集成该函数。但是,我想保持 y 和 z 的值任意,直到我在上面的函数中定义它们为止。到目前为止我得到的最接近的结果如下
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>
#include <gsl/gsl_integration.h>
#include<stdio.h>
#include<math.h>
#define PI 3.1415926535897
double integrand(double x, void * params){
double y = *(double *) params;
double z = *(double *) params; // PROBLEM: this just sets z = y
double tmp = x*z*y;
return tmp;
}
double integral(double a, double b, double y, double z){
gsl_integration_workspace * w
= gsl_integration_workspace_alloc (1000);
gsl_function F;
F.function = &integrand; // Set integrand
F.params = &y, &z; // Set the parameters you wish to treat as constant in the integration
double result, error;
gsl_integration_qags (&F, a, b, 0, 1e-7, 1000,
w, &result, &error);
gsl_integration_workspace_free (w); // Free the memory
return result;
}
int main(){
std::cout << "Result "<< integral(0.0,1.0,3.0,5.0)<<std::endl;
}
这给出了输出
Result 4.5
代码设置 a = 0.0、b = 1.0、y = z = 3.0 - 我想要 a = 0.0、b = 1.0、y = 3.0、z = 5.0,这将得到 7.5 的结果。
如果可能的话,我想坚持使用 GSL 集成而不是 boost。我也咨询过https://www.gnu.org/software/gsl/doc/html/integration.html但我一无所知。任何建议将不胜感激,谢谢。
最佳答案
我正在猜测,但在我看来你想要
double params[] = { y, z };
F.params = params;
和
double y = ((double *)params)[0];
double z = ((double *)params)[1];
关于c++ - gsl 多变量数值积分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51365545/