Why does the Random.Next method in .NET support float / double?

So maybe I want values ​​between -1.0 and 1.0 as float. It's awkward to write this and anchor it on top with IMO extension methods.

0


source to share


8 answers


public static double NextDouble(this Random rnd, double min, double max){
    return rnd.NextDouble() * (max - min) + min;
}

      

Call using:



double x = rnd.NextDouble(-1, 1);

      

to get a value in the range -1 <= x < 1

+14


source


There is a method .NextDouble()

that does almost what you want - just 0 to 1.0 instead of -1.0 to 1.0.



+18


source


Because most of the time, we want to use int within a range, so we have been provided with methods for that. Many languages ​​only support a random method that returns a double between 0.0 and 1.0. C # provides this functionality in the .NextDouble () method.

This is a decent enough design as it makes it simple (Rolling a die - myRandom.Next (1,7);) and still possible. - myRandom.NextDouble () * 2.0 - 1.0;

+4


source


You can use the Random.NextDouble () method which will generate a random value between 0.0 and 1.0 as suggested by @Joel_Coehorn

I just want to add that expanding the range to -1.0 and 1.0 is a simple calculation

var r = new Random();

var randomValue = r.NextDouble() * 2.0 - 1.0

      

Or, to generalize it to expand the result NextDouble()

to any range (a, b), you can do this:

var randomValue = r.NextDouble() * (b - a) - a

      

+3


source


On the side of the note, I would have to point out that finally the random number generation algorithm in the framework is not something clumsy (like cstdlib rand()

), but actually a good implementation (Park & ​​Miller, IIRC).

+1


source


The vast majority of random number use I've seen (actually all I've ever seen, though apparently over three decades of programming that I've not seen) generate random integers in the specified range.

Hence Random.Next seems to be very convenient to me.

0


source


Awkward to write this and secure it on top with extension methods

Not really - extension methods are terse and I'm glad the function exists for this kind of thing.

0


source


This method is not that hard to add, seems ideal when using an extension method.

public double NextSignedDouble(this Random r)
{
    return (r.Next(0, 2) == 0) ? r.NextDouble() : (r.NextDouble() * -1);
}

      

0


source







All Articles