Can someone help me understand Math.random()?

Tell us what’s happening:

Hello so far i understand what Math.floor and math.random is doing but i have no idea whats happening after that

function ourRandomRange(ourMin, ourMax) {
  return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
}

i dont understand the * after math.random() and what ourMax - ourMin + 1 means
also what is +ourMin doing at the end?

can someone help me understand this?..

Your code so far


// Example
function ourRandomRange(ourMin, ourMax) {

return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
}

ourRandomRange(1, 9);

// Only change code below this line.

function randomRange(myMin, myMax) {

return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin; // Change this line

}

// Change these values to test your function
var myRandom = randomRange(5, 15);


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36.

Challenge: Generate Random Whole Numbers within a Range

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-within-a-range

All of those are standard arithmetic operators

* : multiplication
+ : addition
- : subtraction

Math.random() returns a floating-point number in the range [0, 1).

Math.floor() rounds its first argument down to the nearest whole number.

So Math.floor(Math.random()) will always return 0, because no matter what Math.random() evaluates to, it will always round down to 0.

In order to control the range of values from which to choose the random integer, we need to do some arithmetic.

First, the size of the range of the values can be changed through multiplication with Math.random().

Ex)

Math.floor(Math.random())       // [0]
Math.floor(Math.random() * 2)   // [0, 1]
Math.floor(Math.random() * 100) // [0, 1, 2, ... 99]

If we add or subtract from the result, we can change where the range starts.

Ex)

Math.floor(Math.random())         // [0]
Math.floor(Math.random()) + 5     // [5]
Math.floor(Math.random()) + 1000  // [1000]

Now, what happens when we put those together? Then we can control both the size of the range, and from where the range starts.

Ex)

Math.floor(Math.random() * 2) + 5      // [5, 6]
Math.floor(Math.random() * 100) + 1000 // [1000, 1001, 1002, ... 1099]

And it turns out we can phrase this equation in terms of the minimum and maximum of the range. That equation is:

floor(rand() * (max - min + 1)) + min

For example, if we look at the first line in the example directly above, we could write it as the following:

// equivalent to Math.floor(Math.random() * 2) + 5
const min = 5;
const max = 6;
Math.floor(Math.random() * (max - min + 1)) + min 

Does that help?

2 Likes