随机数发生器,C ++ [英] Random number generator, C++

查看:146
本文介绍了随机数发生器,C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道C ++中的随机数生成有一些限制(可以是非均匀的)。如何生成1到14620之间的数字?

I know there is a bit of limitations for a random number generation in C++ (can be non-uniform). How can I generate a number from 1 to 14620?

谢谢。

推荐答案

一种常见的方法是使用 std :: rand() 与模数:

A common approach is to use std::rand() with a modulo:

#include<cstdlib>
#include<ctime>

// ...
std::srand(std::time(0));  // needed once per program run
int r = std::rand() % 14620 + 1;

然而,正如@tenfour在他的回答中提到的,模运算符可以扰乱值< c $ c> std :: rand()返回。这是因为模将其丢弃的值转换为有效值,并且此转换可能不一致。例如, n 在[0,10)中,值 n%9 将9转换为0,通过真零或9被转换为零来获得零。

However, as @tenfour mentions in his answer, the modulo operator can disrupt the uniformity of values std::rand() returns. This is because the modulo translates the values it discards into valid values, and this translation might not be uniform. For instance, for n in [0, 10) the value n % 9 translates 9 to 0, so you can get zero by either a true zero or a 9 translated to zero. The other values have each only one chance to yield.

另一种方法是从 std :: rand()中翻译随机数。 code>到[0,1]范围内的浮点值,然后将值翻译并移到您需要的范围内。

An alternative approach is to translate the random number from std::rand() to a floating-point value in the range [0, 1) and then translate and shift the value to within the range you desire.

int r = static_cast<double>(std::rand()) / RAND_MAX * 14620 + 1;

这篇关于随机数发生器,C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆