0
$\begingroup$

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?

$\endgroup$
3
  • 3
    $\begingroup$ RandomReal[{0,1-$MachineEpsilon}]? $\endgroup$
    – march
    Aug 15, 2017 at 17:17
  • 3
    $\begingroup$ 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. $\endgroup$
    – Searke
    Aug 15, 2017 at 17:28
  • 2
    $\begingroup$ 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]] $\endgroup$
    – Searke
    Aug 15, 2017 at 17:29

1 Answer 1

-5
$\begingroup$

One approach:

If[(a = RandomReal[]^{100}) == 1., 1-RandomReal[], a]
$\endgroup$
5
  • $\begingroup$ ...but not zero, since there are a finite number of machine precision numbers between 0 and 1. $\endgroup$
    – march
    Aug 15, 2017 at 17:18
  • $\begingroup$ myRand[] := With[{rnd=RandomReal[]}, If[rnd==1.,myRand[],rnd]] $\endgroup$
    – Searke
    Aug 15, 2017 at 17:20
  • 1
    $\begingroup$ tl;dr use rejection sampling via recursion. That's the easy, off the cuff, kind of solution. $\endgroup$
    – Searke
    Aug 15, 2017 at 17:22
  • $\begingroup$ 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. $\endgroup$
    – Searke
    Aug 15, 2017 at 17:26
  • 3
    $\begingroup$ 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. $\endgroup$
    – Carl Woll
    Aug 15, 2017 at 17:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.