首页 > 解决方案 > 随机概率计算不准确

问题描述

我有一个游戏,出口会触发一种骰子,可以引导你进入随机关卡。我有这个脚本可以做到这一点:

public string levelToLoad; // first level
public bool levelSplit; //Do we split?
public string levelToSplit; //second levl
public int splitLevelChance; //if the chance was 4/7, this should be the 4
public int SplitDenominator; //And this should be the 7

int normal = 0;  //To keep count
int split = 0;

for (int i = 0; i < 2000; i++) //Run the test 2000 times
{
    System.Random rnd = new System.Random();

    int dice = rnd.Next(1, SplitDenominator + 1); //Roll a dice
    print(dice);

    if (dice <= splitLevelChance)
    {
        normal++;
      //  SceneManager.LoadScene(levelToLoad);
    }
    else
    {
        split++;
       // SceneManager.LoadScene(levelToSplit);
    }
}

print("normal: " + normal);
print("split:" + split);

所以这适用于 1/4 或 1/8 之类的东西,但是当我这样做时,例如 8/ 18 它是不准确的。

以下是我对 8/18 所做的测试

测试 1 - 正常 = 899,拆分 = 1101

测试 2 - 正常 = 879,拆分 = 1121

测试 3 - 正常 = 885,拆分 = 1115

如果我的数学是正确的,正常应该在 615 左右并拆分 1385

编辑:我的数学错了,代码实际上可以正常工作

标签: c#unity3d

解决方案


您需要将新的 Random 拉出循环。

System.Random rnd = new System.Random();
for (int i = 0; i < 2000; i++) //Run the test 2000 times
{

种子是基于时间的,因此它会在多个循环中获得相同的种子。


推荐阅读