Javascript random number in range

Math.random()

Math.random() — это функция встроенного объекта Math , которая возвращает псевдослучайное число с плавающей запятой из диапазона от 0 включительно, до 1 не включительно.

Синтаксис

Опубликуем результат в console.

 let randomNumber = Math.random() console.log(randomNumber) // или просто console.log(Math.random()) 

Особенности генерации случайных чисел

1. Math.random() генерирует случайные числа на основе алгоритма, который в итоге можно просчитать, поэтому метод не подходит там, где речь идет о безопасности.

2. Разработчик или пользователь не может выбрать алгоритм, который будет использовать метод для генерации рандомного числа.

3. Math.random() формирует числа похожие на 0.6592126750964376 или 0.4571938784553331. В дальнейшем результат масштабируются до нужного формата и диапазона.

4. Результатом метода может быть ноль, но единица никогда.

5. В сферах связанных с безопасностью рекомендуется использовать Web Cryptography API и его методы getRandomValues() и generateKey() .

Случайное число в диапазоне

Для того, чтобы получить случайное число в заданном интервале можно использовать следующую функцию.

 function getRandomNumber(min, max)

Целое число в диапазоне

Получаем целое число от минимума (включительно) до максимума (не включительно)

 function getRandomNumber(min, max)
 function getRandomNumber(min, max)

ceil() — округляет в большую сторону, floor() в меньшую.

Случайное число в диапазоне включительно max

Функция учитывает недостатки предыдущих решений и выводит случайные числа от и до включительно для обоих случаев.

 function getRandomNumber(min, max)
 function getRandomNumber(min, max)
 function getRandomNumber(min, max)

round() — округляет до ближайшего целого.

Итого

Math.random() генерирует псевдослучайное число от 0 до 1 (не включительно). Метод не содержит параметров, а его результаты удобно форматировать, тем самым получая случайные целые или дробные числа в необходимом диапазоне.

Skypro — научим с нуля

Источник

Math.random()

The Math.random() static method returns a floating-point, pseudo-random number that’s greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.

Note: 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.

Try it

Syntax

Return value

A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).

Examples

Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for Math.random() itself) aren’t exact. If extremely large bounds are chosen (2 53 or higher), it’s possible in extremely rare cases to reach the usually-excluded upper bound.

Getting a random number between 0 (inclusive) and 1 (exclusive)

function getRandom()  return Math.random(); > 

Getting a random number between two values

This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) min , and is less than (and not equal) max .

function getRandomArbitrary(min, max)  return Math.random() * (max - min) + min; > 

Getting a random integer between two values

This example returns a random integer between the specified values. The value is no lower than min (or the next integer greater than min if min isn’t an integer), and is less than (but not equal to) max .

function getRandomInt(min, max)  min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min) + min); // The maximum is exclusive and the minimum is inclusive > 

Note: It might be tempting to use Math.round() to accomplish that, but doing so would cause your random numbers to follow a non-uniform distribution, which may not be acceptable for your needs.

Getting a random integer between two values, inclusive

While the getRandomInt() function above is inclusive at the minimum, it’s exclusive at the maximum. What if you need the results to be inclusive at both the minimum and the maximum? The getRandomIntInclusive() function below accomplishes that.

function getRandomIntInclusive(min, max)  min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1) + min); // The maximum is inclusive and the minimum is inclusive > 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Mar 28, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

How to Generate a Random Number within Certain a Range in JavaScript

Dillion Megida

Dillion Megida

How to Generate a Random Number within Certain a Range in JavaScript

Let’s say you want to generate a random number between 10 and 15 – how do you do that in JavaScript? I’ll show you how with examples in this article.

In JavaScript, there’s the random method of the Math object which returns random numbers. But this has a range limitation. So let’s see how we can take advantage of this method to solve for different ranges.

I’ve created a video version of this article that you can use to supplement your learning here.

How to Use Math.random in JavaScript

The random method returns a random floating number between 0 and 1 . Here’s a code example:

Math.random() // 0.26636355538480383 Math.random() // 0.6272624945940997 Math.random() // 0.05992852707853347 

From the results, you can see three random numbers between 0 and 1. Now let’s solve for other ranges.

How to Get Random Numbers within a Range in JavaScript

We will have a function that we can use for different ranges:

function getRandom(min, max) < // code here >

This function takes the min (lowest parameter of the range) and max (highest parameter of the range) arguments. Now let’s use this range and Math.random to get a random number:

function getRandom(min, max) < const floatRandom = Math.random() const difference = max - min // random between 0 and the difference const random = Math.round(difference * floatRandom) const randomWithinRange = random + min return randomWithinRange >

Here’s what’s happening in the function:

  • first, we get a random floating number using Math.random()
  • next, we find the difference between the highest and lowest range
  • next, we evaluate a random number between 0 and the difference between the ranges

To get this random number, we multiply the difference by the random number we got from Math.random and we apply Math.round on the result to round the number to the nearest integer.

So if, for example, Math.random returns 0.3 and the difference between the ranges is 5, multiplying them together gives 1.5. Then using Math.round makes it 2 which is between 0 and 5 (the difference).

Another example: if Math.random returns 0.9 and the difference between the specified ranges is 8, multiplying them together gives 7.2. Then using Math.round makes it 7 which is between 0 and 8 (the difference).

Now that we have a random number between 0 and the difference, we can add that random number to the minimum range. Doing this gives us a result that is within the minimum and maximum range.

We assign this result to randomWithinRange and return it from the function. Now let’s see the function in use:

console.log(getRandom(10, 15)) // 14 console.log(getRandom(10, 15)) // 11 console.log(getRandom(10, 15)) // 12 console.log(getRandom(10, 15)) // 15 

Here, we use a min of 10 and a max of 15. The four times we call the function with these arguments, you can see the results which are random numbers between the range provided.

Let’s look at another example of the function in use:

console.log(getRandom(180, 450)) // 215 console.log(getRandom(180, 450)) // 386 console.log(getRandom(180, 450)) // 333 console.log(getRandom(180, 450)) // 442 

Here, we use a min of 180 and a max of 450. Again, you can see how the random number results from our function.

Wrapping Up

If you ever need to generate a random number within a specific range, I hope this article has shown you how.

In this article, I explained the range limitation of Math.random which returns a random number between 0 and 1. And I also showed you how to take advantage of this math method to create a reusable function for generating random numbers within any range of your choice.

Kindly share this article if you find it helpful.

Dillion Megida

Dillion Megida

Developer Advocate and Content Creator passionate about sharing my knowledge on Tech. I simplify JavaScript / ReactJS / NodeJS / Frameworks / TypeScript / et al My YT channel: youtube.com/c/deeecode

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

JavaScript: Generate Random Number in Range

We as software developers often stumble into situations where we need to insert a dose of randomness into our code.

In this article, we will look at how to generate random numbers in JavaScript. We will also touch upon a few built-in methods to deal with random numbers. By the end, we will put this knowledge to good use by writing a function to simulate a six-sided die.

Generating Random Numbers in JavaScript

Math.random() in JavaScript generates a floating-point (decimal) random number between 0 and 1 (inclusive of 0, but not 1). Let’s check this out by calling:

This will output a floating-point number similar to:

This is useful if you’re dealing with percentages, as any value between 0 and 1 , rounded to two decimal places, can be thought of as a percentile.

Generating Random Whole Numbers in Range

We generally don’t deal with floating-point numbers in the 0 to 1 range, though. So, let’s look at a way to round floating-point numbers.

We can round down a floating-point number using Math.floor() . Similarily, we can round up a number via the Math.ceil() function:

console.log(Math.floor(3.6)) console.log(Math.ceil(3.6)) 

This will give us the output:

Let’s generate a random number between min and max , not including max :

function randomNumber(min, max)< const r = Math.random()*(max-min) + min return Math.floor(r) > 

Alternatively, we could’ve included max with the Math.ceil() function instead.

We are multiplying with (max-min) to transform the range [0,1) into [0, max-min ). Next, to get a random number in the required range, we are adding min . Finally, we are rounding this to an integer using Math.floor() .

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Let’s call this method a few times and observe the results:

for (var i = 0; i < 10; i++) < console.log(randomNumber(0, 10)) > 

This will output something similar to:

Conclusion

Generating pseudo-random numbers in a program can be used to simulate unpredictability of an enemy in-game, or for randomization of forests in a block-like game we all know and love. It can also be used to simulate random inputs while testing another program you wrote.

Either way, generating a random number is an important tool in any engineer’s toolkit, and should be expanded as much as possible with different generation methods and algorithms. This article was just the first step of learning random number generation.

Источник

Читайте также:  Python read file in linux
Оцените статью