Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to generate a random float value in Java. The value has to be within a specific range of possible values.

For example, I have to generate a random value that is in the following range:

MIN: 41,815080
MAX: 41,829191

These values happen to represent a range of possible longitudes on a map, but the question applies more generally.

What is a smart way to do it?

like image 728
AndreaNobili Avatar asked Nov 04 '16 21:11

AndreaNobili


People also ask

Which method is used to generate a random float value?

The parameterized method is used here to generate a random float value. The method accepts lower and upper bound as the parameters.

How do you generate a random float number in Python?

Use a random. random() function of a random module to generate a random float number uniformly in the semi-open range [0.0, 1.0) . Note: A random() function can only provide float numbers between 0.1. to 1.0. Us uniform() method to generate a random float number between any two numbers.

How do you generate a random float value in Java?

In order to generate Random float type numbers in Java, we use the nextFloat() method of the java. util. Random class. This returns the next random float value between 0.0 (inclusive) and 1.0 (exclusive) from the random generator sequence.


3 Answers

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.

like image 119
Bohemian Avatar answered Oct 13 '22 03:10

Bohemian


If you want to generate random float values try this:

import java.util.Random;

public static float randFloat(float min, float max) {

    Random rand = new Random();

    return rand.nextFloat() * (max - min) + min;

}

Hope this helped.

like image 30
Yogesh D Avatar answered Oct 13 '22 04:10

Yogesh D


I know that this question is over a year old, but the other answers here are missing important points. The best way to generate a random floating-point value in Java (assuming you don't need a specific seed and you don't need to be cryptographically secure) is the ThreadLocalRandom class.

For example, if you want a method that generates random numbers between two other numbers, you could write it like this:

public static double generateRandomDouble(double min, double max) {
  return ThreadLocalRandom.current().nextDouble(min, max);
}
  • The problem with Math.random is that it results in contention. In other words, if your code is being run concurrently with any other code that uses Math.random, your random number may have to be recomputed.
  • The problem with new Random() is that it's creating a new Random instance every time it's called, which is extra work and more verbose.
  • The problem with both of these methods is that they force you to do the extra math to scale it to the desired range, making your code less readable and more error-prone. The ThreadLocalRandom class has a very convenient nextDouble overload that lets you specify an "origin" and "bound," meaning minimum and maximum.
  • Another problem with both of these methods is that they're imprecise. Because you're doing the scaling, you need to account for the rounding problems that are inherent in floating-point arithmetic. In fact, all of the other answers to this question will sometimes produce answers equal to max.

In the code above, I am making two assumptions. First, you want the lower bound to be inclusive and the upper bound to be exclusive. This assumption is rather trivial, because the probability of actually landing on the boundary is very small. This is also what the other answers are attempting to do (though they sometimes produce answers equal to max, unlike mine). The second assumption I make is that by a "random float value," you mean a floating-point value, which I assumed based on the fact that you tagged the question with floating-point. Thus, I gave a method that returns a double, which is a double-precision floating-point value, and what you'll typically use in Java for floating-point values. However, if you meant to specify a float primitive, you can use the following method:

public static float generateRandomFloat(float min, float max) {
  if (min >= max)
    throw new IllegalArgumentException("max must be greater than min");
  float result = ThreadLocalRandom.current().nextFloat() * (max - min) + min;
  if (result >= max) // correct for rounding
    result = Float.intBitsToFloat(Float.floatToIntBits(max) - 1);
  return result;
}

There is unfortunately no nextFloat overload on ThreadLocalRandom, presumably because they expect very few people to need random floats. To write this method correctly, you must correct for floating-point rounding problems. Thus, I would strongly recommend that you use the version that produces a double.

In conclusion, you should never use Math.random, and you shouldn't create a new Random instance every time you need to generate a random number (unless, of course, you need a specific seed). When generating random numbers, default to the ThreadLocalRandom class.

like image 7
Finn Avatar answered Oct 13 '22 02:10

Finn