If I want to sample from a continuous uniform distribution with interval $(a,b]$, how can I do it in R? Or is it just the same as sampling from $(a,b)$ in R using

runif(1,min = a, max = b)


  • 1
    $\begingroup$ What makes you think runif samples from [a,b]? The help suggests it's usually otherwise (and explicitly states it is otherwise for the default). [As for your question, one thing to keep in mind is that what you actually get is a discrete distribution, not a truly continuous one] $\endgroup$
    – Glen_b
    Aug 24, 2013 at 9:29
  • $\begingroup$ you mean the samples i obtain from U(a,b] will be discrete ? $\endgroup$ Aug 24, 2013 at 9:36
  • 2
    $\begingroup$ Necessarily so. There's a smallest possible gap between two floating point numbers. You can't get values between them. The mathematical notion of closed and open is somewhat less clearly what you intended when it comes to numbers represented on computers. $\endgroup$
    – Glen_b
    Aug 24, 2013 at 9:37
  • $\begingroup$ Many pseudorandom number generators return values in $[0,1)$, or in $(0,1]$, and not in $[0,1]$ or $(0,0)$; that is, one end point is one of the possible values returned by a call to the generator, but the other is not. In such a case, it is straightforward to map $(0,1]$ onto $(a,b]$, and only slightly more cumbersome to map $[0,1)$ to $(a,b]$, assuming that it is particularly important in your simulation that $b$ is possibly one of the values returned by the generator. $\endgroup$ Aug 24, 2013 at 14:16
  • $\begingroup$ Perhaps the simplest solution is just to reject the result when $a$ is returned and try again. The chance of this happening in theory is zero and in practice is extremely small, almost always less than $2^{-31}$ in any system. $\endgroup$
    – whuber
    Aug 24, 2013 at 14:33

1 Answer 1


As shown in the R Documentation: runif will not generate either of the extreme values unless max = min or max-min is small compared to min, and in particular not for the default arguments. So generally you don't have to worry about that.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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