lundi 1 juin 2015

How can I get full-ranged random float values?

I found that Random#nextFloat returns a value between 0.0 and 1.0.

How can I get a random float value such as -72.0F or 126.232F?

I currently doing like this.

float randomFloat() {
    final ThreadLocalRandom random = ThreadLocalRandom.current();
    float value = random.nextFloat() * Float.MAX_VALUE;
    if (random.nextBoolean()) {
        value = 0 - value;
    }
    return value;
}

Is this right? Is there any other way to do this?




Aucun commentaire:

Enregistrer un commentaire