01.07
To get random numbers in Javascript, the most commonly method used is random() from the Math object. The Math object of JavaScript returns a floatingpoint number between 0.0 and 1.0. So really to get a random number between the whole numbers, simply applying random() is not sufficient and requires few other arithmetic calculations. For example you need random numbers between 1 and 100. Below is the one of the solution where few methods from Math object are applied to generate random method.
The first step is to apply random() as below
var random_number = Math.random();
The above code line returns a floating-point number and assigns to the variable random_number. Now the next method we will use is ceil() methos of JavaScript which is also from Math object. Applying Ceil() to a decimal number rounds it to the next higher integer. So if we simply pass the result stored in variable random_number we will always get 1 due to the fact that random() method returns floating-point between 0.0 and 1.0. The trick here is to actually multiply the result and then pass it Ceil() as below and resultant will fall beween 1 and 100.
var random_number = Math.ceil( (Math.random() ) * 100 );
Although JavaScript utilizes a fixed formula and you can also say that if a formula is known then really its not random, as you can easily predict what number will come up next. However for web applications and browser based software it does fulfills the need.
The above code, using ceil(), although does provides whole numbers between 1 and 100, but if you want a random between 0 and 100, i.e also want to add a possibility of getting 0. The ceil() will fail in this case as 0 cannot become a candidate for the range in question. Here comes another method called “floor()” to rescue. The function “floor()” of Math class rounds a number down to the lowest integer. But the problem has not moved to the other end if we use “floor()” as you can see probability to get 100 is gone due to the fact of rounding to the lower integer value.
The solution here is to simply multiply the random number generated by one number higher of the range.
var random_number = Math.floor( (Math.random() ) * (100 + 1) );
Although simply adding 1 every time is not the right way, we may consider the following rule of thumb to get a random number from a range.
First get the random number between 0.0 and 1.0 by using random() method
Next multiply the result with the delta of "upper value" and "one less than the lower value" of the given range.
Now apply "floor()" to the result
And add the "lower value" of the range.
/* sample formula can be */
var l = 1; // lower value of range
var u = 100; // upper value of range
var random_number = Math.floor( (u - (l - 1) * Math.random()) + u );
No Comment.
Add Your Comment