The Coder's Handbook
Random
USING MATH.RANDOM()
Zero to One
Your program can generate a random number in a specified range.
Math.random()
Returns a random double between 0 and 1
It's important to note that Math.random generates a value that includes minimum but excludes maximum.
Using Math To Make Any
Since we can only generate a number between 0 and 1, we'll need to use math functions to modify that. For example, we can scale it using multiplication and add to it using addition.
Example #1
Math.random() * 5 // generates a double between 0 inclusive and 5 exclusive
Example #2
Math.random() * 5 + 2 // generates a double between 2 inclusive and 7 exclusive
In the physical world, we use tools like dice to try and approximate random numbers. But they're not truly random - they're based on physics. As a result, they only produce pseudorandom numbers. They're "random enough" for our purposes.
Computers aren't that much better! We use the system clock and math to make pseudorandom numbers. But it's actually very difficult to find true randomness in nature.
What about integers?
Often you will want to generate a random integer value. For example, if you are simulating a die roll. To do this, we'll need to using casting (see variables) to convert it to an integer. Remember that it truncates the value, so be careful you don't end up off by one.
Example #3
((int) (Math.random() * 5)) + 2 // generates an int between 2 and 6
In addition, you want to be careful that you multiply Math.random() by the scalar before casting it to an integer. If you cast the base value - which is between 0 inclusive and 1 exclusive - to an integer, it will always be zero.
RESOURCES