DE
Java - 4 verschiedene Möglichkeiten, um einen Random-Float im Bereich zu generieren
3
points
1. Random-Float im Bereich mit ThreadLocalRandom generieren
public static float nextFloatBetween(float min, float max) {
return (ThreadLocalRandom.current().nextFloat() * (max - min)) + min;
}
Beispiel:
System.out.println(nextFloatBetween(4.0f, 8.0f)); // 4.2842164
System.out.println(nextFloatBetween(100.0f, 900.0f)); // 457.32108
System.out.println(nextFloatBetween(-6.5f, -3.5f)); // -4.848301
2. Random-Float im Bereich mit Random class generieren
public static float nextFloatBetween2(float min, float max) {
return (new Random().nextFloat() * (max - min)) + min;
}
Beispiel:
System.out.println(nextFloatBetween2(4.0f, 8.0f)); // 6.454987
System.out.println(nextFloatBetween2(100.0f, 900.0f)); // 518.71204
System.out.println(nextFloatBetween2(-6.5f, -3.5f)); // -3.6078863
3. Random-Float im Bereich mit Random und DoubleStream generieren
public static float nextFloatBetween3(float min, float max) {
// java 8 + DoubleStream + cast to float
return (float) new Random().doubles(min, max).limit(1).findFirst().getAsDouble();
}
Beispiel:
System.out.println(nextFloatBetween3(4.0f, 8.0f)); // 4.026776
System.out.println(nextFloatBetween3(100.0f, 900.0f)); // 542.0356
System.out.println(nextFloatBetween3(-6.5f, -3.5f)); // -5.739404
4. Random-Float im Bereich mit Math generieren
public static float nextFloatBetween4(float min, float max) {
return (float) (Math.random() * (max - min)) + min;
}
Beispiel:
System.out.println(nextFloatBetween4(4.0f, 8.0f)); // 6.454987
System.out.println(nextFloatBetween4(100.0f, 900.0f)); // 518.71204
System.out.println(nextFloatBetween4(-6.5f, -3.5f)); // -3.6078863
5. Testen, ob Float im Bereich Methoden funktionieren, wie erwartet
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.
public static void testFloatInRange() {
List<Float> list = new ArrayList<>();
for (int i = 0; i < 2000; i++) {
//float rand = nextFloatBetween(2.0f, 4.0f);
//float rand = nextFloatBetween2(2.0f, 4.0f);
//float rand = nextFloatBetween3(2.0f, 4.0f);
float rand = nextFloatBetween4(2.0f, 4.0f);
list.add(rand);
}
list.sort(Float::compareTo);
// print 2000 sorted floats in asc order
list.forEach(System.out::println);
}
public static void main(String[] args) {
testFloatInRange();
}
Ausgabe (nur die ersten 5 x Floats und die letzten 5 x Floats):
2.0001996
2.0011134
2.0021777
2.006852
2.0091434
...
3.9970121
3.9975452
3.9978209
3.9982586
3.9999447
Literaturverzeichnis
ThreadLocalRandom - Java docs
Math - Java docs
Random - Java docs
DoubleStream - Java docs