基于百分比的概率 [英] Percentage Based Probability

查看:76
本文介绍了基于百分比的概率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码段:

Random rand = new Random();
int chance = rand.Next(1, 101);

if (chance <= 25) // probability of 25%
{
    Console.WriteLine("You win");
}
else
{
    Console.WriteLine("You lose");
}

我的问题是,它真的计算出25%的获胜概率吗?在这里为玩家赢得胜利的机会真的是25%吗?

My question is, does it really calculate a 25% probability for winning here? Is the chance of winning for the player here is really 25%?

我只是这样写的:

        double total = 0;
        double prob = 0;
        Random rnd = new Random();
        for (int i = 0; i < 100; i++)
        {
            double chance = rnd.Next(1, 101);
            if (chance <= 25) prob++;
            total++;
        }
        Console.WriteLine(prob / total);
        Console.ReadKey();

这是非常不准确的.大约是0.15到0.3.

And it's highly inaccurate. It goes from about 0.15 to 0.3.

但是,当我进行更多检查(从(i< 100)更改为(i< 10000))时,它会更加准确.

But when I do more checks (change from (i < 100) to (i < 10000)) it's much more accurate.

这是为什么?为什么100张支票不够准确?

Why is this? Why aren't 100 checks enough for it to be accurate?

推荐答案

这很容易检查自己:

Random rand = new Random(); 
int yes = 0;
const int iterations = 10000000;
for (int i = 0; i < iterations; i++)
{
   if (rand.Next(1, 101) <= 25)
   {
       yes++;
   }
}
Console.WriteLine((float)yes/iterations);

结果:

0.2497914

结论:是的,是的.

只是为了好玩,LINQy版本:

Just for fun, the LINQy version:

Random rand = new Random(); 
const int iterations = 10000000;
int sum = Enumerable.Range(1, iterations)
                    .Count(i => rand.Next(1, 101) <= 25);
Console.WriteLine(sum / (float)iterations);

这篇关于基于百分比的概率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆