JavaScript - Zufallszahlen: Unterschied zwischen den Versionen
Aus Wikizone
(Die Seite wurde neu angelegt: „Quelle: https://wiki.selfhtml.org/wiki/JavaScript/Anwendung_und_Praxis/Zufallszahlen (2017-03) <sytaxhighlight lang="javascript"> var min = 5; var max = 10; v…“) |
|||
| (Eine dazwischenliegende Version desselben Benutzers wird nicht angezeigt) | |||
| Zeile 1: | Zeile 1: | ||
Quelle: https://wiki.selfhtml.org/wiki/JavaScript/Anwendung_und_Praxis/Zufallszahlen (2017-03) | Quelle: https://wiki.selfhtml.org/wiki/JavaScript/Anwendung_und_Praxis/Zufallszahlen (2017-03) | ||
| − | < | + | <syntaxhighlight lang="javascript"> |
var min = 5; | var min = 5; | ||
var max = 10; | var max = 10; | ||
| Zeile 8: | Zeile 8: | ||
Beispiel | Beispiel | ||
| − | < | + | <syntaxhighlight lang="javascript"> |
var test = { | var test = { | ||
results : { | results : { | ||
| Zeile 62: | Zeile 62: | ||
}; | }; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| + | <button onclick="test.start(this)">Berechnung starten</button> | ||
Aktuelle Version vom 6. März 2017, 09:46 Uhr
Quelle: https://wiki.selfhtml.org/wiki/JavaScript/Anwendung_und_Praxis/Zufallszahlen (2017-03)
var min = 5;
var max = 10;
var x = Math.floor(Math.random() * (max - min + 1)) + min;
Beispiel
var test = {
results : {
mathfloor : [],
mathround : []
},
min : 5,
max : 10,
iterations : 120000,
drawings : 0,
randFloor : function () {
return Math.floor(Math.random() * (test.max - test.min + 1)) + test.min;
},
randRound : function () {
return Math.round(Math.random() * (test.max - test.min)) + test.min;
},
start : function (button) {
for (var i = 0; i < test.iterations; i++) {
test.save("mathfloor", test.randFloor());
test.save("mathround", test.randRound());
}
test.drawings += test.iterations;
test.report();
},
save : function (type, n) {
var resultArray = test.results[type];
if (typeof resultArray[n] == "number") {
resultArray[n]++;
} else {
resultArray[n] = 1;
}
},
report : function () {
var tbody = document.getElementById("ausgabe");
var child = tbody.firstChild;
for (var i = tbody.childNodes.length - 1, child; i >= 0; i--) {
tbody.removeChild(tbody.childNodes[i]);
}
var html = "";
for (var i = test.min; i <= test.max; i++) {
var nRound = test.results.mathround[i];
var pRound = (nRound / test.drawings).toString().substr(0, 6);
var nFloor = test.results.mathfloor[i];
var pFloor = (nFloor / test.drawings).toString().substr(0, 6);
var row = tbody.insertRow(-1);
(row.insertCell(-1)).appendChild(document.createTextNode(i));
(row.insertCell(-1)).appendChild(document.createTextNode(nRound));
(row.insertCell(-1)).appendChild(document.createTextNode(pRound));
(row.insertCell(-1)).appendChild(document.createTextNode(nFloor));
(row.insertCell(-1)).appendChild(document.createTextNode(pFloor));
}
}
};
<button onclick="test.start(this)">Berechnung starten</button>