Friday, January 20, 2012

Java's Math.random Explained!

The command, Math.random() Explained!

Math.random is an important feature of the Java programming language. It generates psuedo-random numbers which in simple terms are approximated random values.

For most applications written in Java, Math.random is upredictable enough to be considered random.

So what does the command do exactly?
Math.random() creates a value from between 0 and 1; a fraction, essentially.

See it for Yourself!
Copy and paste the following code into a main method of any java class. 

/**This will be a double value between 0 and 1. 
* The value discludes 0 and 1,
* so it is non-inclusive or exclusive

//Prints a random number (0 to 1) to the console.

The Realistic Application Of Math.random()
Programmers can get integer (-1,0,2,3,4,5, ect...) values randomly by manipulating the double (decimal/fraction) value returned by Math.random().

int lowNumber = 1;
int highNumber = 6;

//This code is actually an algorithm for getting random integers by means of Math.random()!
int faceOfDice = (int)((Math.random() * 6) + 1);

//Print out the result
System.out.println("Face of die: "+faceOfDie);

No comments: