What is the best way to generate a random float value included into a specified value interval?

For a random value within a range, the formula is:

double random = min + Math.random() * (max - min);

This basic formula is constant no matter what you use to generate random numbers.

Math.random() provides moderately well distributed numbers, but you can replace it with whatever random number generator you want, for example (slightly better):

Random r = new Random();
double random = min + r.nextDouble() * (max - min);

or if you really want a float:

float random = min + r.nextFloat() * (max - min);

For a better quality (at the cost of speed) random number generation use

Random random = new SecureRandom();

Or you can use a more exotic 3rd party library, such as:

import org.apache.commons.math3.random.RandomDataGenerator;

RandomData random = new RandomDataGenerator();

Which uses the superior Well19937c algorithm.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)