3

I'm writing a roulette simulator and I stuck just on the beginning. I wanted to draw integer from 0 to 36, so I used runif(). I noticed that 0's are outstanding. Have a look:

n=1000000
x=floor(runif(n,0,37))
hist(x,breaks=37)

Histogram: floor(runif(n,0,37))

To remove "0's" i wrote:

n=1000000
x=floor(runif(n,0,37)*100)/100
hist(x,breaks=37)

What gave me

Histogram: enter image description here

And my question is why it works?

KryptonLC
  • 70
  • 9
  • 1
    No, it's not a problem with runif. Try this instead `plot(density(x))` the issue is with where the breaks in your histogram are being placed, and that there's a fencepost problem at work – Shape Dec 29 '15 at 15:29
  • 3
    @Shape, post as answer ? (OP may want to consider `sample(0:36,size=1e6,replace=TRUE)` ...) – Ben Bolker Dec 29 '15 at 15:30
  • I know I've written an answer on another question about this somewhere...there, found it! – joran Dec 29 '15 at 15:36
  • @joran Sorry, I didn't found this post before. Thank you for your notice. – KryptonLC Dec 29 '15 at 15:44
  • It took me a few minutes to find it, and I wrote the answer! ;) If you are really just intending to sample integers with equal probability, you really should consider Ben's suggestion to use `sample`, as that function is specifically designed for that purpose. (`runif` will give you the right answer too, but `sample` is just what people tend to use for this...) – joran Dec 29 '15 at 15:46

1 Answers1

4

No, it's not a problem with runif.

Try this instead: plot(density(x))

and you see the distribution is smooth

the issue is with where the breaks in your histogram are being placed, and that there's a fencepost problem at work. Histogram is not the best visualization tool for this, because basically the breaks have to line up perfectly.

Shape
  • 2,892
  • 19
  • 31
  • thank you. So it means that I can assume that `floor(runif(n,0,37))` gives me uniform distributed integers, right? – KryptonLC Dec 29 '15 at 15:39
  • It should. You can also look at table(x), if you want to eyeball the actual counts. – Shape Dec 29 '15 at 15:45