C # random number generator stuck in loop

I use .NET to create an artificial life program, and I use the C # pseudo-random class defined in Singleton. The idea is that if I use the same random number generator in the whole application, I could just save the seed and then reload from the seed to double-check some interesting run.

public sealed class RandomNumberGenerator : Random
{
    private static readonly RandomNumberGenerator instance = new RandomNumberGenerator();

    RandomNumberGenerator()
    {

    }

    public static RandomNumberGenerator Instance
    {
        get
        {
            return instance;
        }
    }
}

I also need a method that could give me two different random numbers.

public static Tuple<int, int> TwoDifferentRandomNumbers(this Random rnd, int minValue, int maxValue)
    {
        if (minValue >= maxValue)
            throw new ArgumentOutOfRangeException("maxValue", "maxValue must be greater than minValue");
        if (minValue + 1 == maxValue)
            return Tuple.Create<int, int>(minValue, maxValue);

        int rnd1 = rnd.Next(minValue, maxValue);
        int rnd2 = rnd.Next(minValue, maxValue);
        while (rnd1 == rnd2)
        {                
            rnd2 = rnd.Next(minValue, maxValue);
        }
        return Tuple.Create<int, int>(rnd1, rnd2);            
    }

The problem is that sometimes it rnd.Next(minValue,maxValuealways returns minValue. If at this moment I stop at a point and try to create a double and set it to rnd.NextDouble(), it will return 0.0. Does anyone know why this is happening?

, , , , , 0. ... ?

EDIT: , .

.

 public sealed class RandomNumberGenerator : Random
{
    private static Random _global = new Random();
    [ThreadStatic]
    private static Random _localInstance;

    RandomNumberGenerator()
    {

    }

    public static Random Instance
    {
        get
        {
            Random inst = _localInstance;
            if (inst == null)
            {
                int seed;
                lock (_global) seed = _global.Next();
                _localInstance = inst = new Random(seed);
            }
            return _localInstance;
        }
    }
}
+5
4

RNG , , , , RNG .

/ , RNG .

, , 100% , RNG , , .

+3

Random .

static [ThreadStatic] .

+11

, , , , .

RNG. Random seed, ​​ .

: , .

+1

I don’t even have to look for a Random class that knows "all instance methods of this class are not thread safe." This applies to all .NET classes, with very few exceptions.

So this is multithreading. But you have not indicated that MaxValue> MinValue either.

+1
source

All Articles