Random in javascript with range

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.

Читайте также:  Error java lang null exception

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.

Источник

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.

Источник

How to generate a random number between a range in JavaScript

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

In JavaScript, the Math.random function will generate a random floating point number between 0 and 1(0 is included 1 is excluded):

Generate a random number with a Max limit

Let’s say we need to generate a random number under 100. To do this, we would multiply the random number by 100. Math.random() will not return 1, so the value will be below 100.

Math.random() * 100; // 84.06448370345245 

We can use Math.floor to round it down as shown here:

function generateRandom(maxLimit = 100)
let rand = Math.random() * maxLimit;
console.log(rand); // say 99.81321410836433
rand = Math.floor(rand); // 99
return rand;
>
generateRandom(); // 43
generateRandom(500); // 165

Generate a random number between two numbers

In this case, we will have a MIN and a MAX value and will need to include the MIN value and exclude the MAX value.

If the MIN value is always 0 , then we can multiply the random number with the MAX value, but if the MIN value is other than 0 , we need to find the difference between MAX and MIN . Then we will multiply the random number with that difference and add the MIN value.

  • Let’s say MIN = 3 & MAX = 5 .
  • Difference is MAX — MIN = 2 .
  • Upon multiplying a random number by 2, we will get a value between 0 and below 2. So, the possible value will be either 0 or 1.
  • When we add the MIN(3) value to the random number, the result is either 3 or 4 . We can see this as follows:

Источник

Оцените статью