Random Number Between 2 Double Numbers

2019-01-07 04:26发布

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

Example:

public double GetRandomeNumber(double minimum, double maximum)
{
    return Random.NextDouble(minimum, maximum) 
}

Then I call it with the following:

double result = GetRandomNumber(1.23, 5.34);

Any thoughts would be appreciated.

标签: c# random
10条回答
成全新的幸福
2楼-- · 2019-01-07 04:39

What if one of the values is negative? Wouldn't a better idea be:

double NextDouble(double min, double max)
{
       if (min >= max)
            throw new ArgumentOutOfRangeException();    
       return random.NextDouble() * (Math.Abs(max-min)) + min;
}
查看更多
够拽才男人
3楼-- · 2019-01-07 04:39
Random random = new Random();

double NextDouble(double minimum, double maximum)
{  

    return random.NextDouble()*random.Next(minimum,maximum);

}
查看更多
成全新的幸福
4楼-- · 2019-01-07 04:42

About generating the same random number if you call it in a loop a nifty solution is to declare the new Random() object outside of the loop as a global variable.

Notice that you have to declare your instance of the Random class outside of the GetRandomInt function if you are going to be running this in a loop.

“Why is this?” you ask.

Well, the Random class actually generates pseudo random numbers, with the “seed” for the randomizer being the system time. If your loop is sufficiently fast, the system clock time will not appear different to the randomizer and each new instance of the Random class would start off with the same seed and give you the same pseudo random number.

Source is here : http://www.whypad.com/posts/csharp-get-a-random-number-between-x-and-y/412/

查看更多
霸刀☆藐视天下
5楼-- · 2019-01-07 04:45

You could do this:

public class RandomNumbers : Random
{
    public RandomNumbers(int seed) : base(seed) { }

    public double NextDouble(double minimum, double maximum)
    {
        return base.NextDouble() * (maximum - minimum) + minimum;
    }
}
查看更多
劳资没心,怎么记你
6楼-- · 2019-01-07 04:48

Johnny5 suggested creating an extension method. Here's a more complete code example showing how you could do this:

public static class RandomExtensions
{
    public static double NextDouble(
        this Random random,
        double minValue,
        double maxValue)
    {
        return random.NextDouble() * (maxValue - minValue) + minValue;
    }
}

Now you can call it as if it were a method on the Random class:

Random random = new Random();
double value = random.NextDouble(1.23, 5.34);

Note that you should not create lots of new Random objects in a loop because this will make it likely that you get the same value many times in a row. If you need lots of random numbers then create one instance of Random and re-use it.

查看更多
放我归山
7楼-- · 2019-01-07 04:49

The simplest approach would simply generate a random number between 0 and the difference of the two numbers. Then add the smaller of the two numbers to the result.

查看更多
登录 后发表回答