The answer provided by @Backlin is the most straightforward way to go about doing this, but note that if you care about the distribution of the end result, you have to think carefully about how you are drawing your samples. For example, here is the result of 1 million draws from a random uniform using the straightforward method:
> a <- runif(1000000)
> mult <- 0.125
> samp <- mult * round(a/mult)
> table(samp)
samp
0 0.125 0.25 0.375 0.5 0.625 0.75 0.875 1
62889 125172 124564 125096 125443 124716 124899 124988 62233
Notice that even though the original data were drawn from a uniform [0,1]
distribution, 0 and 1 are underrepresented in the distribution of the rounded distribution. If you really wanted a random sample from a uniform between [0,1]
in increments of 0.125
, I would use sample
and seq
:
> rng <- seq(0, 1, 0.125)
> samp <- sample(rng, 1000000, replace=TRUE)
> table(samp)
samp
0 0.125 0.25 0.375 0.5 0.625 0.75 0.875 1
111206 111209 111222 110972 110617 111200 110827 111199 111548
This is how I would suggest you draw from a uniform distribution. If you want to put different weights on the possible results, you could use the prob
argument to sample
.
If you are wanting to draw from a different distribution that doesn't have a clearly defined upper and lower bound, such as the normal distribution, you may or may not have similar problems. You will need to think carefully and run many tests to make sure you are getting the distribution you want.