random() is a pseudo-random number as no computer can generate a truly random number, that exhibits randomness over all scales and over all sizes of data sets. However, the pseudo-random number generated by Math. random() is usually sufficient for the needs of nearly any program you may write.
Generating Javascript Random Numbers Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.
random() The Math. random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.
Given numbers between 1 and 100.
Given numbers between 1 and 1000.
and so on.
So if you select some at random, then that vast majority of selected numbers will have the same number of digits, because the vast majority of possible values have the same number of digits.
Your results are actually expected. If the random numbers are uniformly distributed in a range 1 to 10^n, then you would expect about 9/10 of the numbers to have n digits, and a further 9/100 to have n-1 digits.
There different types of randomness. Math.random gives you an uniform distribution of numbers.
If you want different orders of magnitude, I would suggest using an exponential function to create what's called a power law distribution:
function random_powerlaw(mini, maxi) {
return Math.ceil(Math.exp(Math.random()*(Math.log(maxi)-Math.log(mini)))*mini)
}
This function should give you roughly the same number of 1-digit numbers as 2-digit numbers and as 3-digit numbers.
There are also other distributions for random numbers like the normal distribution (also called Gaussian distribution).
Looks perfectly random to me! (Hint: It's browser dependent.)
Personally, I think my implementation would be better, although I stole it off from XKCD, who should ALWAYS be acknowledged:
function random() {
return 4; // Chosen by a fair dice throw. Guaranteed to be random.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With