Dragon Slayer - Declare your Variables


#1

I am not stuck on anything I just wondered about the hint section for this topic in which it describes Math.random()

So the "hint" section says the following:

First we use Math.random() to create a random number from 0 up to 1.
For example, 0.5
Then we multiply by 5 to make the random number from 0 up to 5.
For example, 0.5 * 5 = 2.5
Next we use Math.floor() to round down to a whole number.
For example, Math.floor( 2.5 ) = 2
Finally we add 1 to change the range from between 0 and 4 to between 1 and 5 (up to and including 5)

Now I could be wrong, but if Math.random() can make any number from 0-1, does this not mean it can get 1, so when you multiply it by 5 and Math.floor() it to 5 then add 1 you get 6? So the range of damage is actually 1-6? (Albeit a rare chance to get 1 with Math.random(), I just wanted to check I understood it correctly.)


#2

right. So the Math.random() function will hit every number starting at 0, and ending at 1. to include 1. The chance of it hitting zero is a very small chance, same as 1

but if you take that number and multiply it by 5 you're able to get any number between 0-5 to include 0 and 5. and the plus 1 will make it any number between 1-6 to include 1 and 6. I hope this explains it for you.


#3

Good point! If you have a look at the documentary from the Mozilla people:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
you see that 1 is actually excluded so when it's said from 0 to 1 it technically just goes from 0 to 0.999999999


#4

Ahh awesome thank you, I thought this might be the case, as that tiny chance of hitting 1 could throw off a lot of peoples code, even if it was a very rare chance.


#5

I think you didnt get it right. It is impossible to get 6 from (Math.floor(Math.random() * 5 + 1) anyhow.
Why? Because Math.random() is choosing nambers between 0 and 1 but not including 1 and Mathfloor always rounds a number downward to its nearest integer. So the bigeest number oyu can get is 4.99999 plus 1 is 5.999 and with Mathfloor it is 5. I think thats the real point correct me if Im wrong.


#6

Yea that was the point, the description says it can generate the number 1, which I figured was wrong and wanted to check if I was right or not.