gpt4 book ai didi

random - GSL 统一随机数生成器

转载 作者:行者123 更新时间:2023-12-01 11:02:08 25 4
gpt4 key购买 nike

我想使用 GSL 的统一随机数生成器。在他们的网站上,他们包含以下示例代码:

 #include <stdio.h>
#include <gsl/gsl_rng.h>

int
main (void)
{
const gsl_rng_type * T;
gsl_rng * r;

int i, n = 10;

gsl_rng_env_setup();

T = gsl_rng_default;
r = gsl_rng_alloc (T);

for (i = 0; i < n; i++)
{
double u = gsl_rng_uniform (r);
printf ("%.5f\n", u);
}

gsl_rng_free (r);

return 0;
}

但是,这不依赖于任何种子,因此每次都会产生相同的随机数。

他们还指定了以下内容:

The generator itself can be changed using the environment variable GSL_RNG_TYPE. Here is the output of the program using a seed value of 123 and the multiple-recursive generator mrg,

 $ GSL_RNG_SEED=123 GSL_RNG_TYPE=mrg ./a.out


但我不明白如何实现这一点。关于我可以对上述代码进行哪些修改以合并种子的任何想法?

最佳答案

问题是没有生成新种子。如果你只想要一个返回一个该死的随机数的函数,而不关心它是如何生成的粘性细节,试试这个。假设您已安装 GSL。

#include <iostream>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <sys/time.h>

float keithRandom() {
// Random number function based on the GNU Scientific Library
// Returns a random float between 0 and 1, exclusive; e.g., (0,1)
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
struct timeval tv; // Seed generation based on time
gettimeofday(&tv,0);
unsigned long mySeed = tv.tv_sec + tv.tv_usec;
T = gsl_rng_default; // Generator setup
r = gsl_rng_alloc (T);
gsl_rng_set(r, mySeed);
double u = gsl_rng_uniform(r); // Generate it!
gsl_rng_free (r);
return (float)u;
}

关于random - GSL 统一随机数生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9768519/

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