DE
Java - 4 verschiedene Möglichkeiten, um einen Random-Float im Bereich zu generieren
3 points
xxxxxxxxxx
1
public static float nextFloatBetween(float min, float max) {
2
return (ThreadLocalRandom.current().nextFloat() * (max - min)) + min;
3
}
Beispiel:
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
}
Beispiel:
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
}
Beispiel:
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
}
Beispiel:
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
Man kann z. B. 2000 Float-Nummern im Bereich 2.0f
und 4.0f generieren.
Dann man soll sie in aufsteigender Reihenfolge sortieren.
Anschließend soll man alle 2000 Floats in sortierter Reihenfolge drucken und dann sicherstellen, dass alle Zahlen am Anfang bei 2.0f und am Ende bei 4.0f liegen.
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
}
Ausgabe (nur die ersten 5 x Floats und die letzten 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