Javascript random number generation

How to generate random numbers with Javascript. We make a function that returns a random number between a minimum and a maximum.

In Javascript we have the Math class, very useful when we want to do mathematical calculations of a certain complexity, beyond the arithmetic operators that the language already provides us.

This class is explained and documented in the del . For those who need it, we also have .

The fact is that the Math class allows us to generate random numbers in Javascript, but only through a floating number (with decimals) between zero and one. In this Javascript workshop we are going to build a simple function to create a random number, between a minimum and a maximum, which is much more useful and that we can use later in other more complex programs.

Generate a random number with the Javascript Math class

Here is the code that uses the random method of the Math class to get a random number with Javascript.

var random = Math.random();

Thus we have created a random variable to which we assign the result of executing the random method of the Math class. The random number we get will always be between 0 and 1. It will be something like 0.3882 or 0.9992…

Generate random numbers in Javascript between a minimum and a maximum

If we want to obtain a random number in another range, we can do it with a bit of mathematics and the Math class for the calculation of the random value and its rounding. To illustrate it, we are going to make a function that returns a random number included in an interval. The interval is received as a parameter with two variables, one for the limit at the bottom and another for the limit at the top.

See also  How can I open docx documents if I don't have Office?

function random(min, max) { return Math.floor((Math.random() * (max – min + 1)) + min); }

The function is as simple as that. By means of some simple calculations you can verify that by doing the appropriate addition and subtraction multiplications we can verify that the result will be correct. But it may not be very explanatory if you are starting in Javascript and it is difficult for you to see so much code on the same line.

Another more explanatory function to generate the randoms

Now let’s see a similar function, which performs all the calculations but step by step, which you might like better.

function random(bottom, top) { var numOdds = top – bottom; var random = Math.random() * (numChances + 1); random = Math.floor(random); return bottom + random; }

The function that we have made is very simple, but it works perfectly for all the types of intervals that we can pass to it, both with positive and negative numbers. The first thing we do is obtain the number of possibilities by subtracting the lower limit from the upper limit. Then we multiply said number of possibilities by the random number obtained (which is between 0 and 1), with which we obtain a random number between 0 and the number of possibilities.

The number has a lot of decimal places, and in this example we want to get a whole number, with no decimal places. So we then use the round() method of the Math class, which gives us the nearest integer. Since the number is still between 0 and the number of possibilities we have to add the lower bound to it, so it will be within the range we want. This last value will be where the function returns.

See also  application layer

An example of what we can do with a random number can be to create a random link on a web page. We can see it in the example. Also, in this example the random number is created in a slightly different way than we have seen it now, which can be interesting to better learn how to use the methods of the Math class.

Note: If you prefer it with decimal numbers, look at this other code. It gives you a number between the min and the max (excluding reaching the max). That is, if you ask for numbers between 1 and 10, you would actually be requesting between 1 and 9.9999999. function randomNumberDecimals(min, max) { var num = Math.random() * (max – min); return num + min; }

Verify that the probabilities of obtaining numbers are always the same

As an extra in this practice we could verify that the proposed function does not have problems derived from delivering random numbers that do not have the same chances of coming out.

function random(min, max) { return Math.floor(Math.random() * (max – min + 1) + min); } // Create an array to keep track of the values ​​let valueAppearances = ; // initialize the array with the count of values ​​to zero for (let index = 0; index < 10; index++) { valueAppearances.push(0); } // get randoms a bunch of times for (let i = 0; i <= 10000; i++) { // get the random between 2 and 9 let randomIndex = random(2, 9); // increment the occurrences of this value valueAppearances++; } // display the resulting array, which should have more or less the same appearances // remember, for indices between 2 and 9 console.log(valueAppearances);

See also  Photoshop Slices

If you run this code you will see in the Javascript console the number of occurrences for each value. Remember that we have only searched for randoms between 2 and 9, so the indices 0, 1 of the array should be zero.

Obviously, each time you will get a number of different occurrences of each value, but they will be more or less close to each other, indicating that the probability is the same.

A possible resulting array value would be this: .

conclusion

With this we have learned how to use the math function to get random numbers in Javascript. We have also been able to practice with the function that rounds decimals down (Math.floor()).

As the largest value, we have a function that takes random values, integers between a minimum and a maximum, that we can use as many times as we need.

Loading Facebook Comments ...
Loading Disqus Comments ...