EN
Java - 4 different ways to generate random float in range
4 points
xxxxxxxxxx
1
public static float nextFloatBetween(float min, float max) {
2
return (ThreadLocalRandom.current().nextFloat() * (max - min)) + min;
3
}
Example:
xxxxxxxxxx
1
System.out.println(nextFloatBetween(4.0f, 8.0f)); // 4.2842164
2
System.out.println(nextFloatBetween(100.0f, 900.0f)); // 457.32108
3
System.out.println(nextFloatBetween(-6.5f, -3.5f)); // -4.848301
xxxxxxxxxx
1
public static float nextFloatBetween2(float min, float max) {
2
return (new Random().nextFloat() * (max - min)) + min;
3
}
Example:
xxxxxxxxxx
1
System.out.println(nextFloatBetween2(4.0f, 8.0f)); // 6.454987
2
System.out.println(nextFloatBetween2(100.0f, 900.0f)); // 518.71204
3
System.out.println(nextFloatBetween2(-6.5f, -3.5f)); // -3.6078863
xxxxxxxxxx
1
public static float nextFloatBetween3(float min, float max) {
2
// java 8 + DoubleStream + cast to float
3
return (float) new Random().doubles(min, max).limit(1).findFirst().getAsDouble();
4
}
Example:
xxxxxxxxxx
1
System.out.println(nextFloatBetween3(4.0f, 8.0f)); // 4.026776
2
System.out.println(nextFloatBetween3(100.0f, 900.0f)); // 542.0356
3
System.out.println(nextFloatBetween3(-6.5f, -3.5f)); // -5.739404
xxxxxxxxxx
1
public static float nextFloatBetween4(float min, float max) {
2
return (float) (Math.random() * (max - min)) + min;
3
}
Example:
xxxxxxxxxx
1
System.out.println(nextFloatBetween4(4.0f, 8.0f)); // 6.454987
2
System.out.println(nextFloatBetween4(100.0f, 900.0f)); // 518.71204
3
System.out.println(nextFloatBetween4(-6.5f, -3.5f)); // -3.6078863
Generate 2000 float numbers in range 2.0f
and 4.0f
Sort them in asc order.
Print all 2000 floats in sorted order and verify that all of the numbers at the beginning are around 2.0f and at the end around of 4.0f.
xxxxxxxxxx
1
public static void testFloatInRange() {
2
List<Float> list = new ArrayList<>();
3
for (int i = 0; i < 2000; i++) {
4
//float rand = nextFloatBetween(2.0f, 4.0f);
5
//float rand = nextFloatBetween2(2.0f, 4.0f);
6
//float rand = nextFloatBetween3(2.0f, 4.0f);
7
float rand = nextFloatBetween4(2.0f, 4.0f);
8
list.add(rand);
9
}
10
list.sort(Float::compareTo);
11
12
// print 2000 sorted floats in asc order
13
list.forEach(System.out::println);
14
}
15
16
public static void main(String[] args) {
17
testFloatInRange();
18
}
Output (only first 5 x floats and last 5 x floats):
xxxxxxxxxx
1
2.0001996
2
2.0011134
3
2.0021777
4
2.006852
5
2.0091434
6
...
7
3.9970121
8
3.9975452
9
3.9978209
10
3.9982586
11
3.9999447
ThreadLocalRandom - Java docs
Math - Java docs
Random - Java docs
DoubleStream - Java docs