gpt4 book ai didi

c++ - gsl多变量数值积分

转载 作者:行者123 更新时间:2023-11-30 04:59:10 26 4
gpt4 key购买 nike

我一直在使用 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 集成而不是提升。我也咨询过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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com