...

/

Fix the Trivial Problems

Fix the Trivial Problems

In this lesson, we will begin redesigning the Random library and have a look at the performance issues.

In the previous lesson, we discussed the shortcomings of System.Random. In this lesson, we will begin redesigning the Random library.


First Attempt to Fixing Random

The first thing we want is two static methods, one that gives me an actually-random integer from 0 to Int32.MaxValue, and one that gives us a random double from 0.00.0 (inclusive) to 1.01.0 (exclusive). Not pseudo-random, but indistinguishable from a true random uniform distribution.

Here’s an attempt:

using CRNG = System.Security.Cryptography.RandomNumberGenerator;
public static class BetterRandom
{
  private static readonly ThreadLocal<CRNG> crng = new ThreadLocal<CRNG>(CRNG.Create);
  private static readonly ThreadLocal<byte[]> bytes =
    new
...