JavaScript random numbers

submit to reddit

The task is …

to generate a random number between any two interger unsigned numbers. Let’s assume we’ve two numbers ‘a’ and ‘b’, where b > a. (I don’t count the case with b==a, cause it seems to be pretty strange!). The formula should be like that:

Math.random() * (b-a+1) + a

Looks very nice, but why is that?

because simply by using Math.random() * a gives a random between 0 and a-1. With the expresion (b-a+1) gives a random number between 0 and (b-a+1) and than by adding the value of a we’ve the number between a and b.

Related posts:

  1. JavaScript rounded corners
  2. JavaScript Flexibility – Regex match()
  3. A JavaScript Trick You Should Know

You are a GREAT developer? Click here to answer the weekly quiz!

This entry was posted in javascript, micro tutorial, web development and tagged , . Bookmark the permalink.

One Response to JavaScript random numbers

  1. Susan says:

    I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.

    Susan

    http://dclottery.info

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">