Math.random returns values over 1.0 sometimes. Is this okay?


#1



https://www.codecademy.com/courses/javascript-beginner-en-Bthev-mskY8/0/4?curriculum_id=506324b3a7dffd00020bf661


The lesson is telling me that the math.random() function will choose a random number between 0 and 1. But when I run it, I'm getting numbers above one (i.e. 1.45533222) Am I doing something wrong? I don't want to run into errors later if I set 'scissors' to be chosen from .67-1.00 but nothing above that...


var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
console.log(computerChoice);


#2

In all my years that is the first time I have seen this output from Math.random(). The very definition of the function is to generate a positive float less than 1. We should feel 100% safe accepting that as the working model.

I would be hard pressed to reproduce what you experienced, without adding 1 to Math.random(). We don't have an optional function so this is it.

How's your math? Intervals? Probability?

var x = Math.random();
y = 0 <= x && x < 1     // true 100% of the time

In an inequality,

{ x | 0 <= x < 1; x is Real }

In an interval,

x = [0,1)

The set of upper bounds for n intervals of x, is,

{1/n, 2/n, .., n/n}

The interval only approaches from the left, never equaling, so these bounds are limits; x -> i/n.

This should give you hint how to set 'computerChoice'`s string value, without fudging around with decimals.

c < 1/3 => rock
c < 2/3 => paper
else    => scissors

#3

My code was exactly what I posted in my comment. I'm running the code over and over again now to see if it happens again, but I haven't gotten anything over 1 again. Thank you so much for your answer, because of it I know to be confident in the outcome of math.random(). I remember very clearly that it was 1**.**8 something something, because it confused the crap out of me.
It was probably my eyes playing tricks. I'm not going to go up against your advice and experience on it, so I'll just let it rest. Thank you again.


#4

Reviving…

1.45533222 * 10 ** -8  =>  1.45533222e-08

which is a pretty small number with 7 zeros following the decimal point.

 > 1.45533222 * Math.pow(10, -8)
<- 1.45533222e-08
 >