Math.random(), Zufallszahlen in Java

Codeschnipsel um Zufallszahlen in verschiedenen Bereichen zu erstellen. Beispiele für Gleitkommazahlen (float, double) aber Ganzzahlen (int, integer) sind in Form von Java-Code vorhanden.

Die static Methode random der Klasse Math in Java ist gefolgt definiert:

public static double random 

Returns:
a pseudorandom double greater than or equal to 0.0 and less than 1.0

Zufallszahlen zwischen >=0 und <1 also[0,1[

	public static double myRandom() {
		return Math.random();
	}

Ausgabe von myRandom() ist z.B.:

0.2558734951799192
0.03857502479001995
0.08562741500057713
0.2329257841571789
0.7471882261881438

Zufallszahlen zwischen >=0 und <n also [0,n[

	public static double myRandom(double high) {
		return Math.random() * high;
	}

Ausgabe von myRandom(3) z.B.:

1.6597912671200072
0.741373630031203
2.657789140634944
1.4622900147468707
2.4057227757910007

Zufallszahlen zwischen >=x und <y, also [x,y[

	public static double myRandom(double low, double high) {
		return Math.random() * (high - low) + low;
	}

Ausgabe von myRandom(2,5) z.B.:

3.9431368394427415
4.475098023492928
2.071477063035486
4.824069598598292
3.95627277698636

Ganzzahlige (Integer) Zufallszahlen

Um ganzzahlige Zufallszahlen zu erstellen ist ein Cast mit Hilfe von (int) notwendig.

Ganzzahlige Zufallszahlen zwischen >=x und <y, also [x,y[

	public static int myRandom(int low, int high) {
		return (int) (Math.random() * (high - low) + low);
	}

Ausgabe von myRandom(2,5) z.B.:

3
4
2
2
3

Zufallszahlen inklusive Obergrenze

Soll der high-value auch noch mitaufgenommen werden, hilft dieser kleine Trick:

	public static int myRandomWithHigh(int low, int high) {
		high++;
		return (int) (Math.random() * (high - low) + low);
	}

Nun ist auch die 5 erhalten; Ausgabe von myRandomWithHigh(2,5) z.B.:

4
3
5
2
2

Für Anmerkungen oder Verbesserungsvorschläge kann jederzeit die Kommentarfunktion benutzt werden.

Share

Leave a Comment