Redzen.Numerics.XorShiftRandom.NextDouble C# (CSharp) Method

NextDouble() public method

Generates a random double. Values returned are over the range [0, 1). That is, inclusive of 0.0 and exclusive of 1.0.
public NextDouble ( ) : double
return double
        public double NextDouble()
        {
            uint t = _x^(_x<<11);
            _x=_y; _y=_z; _z=_w;

            // N.B. Here we're using the full 32 bits of randomness, whereas System.Random uses 31 bits.
            return REAL_UNIT_UINT * (_w=(_w^(_w>>19))^(t^(t>>8)));
        }

Usage Example

        /// <summary>
        /// Sample from the provided discrete probability distribution.
        /// </summary>
        /// <param name="dist">The discrete distribution to sample from.</param>
        /// <param name="rng">Random number generator.</param>
        public static int Sample(DiscreteDistribution dist, XorShiftRandom rng)
        {
            // Throw the ball and return an integer indicating the outcome.
            double sample = rng.NextDouble();
            double acc = 0.0;
            for(int i=0; i<dist.Probabilities.Length; i++)
            {
                acc += dist.Probabilities[i];
                if(sample < acc) {
                    return dist.Labels[i];
                }
            }

            // We might get here through floating point arithmetic rounding issues.
            // e.g. accumulator == throwValue.

            // Find a nearby non-zero probability to select.
            // Wrap around to start of array.
            for(int i=0; i<dist.Probabilities.Length; i++)
            {
                if(0.0 != dist.Probabilities[i]) {
                    return dist.Labels[i];
                }
            }

            // If we get here then we have an array of zero probabilities.
            throw new InvalidOperationException("Invalid operation. No non-zero probabilities to select.");
        }
All Usage Examples Of Redzen.Numerics.XorShiftRandom::NextDouble