c# - 随机概率计算不准确
问题描述
我有一个游戏,出口会触发一种骰子,可以引导你进入随机关卡。我有这个脚本可以做到这一点:
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
编辑:我的数学错了,代码实际上可以正常工作
解决方案
您需要将新的 Random 拉出循环。
System.Random rnd = new System.Random();
for (int i = 0; i < 2000; i++) //Run the test 2000 times
{
种子是基于时间的,因此它会在多个循环中获得相同的种子。
推荐阅读
- mysql - 使用 Windows 的 cmd 重置 MySQL 密码后,我无法在 NodeJs 中启动 MySQL 服务器
- tfsbuild - 对 TFS 2017 Gated Build 中的已提交更改和其他功能运行持续集成触发器的确切用途是什么?
- syntax - 我试图运行以下查询,但它显示语法错误
- forms - 使用 vuex 发布表单数据
- python - 通过 PIP 在 opencv-python 中没有最新的(4.3.0.)openCV 库
- angular - 如果 TestBed.inject() 或 TestBed.get() (已弃用)之前运行过,则 TestBed.OverrideProvider() 不起作用
- spring - Spring Data repository:将获取大小设置为参数
- react-admin - 通过
- 将值过滤到操作组件 (REACTADMIN)
- statistics - 线性回归中相关系数与相关确定的相关系数
- python-3.x - AWS弹性beantalk部署总是失败(上传一个zip文件)