What is the best way to create a random float value included in a specified range of values?

I want to create a random float value in Java. The value must be within a certain range of possible values.

For example, I need to create a random value that is in the following range:

MIN: 41,815080 MAX: 41,829191 

These values ​​represent the range of possible longitudes on the map, but the question applies in general.

What is a smart way to do this?

+13
source share
4 answers

For a random value within the range of the formula:

 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 any random number generator you want, for example (a little 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); 

Or you can have a more exotic third-party library.

+35
source

If you want to generate random floating point 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 helps.

+11
source

The code:

 import java.util.Scanner; public class Hello { public static void main(String[] args) { Scanner sc=new Scanner(System.in); double max,min,randfloat; System.out.println("Enter minimum :"); min=sc.nextDouble(); System.out.println("Enter maximum :"); max=sc.nextDouble(); randfloat=(Math.random())*(max-min)+min; //Math.random() generates random value between 0 and 1 System.out.println("Random float value generated is: "+randfloat); sc.close(); } } 

Example

+1
source

I know that this question is more than a year old, but other answers here lack 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 with the ThreadLocalRandom class.

For example, if you need a method that generates random numbers between two other numbers, you can 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 this leads to a conflict . In other words, if your code runs simultaneously with any other code that uses Math.random , your random number may need to be counted.
  • The problem with new Random() is that it creates a new instance of Random every time it is called, which is additional work and more verbose.
  • The problem with both of these methods is that they force you to do additional mathematical calculations to scale them to the desired range, making your code less readable and more error prone. The ThreadLocalRandom class has a very convenient nextDouble overload which allows you to specify "origin" and "bound", that is, a minimum and a maximum.
  • Another problem with both of these methods is that they are inaccurate. As you do the scaling, you need to consider the rounding problems inherent in floating point arithmetic. In fact, all other answers to this question sometimes give answers equal to max .

In the above code, I make two assumptions. First, you want the bottom border to be inclusive, and the top border exclusive. This assumption is rather trivial, because the probability of an actual landing at the border is very small. This is also what other answers try to do (although sometimes they give answers equal to max, unlike mine). The second assumption I make is that by “random floating point value” you mean the floating point value that I accepted based on the fact that you marked the question with . So I gave a method that returns a double value, which is a double-precision floating point value, and what you will usually use in Java for floating point values. However, if you wanted to specify a primitive with float , 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; } 

Unfortunately, overloading nextFloat in ThreadLocalRandom is possible because they expect very few people to need a random float with a float . To write this method correctly, you need to fix floating-point rounding errors. Therefore, I highly recommend that you use the version that produces double .

In conclusion, you should never use Math.random and should not create a new instance of Random every time you need to generate a random number (unless, of course, you need a specific starting number). When generating random numbers, the ThreadLocalRandom class is used by default.

+1
source

Source: https://habr.com/ru/post/1012048/


All Articles