均匀分布的随机数与 2 互质
一个具体的例子,
我需要生成一个 0 到 2 之间的随机数(包括 0 和 2)。 (或在 -1、0 和 1 之间随机选择)。
简单的方法是执行类似 rand() mod 3
的操作,其中 rand()
返回一个整数。 除非 rand()
的上限不是互质(下限为 0),否则此方法不会生成统计随机数。
例如,假设 rand() 返回 2 位(从 0 到 3,含),则模数将映射:
0 -> 0 0
1-> 1
2-> 2
3-> 0
如果返回更多位,则向 0 的偏斜显然会小得多,但无论如何,偏斜仍然存在。
一般问题
有没有一种方法可以生成 0 到 n-1(含)之间均匀分布的随机数,其中 n 与 2 互质?
A specific example
I need to generate a random number between 0 and 2, inclusive. (or choose randomly between -1, 0, and 1).
The naive approach would be to do something like rand() mod 3
where rand()
returns an integer. This approach will not generate statistically random numbers unless the upper bound of rand()
is not relatively prime (and the lower bound is 0).
For instance, assuming rand() returned 2 bits (from 0 to 3, inclusive), the modulus would map:
0 -> 0
1 -> 1
2 -> 2
3 -> 0
This skew toward 0 would obviously be much less if more bits would be returned, but regardless, the skew would remain.
The generic question
Is there a way of generating an evenly distributed random number between 0 and n-1, inclusive, where n is relatively prime to 2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一种常见的方法是丢弃上一个完整周期以上的随机值,而只要求一个新的随机数。
A common approach is to discard random values above the last full cycle, and just ask for a new random number.
它可能有助于选择 rand() 上限为 k*n,其中 k 是整数。 这样,只要 rand() 是一个好的随机生成器,结果就会均匀分布。
如果无法减小上限,则可以选择 k 以使 k*n 尽可能接近 rand() 上限,并丢弃高于此数字的结果,然后重试。
It might help choosing your rand() upper bound to be k*n where k is an integer. This way the outcome will be evenly distributed provided that rand() is a good random generator.
If it's not possible to reduce the upper bound, you can pick k so that k*n is as close to rand() upper bound as possible and discard the results above this number trying again.
请参阅我的回答类似的问题。
基本上,使用你的 RNG 并丢弃 N 以上的所有内容,然后重试。 为了优化,您可以使用 mod,并丢弃 n * Floor(MAX / n) 以上的所有内容
See my answer to a similar question.
Basically, use your RNG and discard everything above N and try again. For optimization, you can use mod, and discard everything above n * floor(MAX / n)
通用答案:您需要使用的数字不仅仅是 2 位。
我的经验法则是生成浮点值,x,0.0 <= x < 1.0,乘以 3 并截断。 这应该会得到 0、1 和 2 范围内的值,这些值取决于更多的位数。
Generic Answer: You need to use more than just 2 bits of the number.
My rule of thumb is to generate floating-point values, x, 0.0 <= x < 1.0, multiply by 3 and truncate. That should get you values in the range 0, 1 and 2 that depend on a larger number of bits.