gpt4 book ai didi

java - Java的Random Object是不是通过均等的机会来产生随机数的?

转载 作者:行者123 更新时间:2023-11-29 06:09:54 25 4
gpt4 key购买 nike

我正在尝试编写一个简短的程序来为我玩骰子游戏(普通的 6 面骰子)。第一卷的数字被添加到分数中。第一次掷骰后,如果我掷出 6,则游戏停止并记录分数(不加上 6)。如果第一次掷出 6,那很好,它会像任何其他数字 1 到 5 一样被添加。我正在尝试运行这个游戏的一系列迭代,这样我就有了一个很长的分数列表(a半身像是滚动的 6)。我将这些分数重新排列为从小到大的顺序,然后找到列表的中位数,即最适合停止的分数。

出于某种原因,当我运行程序时,我总是得到 13,但我知道答案应该是 15。在 Java 中使用 Random 会对中位数产生某种影响吗?我不完全知道 Random 如何生成数字以及它是否以平等的机会创造它们。另外,有没有什么东西突然出现但不应该起作用?

import java.util.*;
public class DiceRoller {

private static Random r = new Random();
private static final int games = 10001;
private static int[] totalScores = new int[games];
private static int index = 0;

public static void main(String[] args) {
int score = 0; boolean firstRoll = true;
while (index < games) {
int roll = roll();
if (firstRoll) {
score += roll;
firstRoll = false;
} else {
if (roll == 6) {
totalScores[index] = score;
index++;
score = 0; firstRoll = true;
} else {
score += roll;
}
}
}
System.out.println("The median is " + median() + ".");
}

public static int roll() {
return r.nextInt(6) + 1;
}

public static int median() {
Arrays.sort(totalScores);
int temp = totalScores[games / 2];
return temp;
}

}

最佳答案

您得到 13 因为这是正确的结果。一点数学知识:如果 S 是代表这些游戏中任何一场得分的随机变量,那么您可以考虑 Probability generating function Sf(z)。从游戏的描述来看,这个概率生成函数满足方程:

f(z) = (z + z^2 + z^3 + z^4 + z^5 + z^6)/36 + f(z)(z + z^2 + z^ 3 + z^4 + z^5)/6

这需要一些思考,或者熟悉这种结构:右侧的左侧项考虑了在简单的 2 掷游戏中获得 1 到 6 的概率;涉及 f(z) 的右侧项考虑了涉及 3 次或更多次掷骰的游戏,用最后的 pre-6 掷骰(必须在 1 到 5 范围内)和前面的掷骰来表示它们,其概率我们可以再次使用f递归表达。

无论如何,走到这一步之后,我们可以重新安排将f描述为z的有理函数,然后展开为幂级数,开始:

f(z) = 1/36*z + 7/216*z^2 + 49/1296*z^3 + 343/7776*z^4 + 2401/46656*z^5 + 16807/279936*z^6 + 63217/1679616*z^7 + 388087/10077696*z^8 + 2335585/60466176*z^9 + 13681927/362797056*z^10 + 77103313/2176782336*z^ 11 + 409031959/13060694016 *z^12 + 2371648321/78364164096*z^13 + 13583773735/470184984576*z^14 + ...

(我用 Pari/GP 得到这个。)

z^k的系数则描述了游戏值为k的概率;因此,得分为 1 的概率为 36 分之一,得分为 2 的概率为 216 分之 7,依此类推。前 12 个系数之和为 0.472828864487196328...,而前 13 个系数之和为 0.5030933144224321950968...。所以中位数确实是 13。

为了提供独立检查,我编写了一个快速的 Python 程序:

from __future__ import division
import random

def roll():
return random.randint(1, 6)

def play():
score = roll()
while True:
throw = roll()
if throw == 6:
break
score += throw
return score

all_scores = sorted(play() for _ in xrange(1000001))
print "median is: ",all_scores[len(all_scores) // 2]
print "fraction of scores <= 12: ",all_scores.index(13) / len(all_scores)
print "fraction of scores <= 13: ",all_scores.index(14) / len(all_scores)

果然,结果如下:

iwasawa:~ mdickinson$ python dice_game.py 
median is: 13
fraction of scores <= 12: 0.472811527188
fraction of scores <= 13: 0.502863497137

因此,为了回答您的问题,您看到的结果并不是 Java 随机数生成存在任何弱点的证据。

关于java - Java的Random Object是不是通过均等的机会来产生随机数的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7297660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com