1

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?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
hqt
  • 29,632
  • 51
  • 171
  • 250
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Dec 03 '13 at 02:51
  • 2
    If you're creating a `double`-precision random number, the odds of exactly zero or exactly one coming up is vanishingly small. What exactly are you trying to do? – James Cronen Dec 03 '13 at 02:53
  • How about ["How do you generate a random number in C#?"](http://stackoverflow.com/questions/44408/how-do-you-generate-a-random-number-in-c) – Scony Dec 03 '13 at 02:54
  • @Scony - the question you suggested does not talk about open/closed intervals for results... – Alexei Levenkov Dec 03 '13 at 02:59
  • @Alexei Levenkov - Right, but it shows method. If you understand method, open/closed intervals are trivial – Scony Dec 03 '13 at 03:04

2 Answers2

3

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.)

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
2

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;
King King
  • 61,710
  • 16
  • 105
  • 130