Math.random()
Метод Math.random() возвращает псевдослучайное число с плавающей запятой из диапазона [0, 1) , то есть, от 0 (включительно) до 1 (но не включая 1), которое затем можно отмасштабировать до нужного диапазона. Реализация сама выбирает начальное зерно для алгоритма генерации случайных чисел; оно не может быть выбрано или сброшено пользователем.
Интерактивный пример
Примечание: метод Math.random() не предоставляет криптографически стойкие случайные числа. Не используйте его ни для чего, связанного с безопасностью. Вместо него используйте Web Crypto API (API криптографии в вебе) и более точный метод window.crypto.getRandomValues() .
Синтаксис
Возвращаемое значение
Псевдослучайное число с плавающей запятой от 0 (включительно) до 1 (не считая).
Примеры
Обратите внимание, что поскольку числа в JavaScript являются числами с плавающей запятой стандарта IEEE 754 с поведением при округлении к ближайшему чётному, все эти диапазоны (исключая диапазон с простым вызовом Math.random() ), не точны. Если заданы очень большие границы (253 или выше), возможен крайне редкий случай вычисления обычно исключённой верхней границы.
Получение случайного числа от 0 (включительно) до 1 (не включая)
Получение случайного числа в заданном интервале
Этот пример возвращает случайное число в заданном интервале. Возвращаемое значение не менее (и может быть равно) min и не более (и не равно) max .
Получение случайного целого числа в заданном интервале
Этот пример возвращает случайное целое число в заданном интервале. Возвращаемое значение не менее min (или следующее целое число, которое больше min , если min не целое) и не более (но не равно) max .
Примечание: Может показаться заманчивым использовать Math.round() для округления, но это может сделать распределение неравномерным, что может оказаться неприемлемым для ваших нужд.
Получение случайного целого числа в заданном интервале, включительно
Функция getRandomInt() выше включает минимальное значение, но не включает максимальное. Но что если вам нужно, чтобы включалось и минимальное, и максимальное значение? Функция getRandomIntInclusive() решает этот вопрос.
Math random method in javaScript
Starting out with the Math.random method in javaScript is simple enough, I just call it and I get a random number between 0 and 1, and can potential include 0 but not 1 from what I have read. From there it is all about what you do with that value when it comes to doing something with such a random value. For example if I want random numbers between 0 and 6 then I just need to multiply the returned value from the math random method by 6.
With that said there is maybe a bit more that just calling the method then when it comes to rounding, getting a range, when it comes to the use of the Math random method in javaScript. One interesting advanced topic might be with the nature of the distribution when using the method largely by itself, as the algorithm used might differ from one javaScript implementation to another.
There are all kinds of expressions, and functions where I might want to plug in a random value, but there is also making such a value a variable in the expression, or an argument of a containing function body that defaults to 0. So lets take a look at a few examples of the Math random method in javaScript from simple to not so simple when it comes to really getting into this specific method.
1 — what to know first, and some Basic Math random examples
Many of the examples here are fairly basic, and easy to just copy and paste over into a project. Still I assume that you have at least some background when it comes to getting started with javaScript. I will not be going over every little detail that you should be aware of before hand in this post as I want to make the focus on the Math random method, and various other related topics that might come up when it comes to using such a method. However I will be touching base on a few things that you might want to read up more on before continuing to read the rest of this post.
In this section I will also be starting out with some fairly basic examples of the Math.random method these will just be the usual hello world style type examples. However in the process of doing so I will also be going over some of the basics of expressions, and writing functions in the process of doing so.
It should go without saying that for the most part this section is for total beginners of javaScript. I should focus heavily on that kind of crowd here as many who read this are in fact fairly new to javaScript still as this is one of the first things I would want to learn how to do when learning a new language. If you do have a fair about of experience with javaScript then chances are you will want to skip over this section to get to the good stuff near and at the bottom of the post.
The examples here can be found on my github
Like all my other posts on vanilla javaScript the source code examples here can be found in my test vjs github repository. I do get around to editing this post now and then, and that is where I will keep my latest revisions of what I am writing about here. If you see something wrong with one of these examples that would also be where to make a pull request, and there is also the comments section of this post.
1.1 — A Very basic math.random example in the javaScript console
So the basic deal is to just call the math random method, when doing so you will get a number between 0 and 1 as the return value of the native method. That is all there is to it if that is all that is needed, and in some cases that is all that is needed actually. With that said I think I should maybe start out with an examples that can be used in the javaScript console of a web browser such as Google chrome. I have wrote a getting started with javaScript type post on this very subject, but the basic idea is to just press ctrl + shift + j in Google chrome and make sure that you have the console tab selected. A line of javaScrit code that is then just calling the Math random method can be called in the console.
So just type Math.random() at the > prompt and press return. The result should then be a random number.
The random number can then be multiplied, and used in all kinds of different expressions to get desired random ranges. So from this point forward it is just working out the expressions that are needed to work with this kind of method. Those expressions can then end up being the return values of functions, or be used to create arguments for pure functions.
If you have nodejs installed, and if you really want to get into javaScript you should at some point it is also possible to get started with basic javaScript code examples by making use of the -e option when calling nodejs from a bash or cmd command prompt.
So then in posix like systems like Linux and MacOs you can do something like this if you have nodejs installed.
In windows systems the same can be done in the command prompt.
1.2 — Client side javaScript example
So now that I got some basic examples that have to do with using the javaScript console out of the way there is going over a few examples that have to do with creating some kind of file and then option that up in a web browser, or run with nodejs. For this example I will be going over a quick client side javaScript environment example of using the Math.random method.
When it comes to client side javaScript I can use methods like the document query selector method to get a reference to an html element. In this example I am going to use a text area element and set the value property of the element to a random number.
So then there is the topic of setting up a basic web server as a way to host this kind of index.html file up via the http protocol. That is the proper way to go about doing so actually, however when it comes to something like this it is still possible for it to work okay by just opening it up in a web browser by way of the file protocol.
1.3 — nodejs example of Math.random
Now for a nodejs file example that can be called from the command line. For this example I am using the os module of nodejs to get the End of line string for the underlaying operating system. I am then using the write method of an instance of a stream of the stdout property of the process global to write to the standard output.
So then the next step when it comes to this kind of nodejs example is to save it as something like basic-node.js and call the script from the command line with nodejs.
The end result is then yet another way to go about using the Math random method in a project.
1.4 — function die example
Okay now I think I should write about making at least one or more functions that make use of the Math random method, starting out with a simple die function example. This function will just take one argument that is the number of sides that a die has, and return a random number between and including 1 and the total number of sides.
1.5 — function roll dice example
How about another function example that builds on top of the die function example that I went over above? With that said how about a roll dice function that will take an array of numbers that defaults to [6,6] that is an array sides for a set of dice? Inside the body of this roll dice function the array map method can be used to create an return a new array from the source array that is this array of sides. So the n each element in the new array that is returned is the result of rolling a dice with the sides value in the source array.
2 — Range and Math random
So then there is just calling the main random method, and then there is plugging the value into some very simple expressions to get some kind of number from zero upwards. However there is then using math.random in various other expressions that have to do with getting a number that is within a range. There is starting out with just a basic example, but then there is maybe running into some problems that have to do with rounding rather than getting a float value. I will be getting into the subject of rounding in depth in a later section in this post, but the main focus in this section will be on the subject of dealing with a random range between and in some cases including a min and max value.
2.1 — Basic range example
Getting a range involves a simple expression where you start with the low end of the range and then add by a random number that is the result of Math.random multiplied by the result of the high end of the range with the low end deducted.
Although this is often the basic idea of how to do about doing this sort of then with random numbers there is a bot more to write about with this of course. For one thing there is running into problems with rounding.
2.2 — A per range function example, and pulling Math.random out of the function
It might be better to start out with a range function in which I am pulling the call of Math.random out and placing an argument that represents the kind of value that Math.random returns in its place. This way I have a function in which I have three arguments one of which what I often call a per value which is short for percent, along with a low and high value. This way I can pass Math.random as the per value, or I can also give a number literal value also.
2.3 — Using the per method as a base for a random range method
Form the range per method I can then cerate all kinds of additional methods that involve the use of the Math.random method. There is having a method that will just call Math.random and pass that as the value for the range per function, but on top of that also providing a filter argument that can be just a function to which the return value of calling the range per method with Math.random value is pass threw that is a range random method. This range random method can then be called with a filter in which I am using the Math.floor method to round the value return by range per to create an integer value. I can then also create additional methods beyond this such as one that will take an array and return a random element from that array and so forth, and so on.
3 — Rounding random numbers
When it comes to rounding and random numbers you want to be careful. Make sure that you are using the Math floor or math ceil methods rather than just the math round method. That is unless you want the result of what happens when you use the math round method to be what happens.
You see if you multiply the result of a Math random call by a number such as six, and use the Math round method to round the result the range will be from and including 0 to and including 6 which is a range of 7 possible values where you might only want 6. So you will want to multiply by 5 rather than 6, or use the math floor or ceil methods rather than the math round method.
4 — Random Color methods
Now for some random color method examples that should work okay when it comes to client side javaScript. These are many ways go do about making this kind of method, and many little features when it comes to having control over various aspects of this kind of process. For example some times I might want to have random shads of just a single color channel. Also I might want to have a random range of colors. Other times I might want to have a static array of options for colors and I just want to have one of those options.
4.1 — Array of color options
One way to go about doing this would be to have an array of color options and then just return a random element from that array. I can make it so that there is a hard coded list of options that are just back and white, and then maybe pass any custom array of colors that I might want for other situations.
4.2 — A nice concise solution
This is one of the most concise solutions for a random color generator function that I have found thus far. This works by passing the value 16 to the to string method of the number prototype that results in converting the random number to a hex string. I then just want the last six characters of that hex sting to get a valid random color as a hex string.
4.3 — rgb method
Here I have a method where I am using the rgba format for making a web color, however I just want a random range for a fixed color channel.
5 — The Math random method and Distribution
Now for a word or two on distribution when using the Math round method. Now the math random method will give pseudo random numbers, however it will distribute in a way that is kind of not so random. That is that the numbers will be kind of evenly distributed when using it, unless you do something more to change that. So in this section I will be going over concerns over distribution and the use of the math random method in the javaScript Math object.
5.1 — Random Distribution scatter plot example
A good way to understand what is going on with this would be to create something that looks like a scatter plot of sorts. If I use the Math random method to generate a bunch of random points by just multiplying width by a Math random call for x, and height by a Math.random call then the points will be random, but in a very evenly distributed kind of way.
So say I have a dist.js file like this.
And I make use of it in an html file like this.
The result is random points, but they are distributed in very different ways. By using Math log in conjunction with math random to work out the points that results in a very different distribution of values for the points, many more of the points are concentrated to the lower sides of the area so they are not so evenly distributed.
6 — No replacement
When it comes to the subject of random numbers there is the topic of replacement, and not replacement. That is that there is the concept of selecting a number between and including 1 and 10, but then each time a section is made it is possible to select the same number next time. This would be considered random selection with replacement. So then there is the concept of not having replacement then, that is that of the options start out as [1,2,3,4,5,6,7,8,9,10] and the first random section is 4, then the current state of the array would now be [1,2,3,5,6,7,8,9,10] and then the size of the array would continue to reduce with each call after that.
6.1 — A create hat method
This example I made real quick might server as a decent example of random selection with out replacement. On top of using the Math random method when it comes to making the random section it is also a half way decent example of the concept of closures in javaScript. Also I am using the array map method as a way to quickly make a shallow copy of an array.
When I run this script the result is random numbers being lodged out to the console between and including 1 to 10, but no number ever repeats. That is until of course I call the start method of the hat object that is returned with the create hat method.
7 — Random item probability example
In certain game projects I may have items, for example in a RPG style game I might have various kinds of item drops. In such a game I might have more than one class of object, and the probability of these items dropping might change a little. For example I might have a junk class of item that is dropped almost all the time, and then on the other extreme I might have an epic class of items that is almost never dropped. Or at least maybe that is how things would start off as there would be ways to change the probabilities for each of these kinds of classes. For example maybe there is a \0.5\% chance of an Epic item dropping to start off with, but threw various items, upgrades, and other factors maybe that percentage can increase to as much as say \10\%.
In this section then I will be going over an example that I put together fairly quickly for the sake of this post that is a kind of system that is used to create an object that is a kind of items classes object. Now this might not be the kind of system that is a full blown item system of sorts that I would actually use in a game, but it might still be a starting point for a component of such a system that has to go with creating a state object that is used to figure out what the chances are of a given class of item being dropped by and enemy each time an enemy is killed.
7.1 — The item class javaScript Module
The main file of interest for this example then would be the item class module. This module will need to have at least two pubic methods for starters, one of which is used to create a state object that holds the current probabilities for each item class, and the other is used to return a random item class object.
In the create method a pool of objects will be crated for a returned state object that will be used for other methods in this module, one object for each item class in the game. Each of these objects should contain at least a points value along with other info such as a description, or id key that will be used with the over all greater item system to create the actually item elsewhere in a project that make use of this. The array reduce method can then be used as a way to sum these points values, and then a value of 0 to 1 can be figured for each object. It is then this value from 0 to 1 that can be used to find out if a certain class of item will be dropped or not.
7.2 — The index html file
I now have an index html file that makes use of my item class module just for the sake of making sure it is working okay so far. In this index html file I have a canvas element that I will be using to get a visual sense if this item class module is working the way that I would want it to or not.
8 — Conclusion
So that is it for now when it comes to random numbers and javaScript using the built in Math random method. In the event that I get some more time, or that I find something more to write about when it comes to the Math.random method, and other things surrounding random numbers in general I will expand this post a bit more as I have a few times all ready.
For now there is maybe reading up more on the various other features of the Math object. It might not be needed to go threw all of them but one of the methods I use often is the Math atan2 method which is useful for finding angles between two points for example. There is also getting int using all kinds of formulas that make use of the math pi constant, and also looking into the natural logarithm method also.
Способы использования Math.random() в JavaScript
Math.random() — это один из API JavaScript. Это — функция, которая возвращает случайные числа. Диапазон возвращаемых чисел представлен значениями от 0 (включая 0, то есть, она может вернуть 0) до 1 (не включая 1, то есть — единицу она вернуть не может).
Эта функция чрезвычайно полезна при разработке игр, при описании анимаций, при создании наборов данных с использованием метода случайного выбора. Случайные числа применяются в процедуральном искусстве, при создании текстов и во многих других случаях. Эти числа можно использовать в веб-разработке, в мобильной разработке, в обычных настольных приложениях.
Вот пример, размещённый на CodePen, позволяющий генерировать случайные числа в диапазоне от 0 до 1 и от 0 до 10 (включая 0 и 10).

Пример использования Math.random()
Функцией Math.random() можно воспользоваться в тех случаях, когда в программах нужен элемент случайности. Рассмотрим десять способов применения этой функции. Все примеры, которые тут показаны, созданы разными программистами, которые, пользуясь Math.random() , добиваются различных интересных эффектов.
Анимация
Вот пример, в котором Math.random() используется для создания анимации.

Здесь объекты создаются и анимируются с использованием Math.random() . Светящиеся линии случайным образом формируют анимированные шестиугольники.
Музыка, сгенерированная компьютером
Вот проект, демонстрирующий пример использования Math.random() в деле создания компьютерной музыки.

Компьютерная музыка
Здесь за основу взята традиционная мелодия «Auld Lang Syne» («Старое доброе время»). Программа строит итоговую композицию, обрабатывая исходный материал по особому алгоритму, основанному на использовании случайных чисел.
Вывод случайного изображения
В данном проекте возможности генератора случайных чисел используются для выбора изображений.

Вывод изображения, выбранного случайным образом
Ссылки на изображения хранятся в массиве. Генерируемое случайное число умножается на длину массива (полученную с использованием его свойства length ). Полученное число округляется с помощью функции Math.floor() и применяется при установке свойства src элемента img , используемого для вывода изображения. Делается это при загрузке страницы или при нажатии на кнопку.
Случайный фоновый цвет
Здесь можно найти проект, в котором показан случайный выбор фонового цвета.

Случайный выбор фонового цвета
Самое интересное происходит в этом фрагменте кода:
Эта функция возвращает случайное целочисленное значение из заданного диапазона. Она используется для настройки характеристик цветов, таких, как тон, насыщенность и светлота.
Если вас интересует вопрос случайного генерирования цветов — взгляните на этот материал.
Процедуральное искусство
Вот проект, в котором случайные числа используются для создания изображения по заданным правилам.

Процедуральное искусство
При построении этих необычных кривых функция Math.random() используется дважды. Первый раз — для выбора цветов градиента. Второй раз — для настройки максимального радиуса кривых. Это — прекрасный пример того, как при каждом запуске процесса создания изображения получается что-то новое.
Случайный выбор слов из заранее созданного списка
Здесь можно найти программу, которая выводит на экран слова, случайным образом выбираемые из заранее созданного массива.

Случайный выбор слов
Вот код, который используется для выбора слова:
Этот пример очень похож на тот, где на странице выводится изображение, выбранное случайным образом. Пожалуй, разработка подобной программы хорошо подойдёт новичкам, которые хотят попрактиковаться в работе с веб-технологиями.
Генератор ключей API
Вот проект, в котором случайные числа используются для создания ключей API.

Система для создания случайных ключей API
Это — пример использования генератора случайных чисел, имеющий практическое применение в разработке реальных приложений. Здесь для создания UUID (Universally Unique IDentifier, универсальный уникальный идентификатор) программа генерирует 16 случайных чисел. Такой UUID можно использовать в роли ключа для доступа к некоему API.
Вывод фрагментов текста с использованием переходов, сформированных случайными символами
Здесь можно найти проект, в котором случайные числа используются при выводе текстов.

Переходы между фразами, сформированные с использованием генератора случайных чисел
Здесь имеются несколько фраз, выводимых друг за другом. Переходы между фразами реализованы с использованием случайных символов, подбираемых с использованием Math.random() . Кажется, что компьютер собирает каждую фразу, выполняя некие таинственные вычисления.
Игра «Камень, ножницы, бумага»
Здесь можно найти реализацию игры «Камень, ножницы, бумага».

Камень, ножницы, бумага
В этой классической игре Math.random() используется в качестве основы игровой логики. Компьютер делает ход, случайным образом выбирая один из трёх вариантов действий.
Генератор надёжных паролей
Вот программа, представляющая собой генератор надёжных паролей.

Генератор надёжных паролей
Здесь Math.random() используется для заполнения массива с будущим паролем буквами в верхнем и нижнем регистрах, цифрами и другими символами. Это — ещё один отличный пример практического использования Math.random() .
Заметки о Math.random()
Вполне возможно, что у вас, после того, как вы взглянули на примеры использования Math.random() , возникли вопросы об этой функции. Вот несколько таких вопросов, с которыми мне доводилось встречаться чаще всего.
▍По-настоящему ли случайны числа, которые выдаёт Math.random()?
Они, так сказать, не совсем случайны. Эта функция возвращает псевдослучайные числа. Алгоритм, на котором она основана, называется «генератор псевдослучайных чисел» (Pseudo-Random Number Generator, PRNG). Это значит, что последовательность выдаваемых им чисел может быть, в определённых условиях, воспроизведена.
Generating random whole numbers in JavaScript in a specific range
How can I generate random whole numbers between two specified variables in JavaScript, e.g. x = 4 and y = 8 would output any of 4, 5, 6, 7, 8 ?
![]()
39 Answers 39
There are some examples on the Mozilla Developer Network page:
Here’s the logic behind it. It’s a simple rule of three:
Math.random() returns a Number between 0 (inclusive) and 1 (exclusive). So we have an interval like this:
Now, we’d like a number between min (inclusive) and max (exclusive):
We can use the Math.random to get the correspondent in the [min, max) interval. But, first we should factor a little bit the problem by subtracting min from the second interval:
We may now apply Math.random and then calculate the correspondent. Let’s choose a random number:
So, in order to find x , we would do:
Don’t forget to add min back, so that we get a number in the [min, max) interval:
That was the first function from MDN. The second one, returns an integer between min and max , both inclusive.
Now for getting integers, you could use round , ceil or floor .
You could use Math.round(Math.random() * (max — min)) + min , this however gives a non-even distribution. Both, min and max only have approximately half the chance to roll:
With max excluded from the interval, it has an even less chance to roll than min .
With Math.floor(Math.random() * (max — min +1)) + min you have a perfectly even distribution.
You can’t use ceil() and -1 in that equation because max now had a slightly less chance to roll, but you can roll the (unwanted) min-1 result too.
![]()
x ) instead of Math.floor() converts x into a two-complement with much smaller range than Number.MAX_SAFE_INTEGER (2³²⁻¹ vs. 2⁵³), thus you have to use it with caution!
Math.random()
Returns an integer random number between min (included) and max (included):
Or any random number between min (included) and max (not included):
Useful examples (integers):
** And always nice to be reminded (Mozilla):
Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.
We are returning a function (borrowing from functional programming) that when called, will return a random integer between the the values bottom and top , inclusive. We say ‘inclusive’ because we want to include both bottom and top in the range of numbers that can be returned. This way, getRandomizer( 1, 6 ) will return either 1, 2, 3, 4, 5, or 6.
(‘bottom’ is the lower number, and ‘top’ is the greater number)
Math.random() returns a random double between 0 and 1, and if we multiply it by one plus the difference between top and bottom , we’ll get a double somewhere between 0 and 1+b-a .
Math.floor rounds the number down to the nearest integer. So we now have all the integers between 0 and top-bottom . The 1 looks confusing, but it needs to be there because we are always rounding down, so the top number will never actually be reached without it. The random decimal we generate needs to be in the range 0 to (1+top-bottom) so we can round down and get an integer in the range 0 to top-bottom :
The code in the previous example gave us an integer in the range 0 and top-bottom , so all we need to do now is add bottom to that result to get an integer in the range bottom and top inclusive. 😀
NOTE: If you pass in a non-integer value or the greater number first you’ll get undesirable behavior, but unless anyone requests it I am not going to delve into the argument checking code as it’s rather far from the intent of the original question.
![]()
All these solutions are using way too much firepower. You only need to call one function: Math.random();
This returns a random integer between 0 (inclusive) and max (non-inclusive).
![]()
![]()
Return a random number between 1 and 10:
Return a random number between 1 and 100:
![]()
Alternative if you are using Underscore.js you can use
x ) instead of Math.floor() converts x into a two-complement with much smaller range than Number.MAX_SAFE_INTEGER (2³²⁻¹ vs. 2⁵³), thus you have to use it with caution!
If you need a variable between 0 and max, you can use:
![]()
![]()
The other answers don’t account for the perfectly reasonable parameters of 0 and 1 . Instead you should use the round instead of ceil or floor :
![]()
Cryptographically strong
To get a cryptographically strong random integer number in the range [x,y], try:
![]()
![]()
Use this function to get random numbers in a given range:
Here’s what I use to generate random numbers.
Math.random() returns a number between 0 (inclusive) and 1 (exclusive). We multiply this number by the range (max-min). This results in a number between 0 (inclusive), and the range.
For example, take random(2,5) . We multiply the random number 0≤x<1 by the range (5-2=3), so we now have a number, x where 0≤x<3.
In order to force the function to treat both the max and min as inclusive, we add 1 to our range calculation: Math.random()*(max-min+1) . Now, we multiply the random number by the (5-2+1=4), resulting in an number, x, such that 0≤x<4. If we floor this calculation, we get an integer: 0≤x≤3, with an equal likelihood of each result (1/4).
Finally, we need to convert this into an integer between the requested values. Since we already have an integer between 0 and the (max-min), we can simply map the value into the correct range by adding the minimum value. In our example, we add 2 our integer between 0 and 3, resulting in an integer between 2 and 5.
Here is the Microsoft .NET Implementation of the Random class in JavaScript—
Use:
![]()
I wanted to explain using an example:
Function to generate random whole numbers in JavaScript within a range of 5 to 25
General Overview:
(i) First convert it to the range — starting from 0.
(ii) Then convert it to your desired range ( which then will be very easy to complete).
So basically, if you want to generate random whole numbers from 5 to 25 then:
First step: Converting it to range — starting from 0
Subtract "lower/minimum number" from both "max" and "min". i.e
So the range will be:
Step two
Now if you want both numbers inclusive in range — i.e "both 0 and 20", the equation will be:
Mathematical equation: Math.floor((Math.random() * 21))
General equation: Math.floor((Math.random() * (max-min +1)))
Now if we add subtracted/minimum number (i.e., 5) to the range — then automatically we can get range from 0 to 20 => 5 to 25
Step three
Now add the difference you subtracted in equation (i.e., 5) and add "Math.floor" to the whole equation:
Mathematical equation: Math.floor((Math.random() * 21) + 5)
General equation: Math.floor((Math.random() * (max-min +1)) + min)
So finally the function will be:
![]()
After generating a random number using a computer program, it is still considered as a random number if the picked number is a part or the full one of the initial one. But if it was changed, then mathematicians do not accept it as a random number and they can call it a biased number.
But if you are developing a program for a simple task, this will not be a case to consider. But if you are developing a program to generate a random number for a valuable stuff such as lottery program, or gambling game, then your program will be rejected by the management if you are not consider about the above case.
So for those kind of people, here is my suggestion:
Generate a random number using Math.random() (say this n ):
Then remove the rest after the decimal point. (i.e., get the floor) — using Math.floor(). This can be done.
If you know how to read the random number table to pick a random number, you know the above process (multiplying by 1, 10, 100 and so on) does not violate the one that I was mentioned at the beginning (because it changes only the place of the decimal point).
Study the following example and develop it to your needs.
If you need a sample [0,9] then the floor of n10 is your answer and if you need [0,99] then the floor of n100 is your answer and so on.
Now let’s enter into your role:
You’ve asked for numbers in a specific range. (In this case you are biased among that range. By taking a number from [1,6] by roll a die, then you are biased into [1,6], but still it is a random number if and only if the die is unbiased.)
So consider your range ==> [78, 247] number of elements of the range = 247 — 78 + 1 = 170; (since both the boundaries are inclusive).
Note: In method one, first I created an array which contains numbers that you need and then randomly put them into another array.
In method two, generate numbers randomly and check those are in the range that you need. Then put it into an array. Here I generated two random numbers and used the total of them to maximize the speed of the program by minimizing the failure rate that obtaining a useful number. However, adding generated numbers will also give some biasedness. So I would recommend my first method to generate random numbers within a specific range.
In both methods, your console will show the result (press F12 in Chrome to open the console).
![]()
To test this function, and variations of this function, save the below HTML/JavaScript to a file and open with a browser. The code will produce a graph showing the distribution of one million function calls. The code will also record the edge cases, so if the the function produces a value greater than the max, or less than the min, you.will.know.about.it.
For a random integer with a range, try:
Here is a function that generates a random number between min and max, both inclusive.
To get a random number say between 1 and 6, first do:
This multiplies a random number by 6 and then adds 0.5 to it. Next round the number to a positive integer by doing:
This round the number to the nearest whole number.
Or to make it more understandable do this:
In general, the code for doing this using variables is:
The reason for taking away 0.5 from the minimum value is because using the minimum value alone would allow you to get an integer that was one more than your maximum value. By taking away 0.5 from the minimum value you are essentially preventing the maximum value from being rounded up.
![]()
Using the following code, you can generate an array of random numbers, without repeating, in a given range.
![]()
![]()
Random whole number between lowest and highest:
It is not the most elegant solution, but something quick.
![]()
![]()
I found this simple method on W3Schools:
![]()
![]()
Math.random() is fast and suitable for many purposes, but it’s not appropriate if you need cryptographically-secure values (it’s not secure), or if you need integers from a completely uniform unbiased distribution (the multiplication approach used in others answers produces certain values slightly more often than others).
In such cases, we can use crypto.getRandomValues() to generate secure integers, and reject any generated values that we can’t map uniformly into the target range. This will be slower, but it shouldn’t be significant unless you’re generating extremely large numbers of values.
To clarify the biased distribution concern, consider the case where we want to generate a value between 1 and 5, but we have a random number generator that produces values between 1 and 16 (a 4-bit value). We want to have the same number of generated values mapping to each output value, but 16 does not evenly divide by 5: it leaves a remainder of 1. So we need to reject 1 of the possible generated values, and only continue when we get one of the 15 lesser values that can be uniformly mapped into our target range. Our behaviour could look like this pseudocode:
The following code uses similar logic, but generates a 32-bit integer instead, because that’s the largest common integer size that can be represented by JavaScript’s standard number type. (This could be modified to use BigInt s if you need a larger range.) Regardless of the chosen range, the fraction of generated values that are rejected will always be less than 0.5, so the expected number of rejections will always be less than 1.0 and usually close to 0.0; you don’t need to worry about it looping forever.