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

NextBool() public method

Generates a single random bit. This method's performance is improved by generating 32 bits in one operation and storing them ready for future calls.
public NextBool ( ) : bool
return bool
        public bool NextBool()
        {
            if(0 == _bitMask)
            {
                // Generate 32 more bits.
                uint t = _x^(_x<<11);
                _x=_y; _y=_z; _z=_w;
                _bitBuffer=_w=(_w^(_w>>19))^(t^(t>>8));

                // Reset the bitMask that tells us which bit to read next.
                _bitMask = 0x80000000;
                return (_bitBuffer & _bitMask)==0;
            }

            return (_bitBuffer & (_bitMask>>=1)) == 0;
        }

Usage Example

Example #1
0
        public void NextBool()
        {
            int sampleCount = 10000000;
            XorShiftRandom rng = new XorShiftRandom();

            int trueCount = 0, falseCount = 0;
            double maxExpectedCountErr = sampleCount / 25.0;

            for(int i=0; i<sampleCount; i++) {
                if(rng.NextBool()) trueCount++; else falseCount++;
            }

            double countErr = Math.Abs(trueCount - falseCount);
            if(countErr > maxExpectedCountErr) Assert.Fail();
        }