Go4Expert

Go4Expert (http://www.go4expert.com/)
-   JavaScript and AJAX (http://www.go4expert.com/articles/javascript-tutorials/)
-   -   Random Numbers in JavaScript (http://www.go4expert.com/articles/random-javascript-t4988/)

pradeep 29Jun2007 18:04

Random Numbers in JavaScript
 

Introduction



A random number generator (often abbreviated as RNG) is a computational or physical device designed to generate a sequence of numbers or symbols that lack any pattern, i.e. appear random. Computer-based systems for random number generation are widely used, but often fall short of this goal, though they may meet some statistical tests for randomness intended to ensure that they do not have any easily discernible patterns. Methods for generating random results have existed since ancient times, including dice, coin flipping, the shuffling of playing cards, and many other techniques.

Here we'll see how to generate random numbers in JavaScript.

How?



The random() method function of the Math object allows you to get random numbers for various uses in your scripts. You can make a random quote generator or have another type of random script. The only trick is knowing how to get a random number within the boundary you want, and making it a random integer.

Code: JavaScript

alert(Math.random()*50); // A random number
 

Random Numbers within a range



We would many times want a random number within a specified ranged, say between 1 and 10.

Code: JavaScript

function rand(l,u) // lower bound and upper bound
 {
     return Math.floor((Math.random() * (u-l+1))+l);
 }
 
 //Usage
 alert(rand(3,6));

You can also make it a method of the Math object like this,
Code: JavaScript

Math.prototype.rand = function(l,u)
 {
     return Math.floor((Math.random() * (u-l+1))+l);
 }
 
 //Usage
 alert(Math.rand(1,10));



All times are GMT +5.5. The time now is 02:44.