Math random review

advertisement
Modified from: http://www.minich.com/education/wyo/java/lecture_notes/random.php
Math random review
The static method named random in the Math class can be used to create a random decimal value that is
greater than or equal to 0.0 and less than 1.0.
double x = Math.random();
// returns a double 0.0 <= x < 1.0
Math.ramdom can be multiplied by a constant to change the range:
x = Math.random() * 6;
// 0 <= x < 6 such as 0.11, 3.21, 5.99
x = Math.random() * 10;
// 0 <= x < 10 such as 2.15, 7.73, 9.99
Casting the result to an integer is used to produce whole number values:
num = (int) (Math.random() * 5);
// 0, 1, 2, 3, 4
num = (int) (Math.random() * 2);
// 0 or 1
num = (int) (Math.random() * 2) + 1;
// 1 or 2
num = (int) (Math.random() * 8) + 1;
// 1, 2, 3, 4, 5, 6, 7, 8
num = (int) (Math.random() * 10) - 4;
// -4 <= num <= 5
Notice the general form:
(int) (Math.random() * howManyNums) + startingNum;
Be careful to use the extra set of parentheses in the examples above since
num = (int) Math.random() * 6 + 1; // always equals one
Complete the method to return a random whole number between low and high (inclusive).
public static int rollDice(int low, int high)
{
return ___________________________________________________________
}
Modified from: http://www.minich.com/education/wyo/java/lecture_notes/random.php
If you wanted something to occur based on a probability of say 40% you could use:
double x = Math.random();
if (x < 0.4)
{
System.out.println("The event occurred.");
}
else
{
System.out.println("The event did not occur.");
}
Be careful not to create a logic error when answering a question like the following. Write a method that
returns "win", "lose", or "draw" each 1/3 of the time.
public String gameOutcome()
{
if ((int) (Math.random() * 3) ) == 0)
{
return "win";
}
else if ((int) (Math.random() * 3) ) == 1)
{
return "lose";
}
return "draw";
}
Download