+ 3

# Does math.random() actually return exact 0 or 1 ever?

In java or any other language where math.random() works... can someone tell me if math.random() is able to return an exact zero or 1.... or it can return in between..... 0.00000000001 and 0.9999999999.. Any help regarding this topic is appreciated.

8th May 2018, 9:38 AM
Sayantan Pal
+ 5
Math.floor((Math.random() * 10) + 1); return a value with 1 to 10 Math.floor(Math.random() * 10); return a value with 0 to 9
8th May 2018, 9:56 AM
Arthur Bacci
+ 4
For practical coding I think Arthur already gave you tools to help you get 0 and 1 when using math.random(). But I find your question interesting so let's see... For starters, math.random() can never return 1 because it returns floats between 0 and 1, 1 not included. So in theory, yes it can return exactly 0. But with all those floats to choose from, what are the odds?
8th May 2018, 10:43 AM
cyk
+ 2
Math.floor(Math.random() * 2); 0 or 1.
8th May 2018, 9:58 AM
Arthur Bacci
+ 1
Thnx fr the help Arthur Bacci ... It means this func returns (0<=x<1) right?
8th May 2018, 10:01 AM
Sayantan Pal
+ 1
a simple look into the java docs would have answered your question... "Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0."
8th May 2018, 11:36 AM
Jeremy