Generates values from a triangular distribution. - CSharp System

CSharp examples for System:Math Geometry

Description

Generates values from a triangular distribution.

Demo Code


using System.Collections.Generic;
using System.Collections;
using System;//w  w  w .ja  v  a  2  s. c o  m

public class Main{
        /// <summary>
        ///     Generates values from a triangular distribution.
        /// </summary>
        /// <remarks>
        ///     See http://en.wikipedia.org/wiki/Triangular_distribution for a description of the triangular probability
        ///     distribution and the algorithm for generating one.
        /// </remarks>
        /// <param name="r"></param>
        /// <param name="a">Minimum</param>
        /// <param name="b">Maximum</param>
        /// <param name="c">Mode (most frequent value)</param>
        /// <returns></returns>
        public static double NextTriangular(this Random r, double a, double b, double c)
        {
            var u = r.NextDouble();

            return u < (c - a)/(b - a)
                ? a + Math.Sqrt(u*(b - a)*(c - a))
                : b - Math.Sqrt((1 - u)*(b - a)*(b - c));
        }
        public static double NextDouble(this Random r, double minimum, double maximum)
        {
            return r.NextDouble() * (maximum - minimum) + minimum;
        }
}

Related Tutorials