# How to get a random real number in the half-open interval [0.0,1.0)? [duplicate]

As far as I understand, RandomReal[] is able to generate random numbers between 0.0 and 1.0 so thinking in Terms of an interval this means [0.0,1.0]. Now I want to exclude explicitly the value 1.0, meaning to have a half-open interval like: [0.0,1.0).

Is their an easy way to do that?

• RandomReal[{0,1-\$MachineEpsilon}]? Commented Aug 15, 2017 at 17:17
• Ignoring the fact that we're working with Floating point numbers, you should know that this question doesn't make sense for Real numbers. The chance of getting 0 or 1 is 0. Commented Aug 15, 2017 at 17:28
• It's not clear from what documentation I've read that you can even get 0 or 1 from RandomReal, but if you want to ensure that you don't get them, then use rejection sampling. Something like myRand[] := With[{rnd=RandomReal[]}, If[rnd==1.,myRand[],rnd]] Commented Aug 15, 2017 at 17:29

One approach:

If[(a = RandomReal[]^{100}) == 1., 1-RandomReal[], a]

• ...but not zero, since there are a finite number of machine precision numbers between 0 and 1. Commented Aug 15, 2017 at 17:18
• myRand[] := With[{rnd=RandomReal[]}, If[rnd==1.,myRand[],rnd]] Commented Aug 15, 2017 at 17:20
• tl;dr use rejection sampling via recursion. That's the easy, off the cuff, kind of solution. Commented Aug 15, 2017 at 17:22
• It's also just problematic because returning 0 if you get 1 doubles the chances of getting 0 compared to other numbers, meaning it's no longer uniform and also it's not clear that RandomReal contains 0 or 1. Commented Aug 15, 2017 at 17:26
• If RandomReal[] returned 0.99999999999999, the test 0.99999999999999 == 1. would return True because Equal uses a tolerance of 2 bits. But, there are many machine numbers between 0.99999999999999 and 1., so it should not be rejected. Commented Aug 15, 2017 at 17:33