dimanche 8 avril 2018

Weird behaviour in random generation

Well, I was in a moment of pure creativity(two months ago) and decided to create this piece of code using new classes and resources learned previously:

using System;

public static class Program
{
    static Random _rndm;
    static int i = 0;
    static float sum = 0;

    public static void Main(string[] args)
    {
        Init();
        Console.Write("Please, enter a number: ");
        float c = float.Parse(Console.ReadLine());
        while(i < c)
        {
            int randomValue = _rndm.Next(0, i);
            sum += randomValue;
            i++;
        }
        Console.WriteLine("Prediction : {0}", c / 4f);
        Console.WriteLine("Correct value : {0}", sum / c);
        Console.WriteLine("Error: {0}", Math.Abs((c / 4f) - (sum / c)));
        i = 0;
        sum = 0;
        Main(null);
    }

    public static void Init()
    {
        if(_rndm == null)
        {
            _rndm = new Random();
        }
    }
}

As you can test here(try numbers higher than 1000), the prediction and the correct value are so close one from another and I am just wondering how can it be possible that the summation of a sequence of random numbers is aproximately the same value of the iterations over four, can someone explain it? Sorry for my bad English, I tried the best.




Aucun commentaire:

Enregistrer un commentaire