取模 N 的随机数的一致性

编程入门 行业动态 更新时间:2024-10-27 08:30:28
本文介绍了取模 N 的随机数的一致性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 [0, n) 中选择随机数的一种常见方法是取 rand() 模 n 的结果:rand() % n.但是,即使可用的 rand() 实现返回的结果是完全统一的,结果 [0, n) 的统一性应该不会有问题RAND_MAX + 1 没有被 n 整除时的数字?例如.假设 RAND_MAX 是 2,而 n 是 2.那么在 3 个可能的 rand() 输出中:0、1 和 2,我们得到 0, 1 和 0 当我们以 n 为模使用它们时.因此,输出将根本不均匀.

One common way of choosing a random number in [0, n) is to take the result of rand() modulo n: rand() % n. However, even if the results returned by the available rand() implementation are fully uniform, shouldn't there be a problem with the uniformity of the resulting [0, n) numbers when RAND_MAX + 1 does not divide evenly by n? E.g. suppose RAND_MAX is 2, and n is 2. Then out of 3 possible rand() outputs: 0, 1 and 2, we get 0, 1 and 0 respectively when we use them modulo n. Therefore the output will not be uniform at all.

这在实践中是一个真正的问题吗?在 [0, n) 中选择随机数的更好方法是什么,从 rand() 输出统一派生,最好没有任何浮点运算?

Is this a real problem in practice? What is a better way of choosing random numbers in [0, n) uniformly deriving from rand() output, preferably without any floating point arithmetic?

推荐答案

你说得对,rand() % N 不是精确均匀分布的.确切地说,这有多重要取决于您想要的数字范围和您想要的随机程度,但是如果您想要足够的随机性以至于您甚至不关心它,您就不想使用 rand()无论如何.得到一个真正的随机数生成器.

You are correct, rand() % N is not precisely uniformly distributed. Precisely how much that matters depends on the range of numbers you want and the degree of randomness you want, but if you want enough randomness that you'd even care about it you don't want to use rand() anyway. Get a real random number generator.

也就是说,要获得真正的随机分布,请修改为 2 的下一个幂并进行采样,直到获得所需范围内的一个(例如,对于 0-9,使用 while(n = rand()%0x10 > 10);).

That said, to get a real random distribution, mod to the next power of 2 and sample until you get one in the range you want (e.g. for 0-9, use while(n = rand()%0x10 > 10);).

更多推荐

取模 N 的随机数的一致性

本文发布于:2023-10-24 09:01:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523514.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数   一致性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!