Hello out there!
var zahl=2*Math.random()+1;
var i=Math.round(zahl);
Willst du das wirklich?
Sei x deine Zufallszahl, 0 ≤ x < 1. Dann gibt es folgende Fälle:
0 ≤ x < 0.25 │ 0.25 ≤ x < 0.75 │ 0.75 ≤ x < 1
0 ≤ 2x < 0.5 │ 0.5 ≤ 2x < 1.5 │ 1.5 ≤ 2x < 2
1 ≤ 2x + 1 < 1.5 │ 1.5 ≤ 2x + 1 < 2.5 │ 2.5 ≤ 2x + 1 < 3
──────────────────┼──────────────────────┼──────────────────
i = 1 │ i = 2 │ i = 3
p(1) = 1/4 │ p(2) = 1/2 │ p(3) = 1/4
Wie du siehst, ist das Intervall für x, für das i = 2 wird, doppelt so breit wie die anderen beiden Intervalle, die Wahrscheinlichkeit des Auftretens von i = 2 ist also doppelt so hoch wie die des Auftretens von i = 1 und i = 3.
Willst du Gleichverteilung erreichen, darfst du nicht Math.round()
verwenden, sondern Math.floor()
:
var i = Math.floor(3 * Math.random() + 1);
0 ≤ x < 1/3 │ 1/3 ≤ x < 2/3 │ 2/3 ≤ x < 1
0 ≤ 3x < 1 │ 1 ≤ 3x < 2 │ 2 ≤ 3x < 3
1 ≤ 3x + 1 < 2 │ 2 ≤ 3x + 1 < 3 │ 3 ≤ 3x + 1 < 4
──────────────────┼──────────────────────┼──────────────────
i = 1 │ i = 2 │ i = 3
p(1) = 1/3 │ p(2) = 1/3 │ p(3) = 1/3
See ya up the road,
Gunnar
“Remember, in the end, nobody wins unless everybody wins.” (Bruce Springsteen)