gpt4 book ai didi

c++ - 使用 Boost 统一生成随机实数

转载 作者:行者123 更新时间:2023-11-28 07:11:52 26 4
gpt4 key购买 nike

<分区>

我正在尝试为蒙特卡洛积分生成一些统一的实数,但我构建的例程返回了一些非常奇怪的值。仔细检查后,我注意到 Boost 返回了一些看起来很疯狂的随机数,例如:

     temp = -0.185276
temp = -0.864523
temp = -0.0942081
temp = -0.164991
temp = -0.873013
temp = -0.0311322
temp = -0.0866241
temp = -0.778966
temp = -0.367641
temp = -0.691833
temp = 5.66499e-310
temp = 9.42007e-311
temp = 6.29821e-310
temp = 5.80603e-310
temp = 8.82973e-311
temp = 6.73679e-310
temp = 6.35094e-310
temp = 1.53691e-310
temp = 4.39696e-310
temp = 2.14277e-310

虽然这些数字在技术上仍然是在边界 -1 和 1 之间生成的实数,但如果它们不是那么小的话我会更喜欢它!

我对 boost 调用的实现是在一个被多次调用(针对不同的边界值)的函数中,如下所示:

// Define Boost typedefs
typedef boost::mt19937 Engine;
typedef boost::uniform_real<double> Distribution;
typedef boost::variate_generator <Engine, Distribution> Generator;

int main (void) {
...
Integral = MCRecursion(...);
...
return 0;
}

double MCRecursion (int Count, double Lower, double Upper, double (*Integrand)(double)) {

// Define Boost objects
Engine Eng;
Distribution Dist (Lower, Upper);
Generator RandomGen (Eng, Dist);

Eng.seed(time(0));

// Variables for Monte Carlo sample sums
double Sum = 0.0;
double temp;

for (int i = 0; i < Count; i++) {
temp = RandomGen();
std::cout << " temp = " << temp << std::endl;
Sum += Integrand(temp);
}

return (Upper - Lower) * Sum / Count;
}

我认为问题出在我的实现上,但我找不到任何错误。任何帮助表示赞赏!干杯, jack

编辑

调用MCRecursion的代码:

我正在编写的代码在我感兴趣的整个域 [Lower, Upper] 上运行蒙特卡罗,然后再次查看整个域的左半部分和域的右半部分。例如如果我们在 -a 和 a 之间积分 f(x),我使用以下方法计算完整积分:

double FullDomain = MCRecursion (1e5, LowerBound, UpperBound, f);
double Centre = (Upper + Lower) / 2.0;
double LeftHalf = MCRecursion (1e5, LowerBound, Centre, f);
double RightHalf = MCRecursion (1e5, Centre, UpperBound, f);

然后我通过计算来查看不确定性: 双差 = fabs(FullDomain - LeftHalf - Righthalf);看看更多的样本在某种意义上是否“值得” jack

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