While loops random number


#1

There was an excercise where I had to loop a card flipping function until I get Spades. Since there are 4 different options the array starts at 0 and ends at 3.

currentCard = cards[Math.floor(Math.random() * 4)];

We were given the code above which should generate random numbers between 0 and 3; however if I’m not mistaken isn’t the number 4 also a possible random number even if it’s way less likely since Math.random() generates a number between 0 and 1. So if it generates 1 we see ‘‘undefined’’ on the display. My final question is thus is there a code that generates random numbers between only 0 and 3 but where each number has the same probability of being generated (Math.random()*3.9 would solve the problem but 3 would appear less than 0, 1 and 2).


#2

the random (psuedo-random actually) number generated by random is between 0 and 1, so exclusive 0 and 1 itself, so the smallest possible value is something like 0.000000001 or so (could be a couple more or less zeroes) while the biggest number is 0.9999999999 (again, plus or minus a few digits). 0.99… * 4 is still 3.something, rounded down is still 3, so you can’t get 4


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.