使用GMP在c ++中生成随机数 [英] Random number generation in c++ using GMP
问题描述
在java随机数字可以像
In java random number can get like
protected final static Random RANDOM = new Random(System.currentTimeMillis());
在c ++中使用GMP库如何生成随机数?
In c++ using GMP Library how it possible to generate random number?
我使用了像
gmp_randstate_t s;
unsigned long seed;
seed = time(NULL);
gmp_randinit_default(s);
gmp_randseed_ui(s, seed);
mpz_class ran;
gmp_randclass rr(s);
ran =rr.get_z_bits(125);
long int random=ran.get_ui();
但我没有随机数字。
请帮助我。
推荐答案
首先,没有 gmp_randclass
它需要一个 gmp_randstate
实例,所以你的代码没有为我编译。 建议使用 gmp_randclass实例$ c $的方法c>
正在使用 gmp_randinit_default
,如下所示:
First, there is no gmp_randclass
constructor that takes a gmp_randstate
instance, so your code didn't compile for me. The recommended way to construct a gmp_randclass instance
is using gmp_randinit_default
, like this:
gmp_randclass rr(gmp_randinit_default);
代码的第一部分是播种 gmp_randstate_t s
,但是随机状态变量 s
不会在代码的第二部分中使用(在上述更改之后)。除非另有种子,默认的GMP随机数生成器始终以相同的种子开始,这意味着每次运行程序时都会生成相同的序列的随机数。您可以使用 gmp_randclass :: seed
函数为 gmp_randclass
The first part of your code is seeding the gmp_randstate_t s
, but that random state variable s
is not used in the second part of your code (after the above change). Unless seeded otherwise, the default GMP random number generator always starts with the same seed, which means the same sequence of random numbers will be generated each time you run the program. You can seed an instance of gmp_randclass
using the gmp_randclass::seed
function.
以下代码与您的类似,但基于当前时间为随机数生成器设置种子。
The following code is similar to yours but seeds the random number generator based on the current time.
mpz_class ran;
gmp_randclass rr(gmp_randinit_default);
rr.seed(time(NULL));
ran =rr.get_z_bits(125);
long int random=ran.get_ui();
请注意,如随机状态播种,使用低分辨率当前时间通常是随机数生成器种子的不佳选择。
Note that as discussed in Random State Seeding, using a low-resolution current time is usually a poor choice for a random number generator seed.
这篇关于使用GMP在c ++中生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!