10.0*rand.nextDouble()
If you need a range with a minimum other than zero, add that minimum to the expression. For example, to get pseudorandom values in the range 10.0 up to (but not including) 25.9, do this
(25.9-10.0)*rand.nextDouble()+10.0
Say that you are not convinced that Java and your electronic calculator
give the same results for sin(x)
.
You could test this by checking the values each produces for some
standard angles, such as 0.0
, pi/2
and so on.
But you should also test several randomly selected angles.
Here is a program that calculates sin(x)
for random angles (in radians)
between -10*pi
and +10*pi
.
import java.util.Random; class SineTester { public static void main ( String[] args ) { int j=0; Random rand = new Random(); System.out.println(" x " + "\t\t\t sin(x)"); while ( j<10 ) { double x = rand.nextDouble()*(20*Math.PI) - 10*Math.PI; System.out.println("" + x + "\t" + Math.sin(x)); j = j+1; } } }
Random values are often used for testing. Sometimes things work perfectly for standard values, but not for random ones. For example, some gas stations in California adjusted their pumps to dispense exactly the correct amount of fuel for multiples of one half gallon, but to dispense less fuel for all other amounts.
The Bureau of Weights and Measures tested the pumps at standard volumes (half a gallon, one gallon, ten gallons and such) so the pumps passed inspection. However, customers who dispensed all other amounts were overcharged! Testing random volumes would have revealed the scam.
Might you ever need to simulate flipping a coin?