A Random number generator in Javascript

Oct 8, 2007 14:50 GMT  ·  By

Random numbers are very useful in programming, because they allow programmers to control and manage various random events. For example, they can be employed in image rotation scripts, random quote generator, games, stochastic simulations, probability calculations and more.

Every programming language contains functions or classes that permit the generation of random numbers. Random number generators are the subject of statistical error determination, because most of them output pseudo-random numbers. The truly random numbers are hard to obtain by using simple generating techniques. In every situation you must know the type of distribution of random numbers associated with certain events in order to select the corresponding algorithm for the generator. In Javascript, the random() function will generate a random number between 0 and 1, but never 1, every time is called.

If you need to generate other types of random numbers, for example integers situated in a certain range, the function multiplied with the appropriate number will output a value that must be rounded. The functions available in Javascript to round numbers are ceil(), round() and floor(). ceil() function rounds numbers upwards to the nearest integer as compared to floor() function which has a reverse action of rounding numbers.

Due to the difference in rounding number mechanism, the best results in generating uniform distributed random integers are achieved with floor() function. The round() function is not optimal in generating good random integer numbers, because one of the generated numbers (situated in the middle of the interval) will appear twice more often than others.

You can try to analyse sets of random numbers generated using different rounding techniques in order to establish or identify their distribution. The next code is an example of random integer number generator using floor() function for rounding. It will generate numbers between 0 and 7:

code
Random Number Generator

function random(n)
{
var x = Math.floor(Math.random()*n)
return x
}
number = random (8)
document.write('the random integer is '+ number)