Games would be boring if the same thing happened each time you played the game. Random numbers can be used in games to generate different outcomes each time the game is played. In Java, the Math.random() method to is used to generate a random number.
There are lots of mathematical methods in the Math class that you might want to use in your programs, like Math.pow(2,3) which calculates the 2 to the power of 3 which is 8.
The Math class is part of the java.lang package. Classes in the java.lang package are available by default. The Math methods are class methods (or static methods) which means you can call them by just using ClassName.methodName().
The Math class contains the following methods that are in the AP CSA subset. There are more Math methods, outside of what you need on the AP exam, that you can find in the Math class Javadocs.
All the Math methods that you may need to use or understand on the AP exam are listed in the AP CSA Java Quick Reference Sheet that you can use during the exam.
These Math methods are mathematical functions that compute new values from their arguments. You may be able to guess what abs, pow, and sqrt do, from their abbreviations.
Math.abs takes a single argument, either a double or an int and returns a value of the same type which is the absolute value of the argument. The absolute value is the positive value of the number without its sign or its distance from 0. So:
Math.sqrt takes an double argument and returns a positive double value which is the square root of the argument. For example, the square root of 9 is 3 because 3 squared is 9.
Since these methods calculate and return a value, you need to use that value, for example in an assignment statement or in a print statement to see the result. For example:
The distance between two numbers on the number line is defined as the absolute value of their difference. Their difference is just what you get when you subtract one from the other. For example, the distance from 0 to 3 is 3, the distance from -3 to 0 is 3, and the distance from -3 to 1 is 4.
The distance between two numbers on a number line, as we discussed in the problem above, is defined as the absolute value of their difference. Their difference is just what you get when you subtract one from the other. For example, the distance from 0 to 3 is 3, the distance from -3 to 0 is 3, and the distance from -3 to 1 is 4.
The Math.random() method returns a double number greater than or equal to 0.0, and less than 1.0. When we talk about ranges of numbers sometimes we need to be precise about whether the ends of the range are part of the range. For example, Math.random returns a number between 0 and 1, but does that mean it can return exactly 0? Or exactly 1? As it turns out it can return 0 but never returns 1.
When we need to be precise about this weβd say that it returns a number between 0, inclusive, and 1, exclusive, meaning include 0 but exclude 1. Lots of ranges in Java are expressed this way, as youβll see later on with an inclusive bottom and exclusive top.
Getting a number between 0, inclusive, and 1, exclusive, may not seem all that useful. But we can expand the range easily enough. To see how, imagine you had less than a dollar to your name and you wanted to be richerβyouβd want to find a way to multiply your money. If you could invest every penny you had in something that would multiply your money by 1,000 then instead of having somewhere between $0 and $1, then youβd have somewhere between $0 (inclusiveβif you started with $0) and $1,000 (exclusive, since if you had even a fraction of a penny less than $1 multiplying by 1,000 would still leave you just a bit shy of $1,000.) If the investment multiplied your original money by a million, youβd have between $0 and $1,000,000! (But never quite $1,000,000.)
Same trick applies to random numbers. The value Math.random returns is like the initial amount of money in your pocket, always a bit less than $1. If you multiply that value by any amount, it will stretch it into the range you want:
You may have noticed that while the numbers generated were always in the range 0 to 10, all the numbers probably had a lot a digits after the decimal point. Often we want a random integer, with nothing after the decimal point. Easy enoughβcasting a double to an int will throw away any values after the decimal point. For example,
// rnd is an integer in the range 0-9 (from 0 up to 10).
int rnd = (int)(Math.random()*10);
Finally, what if we want a number in a range that doesnβt start with 0, say a number from 1 to 10 (including 10) instead of from 0 to 9 (including 9)? Since the size of the two ranges is the same, with ten numbers in each, all we need to do is shift from the range weβve generated into the range we want. In other words, add the difference between the two ranges, 1 in this case.
// rnd is an integer in the range 1-10 (including 10).
int rnd = (int)(Math.random()*10) + 1;
Activity1.11.7.
Run the code below several times to see how the value changes each time. How could you change the code to return a random integer from 1 to 10? Modify the code and see if your answer is correct. Try removing the parentheses from around (Math.random() * 10) and run the code several times. What happens? The parentheses are necessary because (int) will cast the closest expression, and (int)Math.random() will always be 0 since anything after the decimal point is dropped.
// Math.random() returns a random number between 0.0-0.99.
double rnd = Math.random();
// rnd1 is an integer in the range 0-9 (including 9).
int rnd1 = (int)(Math.random()*10);
// rnd2 is in the range 1-10 (including 10). The parentheses are necessary!
int rnd2 = (int)(Math.random()*10) + 1;
// rnd3 is in the range 5-10 (including 10). The range is 10-5+1 = 6.
int rnd3 = (int)(Math.random()*6) + 5;
// rnd4 is in the range -10 up to 9 (including 9). The range is doubled (9 - -10 + 1 = 20) and the minimum is -10.
int rnd4 = (int)(Math.random()*20) - 10;
So the general recipe for generating a random is to first stretch the value from Math.random() until itβs in the right size range by multiplying by the size of the range. Then if you want an integer value, cast to int to discard the part after the decimal point. Then shift the value up by adding the minimum value. The table below shows some applications of that general recipe.
Remember that (int)(Math.random()*range) + min moves the random number into a range starting from a minimum number. We want the minimum number to be 25, but the minimum number here would be 36.
int rn = (int) (Math.random() * 25) + 60;
Remember that (int)(Math.random()*range) + min moves the random number into a range starting from a minimum number. We want the minimum number to be 25, but the minimum number here would be 60.
int rn = (int) (Math.random() * 26) + 60;
Remember that (int)(Math.random()*range) + min moves the random number into a range starting from a minimum number. Here the min is 25. We want the minimum number to be 25, but the minimum number here would be 60.
int rn = (int) (Math.random() * 36) + 25;
Yes, (int)(Math.random()*36) + 25 moves the random number into a range of 36 numbers starting from a minimum number 25 up to 60. The range is (max number - min number + 1) which is (60-25 +1) = 36.
int rn = (int) (Math.random() * 60) + 25;
This would give us random numbers from 25 to 85. Remember that you can compute the range you need with (max number - min number + 1).
You may have a combination lock on your locker at school where you have to spin the dial to 3 separate numbers from 0 up to 40. What if you forgot your combination? Would you be able to guess it?
Write code that will generate 3 random integers from 0 up to 40 (but not including 40) using Math.random() in the Active Code window below. Run it a couple times to see it generate different numbers.
How many times would you need to run it to guess your combination correctly? Letβs have the code compute the number of permutations possible in your combination lock using Math.pow(number,exponent). For example, if you had to spin the dial twice on your combination lock where each spin can choose a digit from 0-9 (10 digits), there are \(10^{2}\) possible permutations. In Java, this would be written as Math.pow(10,2) which means 10 to the power of 2. If you start listing all the permutations possible, you can tell that there are \(10^{2}\) or 100 possible permutations for a 2 spins on a dial lock from 0-9.
Now what about the combination lock for this challenge? You will need to spin the dial 3 times: once to the right, once to the left, and once to the right to 3 different numbers from 0 up to 40 (not including 40). In general, the formula to use is \(NumbersPerDial^{numberOfSpins}\text{.}\) Write this using the Math.pow() method in your code and save it into a variable and print out.
Hereβs another challenge that is a lot of fun! Can you use random numbers to make dancing turtles? This idea was suggested by CSA teacher Zac Martin.
Complete the random numbers using Math.random() in the correct ranges to choose x, y coordinates and random color in the range of 0-255 for the turtle. Put on some music and watch your turtle dance!
(int)(Math.random() * range) + min moves the random number into a range starting from a minimum number. The range is the (max - min + 1). For example, to get a number in the range of 5 to 10, use the range 10-5+1 = 6 and the min number 5: (int)(Math.random()*6) + 5.