Random Number Between 2 Double Numbers

后端 未结 12 2213
粉色の甜心
粉色の甜心 2020-11-27 10:25

Is it possible to generate a random number between 2 doubles?

Example:

public double GetRandomeNumber(double minimum, double maximum)
{
    return Ra         


        
12条回答
  •  没有蜡笔的小新
    2020-11-27 11:06

    Watch out: if you're generating the random inside a loop like for example for(int i = 0; i < 10; i++), do not put the new Random() declaration inside the loop.

    From MSDN:

    The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value...

    So based on this fact, do something as:

    var random = new Random();
    
    for(int d = 0; d < 7; d++)
    {
        // Actual BOE
        boes.Add(new LogBOEViewModel()
        {
            LogDate = criteriaDate,
            BOEActual = GetRandomDouble(random, 100, 1000),
            BOEForecast = GetRandomDouble(random, 100, 1000)
        });
    }
    
    double GetRandomDouble(Random random, double min, double max)
    {
         return min + (random.NextDouble() * (max - min));
    }
    

    Doing this way you have the guarantee you'll get different double values.

提交回复
热议问题