Friday, February 29, 2008

Random Numbers

This week I was skimming over a JavaScript book and I found an interesting piece of code. In JS, Math.random() returns a random number between 0 (inclusive) and 1 (exclusive). Here is the algorithm the book suggests to get a random number between 0 and 4:

do{
    iValue = Math.random() * 10 // random number between 0-10
    iValue = Math.floor(iValue) // round to nearest integer
} while (iValue > 4)

Awesome!!

It is assuring to know that the algorithm will not only generate a random number between 0 and 4, but it will also take a random number of steps to finish. That's what I call taking random number generation to the next level.

The book is "Learning JavaScript" (O'Reilly) and the algorithm is shown on page 91.

3 comments:

Unknown said...

Do they say why on Earth do they do that??

Rodrigo Schmidt said...

On the author's words:

" This isn't the prettiest approach to random-number generation (or the most efficient), but it is accurate and does the job. Sometimes that's enough---at least until you have to explore other options."

So, I think she wanted to avoid exploring more complicated solutions :-).

Anonymous said...

Hello. This post is likeable, and your blog is very interesting, congratulations :-). I will add in my blogroll =). If possible gives a last there on my blog, it is about the OLED, I hope you enjoy. The address is http://oled-brasil.blogspot.com. A hug.