JSFiddle - React, Tailwind, and code Playground
by brunovieira
JavaScript
function getNonZeroRandomNumberWithMathRound() {
var random = Math.round(Math.random() * 198) - 99;
if (random == 0) return getNonZeroRandomNumberWithMathRound();
return random;
}
function getNonZeroRandomNumberWithMathFloor() {
var random = Math.floor(Math.random() * 199) - 99;
if (random == 0) return getNonZeroRandomNumberWithMathFloor();
return random;
}
var number_of_tests = 50000;
var extreme_ocurrences = 0; //will output the appearance of 99 and -99
var normal_ocurrences = 0; //will output the number of appearances of 33 and -33
document.writeln("<p><b>1st Scenario</b>: Using Math.round((Math.random() * 198) - 99)");
for(i=0;i<number_of_tests;i++){
var randomNumber = getNonZeroRandomNumberWithMathRound();
if(randomNumber == 99 || randomNumber == -99)
++extreme_ocurrences;
if(randomNumber == 33 || randomNumber == -33)
++normal_ocurrences;
}
var percentageOfNormalOcurrences = ((normal_ocurrences/number_of_tests) * 100);
var percentageOfExtremeOcurrences = ((extreme_ocurrences/number_of_tests) * 100);
document.writeln("<br/><br/><span>Percentage of normal ocurrences:" + percentageOfNormalOcurrences+"%</span>");
document.writeln("<br/><span>Percentage of extreme ocurrences:" + percentageOfExtremeOcurrences +"%</span><br/>");
document.writeln("<span>Percentage of extreme ocurrences relative to normal ocurrences:" + (percentageOfExtremeOcurrences/percentageOfNormalOcurrences * 100) +"%</span><br/></p>");
var extreme_ocurrences = 0; //will output the appearance of 99 and -99
var normal_ocurrences = 0; //will output the number of appearances of 33 and -33
document.writeln("<p><b>2nd Scenario</b>: Using Math.floor((Math.floor() * 199) - 99)");
for(i=0;i<number_of_tests;i++){
var randomNumber = getNonZeroRandomNumberWithMathFloor();
if(randomNumber == 99 || randomNumber == -99)
++extreme_ocurrences;
if(randomNumber == 33 || randomNumber == -33)
...