mardi 26 février 2019

c# Flawed random generator [duplicate]

This question already has an answer here:

This is simulation of the famous St. Petersburg Paradox

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sorrow
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rnd = new Random(Environment.TickCount);
            double totalSum = 0;
            int bigWins = 0;
            double iterations = 1000;
            for (int z = 0; z < 10; z++)
            {
                iterations *= 10;
                for (double i = 1; i < iterations; i++)
                {
                    int sum = 2;
                    int a = 1;
                    while (a == 1)
                    {
                        //generate a random number between 1 and 2
                        a = rnd.Next(1, 3);

                        if (a == 1)
                        {
                            sum *= 2;
                        }
                        if (sum > 8000)
                        {
                            // if the sum is over 8000 that means that it scored 1 13 times in a row (2^13) - that should happen
                            //once every 8192 times. Given that we run the simulation 100 000 000 times it should hover around 
                            // 100 000 000/8192
                            //However is much , much bigger
                            bigWins++;
                        }
                    }

                    totalSum += sum;

                }

                Console.WriteLine("Average gain over : "+iterations+" iterations is:" + totalSum / iterations);
                Console.WriteLine("Expected big wins: " + iterations / 8192 + " Actual big wins: " + bigWins);
                Console.WriteLine();
            }


        }
    }
}

As you can see we should expect 7 times smaller number. That means that c# random is very prone to choosing the same number over and over again? Is it true or there is something wrong with my code? How can we fix it to true random?




Aucun commentaire:

Enregistrer un commentaire