从范围生成随机整数 [英] Generating random integer from a range

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

问题描述

我需要一个函数,它会在给定的范围内生成一个随机整数(包括边框值)。我没有不合理的质量/随机性要求,我有四个要求:




  • 我需要它快。我的项目需要生成数百万(或有时甚至数千万)的随机数,我的当前函数已经被证明是一个瓶颈。

  • 我需要它是相当均匀的rand()完全正确)。

  • 最小 - 最大范围可以是从< 0,1>到< -32727,32727&



我目前有以下C ++代码:

  output = min +(rand()*(int)(max  -  min)/ RAND_MAX)
)的主要问题,其中最后一个值几乎从不返回。



所以我抓住了笔和纸,下面的公式(建立在(int)(n + 0.5)整数舍入技巧):





但它仍然不能给我均匀分布。重复运行10000样本给我的比值为37:50:13的值为-1,0.1。



你能建议更好的公式吗? (或甚至整个伪随机数生成函数)

解决方案

您尝试过:

  output = min +(rand()%(int)(max  -  min + 1))

这仍然是偏向较低的数字,但比原来的版本要少得多。它也可以扩展它,以消除偏见。


I need a function which would generate a random integer in given range (including border values). I don't unreasonable quality/randomness requirements, I have four requirements:

  • I need it to be fast. My project needs to generate millions (or sometimes even tens of millions) of random numbers and my current generator function has proven to be a bottleneck.
  • I need it to be reasonably uniform (use of rand() is perfectly fine).
  • the min-max ranges can be anything from <0, 1> to <-32727, 32727>.
  • it has to be seedable.

I currently have following C++ code:

output = min + (rand() * (int)(max - min) / RAND_MAX)

The problem is, that it is not really uniform - max is returned only when rand() = RAND_MAX (for Visual C++ it is 1/32727). This is major issue for small ranges like <-1, 1>, where the last value is almost never returned.

So I grabbed pen and paper and came up with following formula (which builds on the (int)(n + 0.5) integer rounding trick):

But it still doesn't give me uniform distribution. Repeated runs with 10000 samples give me ratio of 37:50:13 for values values -1, 0. 1.

Could you please suggest better formula? (or even whole pseudo-random number generator function)

解决方案

Have you tried:

output = min + (rand() % (int)(max - min + 1))

This is still slightly biased towards lower numbers but much less so than your original version. It's also possible to extend it so that it removes the bias.

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

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