So maybe I want to have values between -1.0 and 1.0 as floats. It's clumsy having to write this and bolt it on top using extension methods IMO.
There's a .NextDouble()
method as well that does almost exactly what you want- just 0 to 1.0 instead of -1.0 to 1.0.
The vast majority of random number usage I've seen (in fact all I've ever seen, although apparently in 3 decades of programming I haven't seen much) is generating random integers in a specified range.
Hence Random.Next seems very convenient to me.
Because most of the time, we want an int within a range, so we were provided with methods to do 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 decent enough design, as it makes the common easy (Rolling a die - myRandom.Next(1,7);) and everthing else possible. - myRandom.NextDouble() * 2.0 - 1.0;
It's clumsy having to write this and bolt it on top using extension methods
Not really - extension methods are succinct and I'm glad the feature is there for things like this.
You can use the Random.NextDouble() method which will produces a random value between 0.0 and 1.0 as @Joel_Coehorn's suggested
I just want to add that, extending 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 extend NextDouble()
result to any range (a, b), you can do this:
var randomValue = r.NextDouble() * (b - a) - a
On a side note, I'd have to point out that, at last, the random-number generation algorithm in a framework is not something clumsy (like cstdlib's rand()
) but actually a good implementation (Park&Miller, IIRC).
This method isn't that hard to add, seems like the perfect usage of an extension method.
public double NextSignedDouble(this Random r)
{
return (r.Next(0, 2) == 0) ? r.NextDouble() : (r.NextDouble() * -1);
}
public static double NextDouble(this Random rnd, double min, double max){
return rnd.NextDouble() * (max - min) + min;
}
Call with:
double x = rnd.NextDouble(-1, 1);
to get a value in the range -1 <= x < 1