[英]Given a 32-bit unsigned ran num, how to manipulate value in a certain range [low, high]?
Like the title says, I'm using a random number generator on a Freescale Coldfire chip and it returns a 32 bit unsigned value. 就像标题所说的那样,我在飞思卡尔Coldfire芯片上使用随机数生成器,它返回32位无符号值。 As far as I know, there is no way to configure the generator to limit the range.
据我所知,没有办法配置发生器来限制范围。 What would be the best way to manipulate the number to be in the accepted range?
将数字控制在可接受范围内的最佳方法是什么?
I was thinking of modding the number by the high range value but I would still have to deal with the lower bound. 我本来想通过较高的范围值来修改数字,但我仍然必须处理下限。
This C FAQ article How can I get random integers in a certain range? 此C常见问题解答文章如何获取一定范围内的随机整数? explains how to properly generate random numbers in range
[M,N]
basically the formula you should use is: 解释了如何正确生成
[M,N]
范围内的随机数,基本上应该使用的公式是:
M + (random number) / (RAND_MAX / (N - M + 1) + 1)
Stephan T. Lavavej explains why doing this is still not going to be that great: Stephan T. Lavavej解释了为什么这样做仍然不那么出色:
From Going Native 2013 - rand() Considered Harmful From Going Native 2013- rand()被认为有害
If you really care about even distribution, stick with a power of 2, or find some routines for dithering. 如果您真正关心平均分配,请坚持2的幂,或者找到一些抖动的例程。
Yes, the traditional way is to MOD by the range, and this will be fine for many ordinary uses (simulating cards, dice, etc.) if the range is very small (a range of 52 compared to the 32-bit range of your generator is quite small). 是的,传统的方法是按范围进行MOD,如果范围很小(与您的32位范围相比,范围为52,这对于许多普通用途(模拟卡,骰子等)将是很好的选择)发电机很小)。 This will still be biased, but the bias will be nearly impossible to detect.
这仍然会产生偏差,但几乎无法检测到该偏差。 If your range is bigger, the bias will be bigger.
如果范围更大,则偏差会更大。 For example, if you want a random 9-digit number, the bias will be dreadful.
例如,如果您想要一个随机的9位数字,则偏差将是可怕的。 If you want to eliminate bias altogether, there is no alternative but to do rejection sampling--that is, you must have a loop in which you generate random numbers and throw some away.
如果要完全消除偏差,除了进行拒绝采样外,别无选择,也就是说,必须有一个循环,在其中生成随机数并将其丢弃。 If you do it right, you can keep those extra numbers needed to a minimum so you don't slow things down much.
如果操作正确,则可以将所需的额外数量保持在最低限度,以免降低速度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.