0

My problem is like this: I need to generate a random number from Gaussin/Norma distribution and create a histogram of a width of 0.1.

class Gaussian
{
    public static double Next(Random r, double mu = 0, double sigma = 1)
    {
        var u1 = r.NextDouble();
        var u2 = r.NextDouble();

        var rand_std_normal =   Math.Sqrt(-2.0 * Math.Log(u1)) *
                                Math.Sin(2.0 * Math.PI * u2);

        var rand_normal = mu + sigma * rand_std_normal;

        return rand_normal;
    }
}

I am using the above function to generate a Gaussian random value.

Now, in order to create a histogram, I am in need of such a calculation that is able to automatically convert the gaussian value into an array index. Something like the following:

    static void Main(string[] args)
    {
        const int N = 1000;
        int time = N;
        const double binsDistance = 0.1;
        int binsCount = (int)(N * binsDistance);

        Random rand = new Random();
        int[] array = new int[binsCount];
        int side = 0;
        for (int i = 0; i < time; i++)
        {
            double gauss = Gaussian.Next(rand);
            int binNo = Normalization.Normalize(0, binsCount - 1, gauss);
            array[binNo]++;
        }
    }

For that, I tried two calculations.

  1. the first one is here.
  2. the second one is here.

The problem with the first one is, it can't handle negative numbers properly.

The problem with the second one is, it is generating too many zero values.

So, I have two questions:

  1. What is the basic difference between #1 and #2?
  2. How can I achieve what I am trying to do?
user366312
  • 16,949
  • 65
  • 235
  • 452
  • First, Method 1 is for converting a number from 0 to 1 into a number from min to max, and so is not appropriate for a number from `Double.MinValue` to `Double.MaxValue`. – NetMage Apr 08 '20 at 21:04
  • Where did you get your Gaussian calculation? There seems something funny about it - the more you call it, the wider than range. – NetMage Apr 08 '20 at 21:11
  • @NetMage, https://bitbucket.org/Superbest/superbest-random/src/master/Superbest%20random/RandomExtensions.cs – user366312 Apr 08 '20 at 21:23

0 Answers0