mardi 25 octobre 2016

Can Random.nextDouble() ever return the inclusive value?

I was playing around with the Random class's nextDouble() method as shown below. I expected nextDouble() to return a pseudorandom double value on the interval [-50.0, 50.0), however, after running the loop 1 billion times the output came out to maximum: 49.99999995014588 minimum: -49.99999991024878. I ran the loop without my manipulations of the output interval, and I got maximum: 0.9999999998979311 minimum: 0.0. I find this strange, because all I have done to the 0.0 that was returned is multiply it by 100.0 and subtract 50.0 from it. Why does this code snippet below never return exactly 50.0?

import java.util.Random;

public class randomTest{

public static void main(String[] args) {

    double max = 0;
    double min = 0;
    Random math = new Random();
    for(int a = 0; a < 1000000000; a++) {
        double rand = math.nextDouble() * 100.0 - (100.0 / 2.0);
        max = Math.max(max, rand);
        min = Math.min(min, rand);
    }
    System.out.println("maximum: " + max + " minimum: " + min);
}
}




Aucun commentaire:

Enregistrer un commentaire