Reputation: 30276
By my need in my application, I need to generate number from range 0 to 1, but with a little modify :
1. Range [0,1) : include 0 but not 1
2. Range (0, 1) : not include 0 nor 1
3. Range (0, 1] : same as 1. include 1 but not 0
4. Range [0,1]: include both 0 and 1
In C#, how can I random like this?
Upvotes: 1
Views: 161
Reputation: 700192
Number one is easy, that's what's returned from the NextDouble
method;
Random rnd = new Random();
double number = rnd.NextDouble();
To exclude the zero, pick a new number if you get a zero:
double number;
do {
number = rnd.NextDouble();
} while(number == 0.0);
To include 1 but not 0, subtract the random number from 1:
double number = 1.0 - rnd.NextDouble();
To include both 0 and 1, you would use an approach similar to what King King suggests, with a sufficiently large number for your need:
double number = (double)rnd.Next(Int32.MaxValue) / (Int32.MaxValue - 1);
(Using ints you can get 31 bits of precision. If you need more than that you would need to use NextBytes
to get 8 bytes that you can turn into a long.)
Upvotes: 3
Reputation: 63317
It depends on the precision you want, I suppose the precision is 0.001
, try this code:
var rand = new Random();
//1
var next = (float) rand.Next(1000)/1000;
//2
var next = (float) rand.Next(1,1000)/1000;
//3
var next = (float) rand.Next(1,1001)/1000;
//4
var next = (float) rand.Next(1001)/1000;
Upvotes: 2