It's there any function in Matlab that generates random real numbers in a closed interval. I found something with unifrnd()
but it's generating numbers in an open interval.
If I use unifrnd(x,y);
I get (x,y) interval, instead of [x,y].
Asked
Active
Viewed 2,593 times
3

Alex Chihaia
- 103
- 2
- 15
-
1Can you even tell the difference besides in trivial case? (i.e. where your interval is a single point). Isn't the probability of the endpoints infinitesimal for reals? – hiandbaii May 10 '16 at 17:14
-
Yes, I know, but I have to take those cases into consideration. This is the problem. – Alex Chihaia May 10 '16 at 17:19
-
6Actually, the mathematical probability of choosing any particular point, including the endpoints, from a continuous interval is 0. @hiandbaii is correct...there is no mathematical difference. The digital representation of the numbers means that in reality, the computer is selecting from a discrete distribution, with a maximum resolution of about 1e-16, so if you were running on the interval `[0,1]`, vs `(0,1)`, you would have to run about `(10^16)/2` trials to notice a difference. – gariepy May 10 '16 at 17:35
-
@gariepy The maximum is actually `eps = 2.2204e-16` so you are indeed correct. Your comment I couldn't have said any better. – rayryeng May 10 '16 at 17:47
-
1It's a good idea to be aware of which type of interval a generator has. If your code is sensitive to cancellation that might occur up the tiny chance of a `0` or `1`, then it's a good idea to use a generator that has an open interval. Otherwise the two are virtually interchangeable. – horchler May 10 '16 at 18:01
1 Answers
3
Given the discussion of accuracy in the comments, you could use something like:
mag = floor(log10( y - x))
num = unifrnd(x-(10^mag)*eps, y+(10^mag)*eps)
This essentially adds one "point" to the discrete interval representation, taking into account the accuracy based on the size of the numbers you're using. unifrnd()
is essentially a wrapper around rand()
(which means you don't really need the stats toolbox to do this), and thus it is really just scaling the uniform distribution on (0,1). If you're worried about the endpoints though, that matters, because you can't get more granular than the product the magnitude of your interval length with eps
.

gariepy
- 3,576
- 6
- 21
- 34