Generates normally distributed numbers - CSharp System

CSharp examples for System:Math Statistics

Description

Generates normally distributed numbers

Demo Code


using System.Collections.Generic;
using System.Collections;
using System;/*ww  w.  j ava  2s .  co  m*/

public class Main{
        /// <summary>
        ///     Generates normally distributed numbers. Each operation makes two Gaussians for the price of one, and apparently
        ///     they can be cached or something for better performance, but who cares.
        /// </summary>
        /// <param name="r"></param>
        /// <param name="mu">Mean of the distribution</param>
        /// <param name="sigma">Standard deviation</param>
        /// <returns></returns>
        public static double NextGaussian(this Random r, double mu = 0, double sigma = 1)
        {
            var u1 = r.NextDouble();
            var u2 = r.NextDouble();

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

            var randNormal = mu + sigma*randStdNormal;

            return randNormal;
        }
        public static double NextDouble(this Random r, double minimum, double maximum)
        {
            return r.NextDouble() * (maximum - minimum) + minimum;
        }
}

Related Tutorials