algorithm - 如何使用生成 1 到 5 的函数生成 1 到 7 之间的随机数

标签 algorithm math random

<分区>

Possible Duplicate:
Expand a random range from 1-5 to 1-7

我理解使用拒绝抽样的解决方案,即

public static int rand7() {
    while (true) {
       int num = 5 * (rand5() - 1) + (rand5() - 1);
       if (num < 21) return (num % 7 + 1);
    }
}

但我正在考虑另一种解决方案,即 rand5() 被调用 7 次,结果除以 5,但我不确定这是否正确。请让我知道是否是。

public static int rand7() {    
    int num = rand5()+rand5()+rand5()+rand5()+rand5()+rand5()+rand5();
    return num/5;
}

编辑: 看起来生成 1 的概率是 (1/5)^7,但生成 2 的概率是 7*(1/5)^7。它不均匀,因此无法正常工作。

最佳答案

它不会是均匀分布的(看起来很正常)。正如保罗所说,证明来自 Central Limit Theorem .

enter image description here

关于algorithm - 如何使用生成 1 到 5 的函数生成 1 到 7 之间的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6967274/

相关文章:

c# - 从状态向量中找到真正的异常

java - 如何在 Java 中的数组中存储随机且唯一的数字?

android - 使用 Haversine 公式创建方法,Android V2

php - 模拟头部或尾部

javascript - 从 API 随机生成国家/地区名称

algorithm - Knuth-Morris-Pratt 和 Boyer-Moore 搜索算法之间的主要区别是什么?

algorithm - k表示聚类样本数据

组织矩阵以使邻居最接近的算法

html - 如果当前字体中不存在,浏览器如何更改字体粗细?

java - 简单的 Java 数学运算