# Generate a Random Number Between Range

How come you subtract the min from the max instead of adding 1 to the min first? I thought addition came before subtraction.

Math.floor(Math.random() * (max - min + 1)) + min

Also why does this equation work?

Thanks

Hello there,

Think through this:
`2 + 3 - 1 === 3 - 1 + 2 === 2 - 1 + 3`â€¦

The equation you have above works like this:

``````Math.random() // Returns a number between 0 and 1
max - min // Returns the range
Math.floor() // Rounds the number passed in it down to the nearest whole number
``````

So, `1` is added to the range because the number is rounded down, and you do not want to exclude a potential case where the result is equal to `max`.
`min` is added to the whole result, as, supposedly, you want a random number from `min` to `max` inclusive.

I hope that is clear enough.

1 Like

Ok thank you, I just dont get how 2 + 3 - 1 == 3 -1 + 2

2 + 3 - 1 == 4
3 - 1 + 2 == 0

If I am using PEMDAS, where addition comes before subtraction. Maybe I forgot something from math class but Im confused about that.

Well, I am used to BODMAS, where operation precedence (`+ || - && * || /`) occurs based on position, when reading left-to-right.

You can test it by typing it in the browser consoleâ€¦

1 Like

Oh ok, so PEMDAS does not work in coding??

PEMDAS:
Parentheses
Exponents
Multiplication AND Division
Addition AND Subtraction.

Multiplication/Division or Addition/Subtraction get parsed from left to right.
`2 + 3 - 1` would be `2 + 3` which is `5`, then `5 - 1` which is `4`.
`3 - 1 + 2` would be `3 - 1` which is `2`, then `2 + 2` which is `4`.

The way you are reading the second statement would be `3 - (1 + 2)`.

1 Like

oh ok thank you so much!

To be honest, I am not familiar with enough paradigms to be able to definitively say. As far as JS, Python, MATLAB go. BODMAS is the order of operations.

I believe BODMAS and PEMDAS are the same rules under different names.
Instead of â€śParentheses, exponentsâ€ť itâ€™s â€śBrackets, orderâ€ť. But the operations are all the same.