如何让 Math.random() 调用在 4 种情况下具有绝对相等的概率? (即情况 1 为 0.25,情况 2 为 0.25,情况 3 为 0.25,情况 4 为 0.25)?
我目前得到案例 1 的 0.05、案例 2 的 0.075、案例 3 的 0.45 和案例 4 的 0.425。
一直试图弄清楚为什么它这样做了几个小时但收效甚微。
int direction = 0;
// Select a random number
randno = (int) Math.round(Math.random() * 3);
// Convert this to a direction
while (direction == 0) {
if (randno == 0 && !isWall(robot, Robot.LEFT)) direction = Robot.LEFT;
else if (randno == 1 && !isWall(robot, Robot.RIGHT)) direction = Robot.RIGHT;
else if (randno == 2 && !isWall(robot, Robot.BEHIND)) direction = Robot.BEHIND;
else if (!isWall(robot, Robot.AHEAD)) direction = Robot.AHEAD;
else randno = (int) Math.round(Math.random() * 3);
}
最佳答案
Math.random() * 3
产生 [0, 3)
范围内的值。
将 Math.round
应用到这意味着:
[0, 0.5)
变为 0。- 3 中的 0.5 表示 1/6 概率。[0.5, 1.5)
变为 1 - 是上述范围的两倍,2/6th[1.5, 2.5)
变为 2 - 同上,2/6th[2.5, 3)
变成 3。又是 1/6。
接下来,您还将那些分布不均匀的数字与 isWall
结合起来。特别是像 (randno == 0 && isWall(robot, Robot.LEFT))
(值为 0 但有一堵墙)这样的情况也被添加到最后一个情况。
你真正需要的是 a) 像
这样的方法double probability = Math.random();
if (probability < 0.25) {
..
没有搞砸分发。
b) 不要让选择失败。即使是代码中的最后一个案例也需要通过 randno
进行限制,否则它会吞噬掉不属于那里的案例。
此外,您可能还需要重新考虑要测量的内容。当它决定向左走但有一堵墙时,你怎么算它?选择可以是均匀的,但墙壁不在乎。只有在没有墙壁的情况下才能实现完美的均匀分布。
关于java - Java 中的等概率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33447113/