dimanche 2 juin 2019

Question about JavaScript Math.random() and basic logic

I wrote a simple piece of code to compare random array difference and found something ... that I don't quite understand.

1) I generate 2 arrays filled with random numbers

2) Add up the differences between the random numbers

3) Print out the average difference

I would have expected the result to be random number close to 0.5 but in practice, it is 0.3333.

Why does the random number array home in on 0.3 and not 0.5?

const result = document.getElementById('result');
const generateRandomNrArray = (nrNumbers) => {
        let i;
        let result = [];
        for (i = 0; i < nrNumbers; i++) {
                result.push(Math.random());
        }
        return result;
}
const getArrayDiff = (arr1, arr2) => {
  var diff = 0;
  arr1.forEach(function (v1, index) {
      diff += Math.abs(v1 - arr2[index]);
  });
  return diff;
}
const run = (nr) => {
  const arr1 = generateRandomNrArray(nr);
  const arr2 = generateRandomNrArray(nr);
  const totalDiff = getArrayDiff(arr1, arr2); 
  
  result.innerHTML = "Average difference:" + (totalDiff / nr);
}
button {font-size: 2em;}
<div id="result"></div>
<button id="run" onclick="run(1500)">Click Me</button>



Aucun commentaire:

Enregistrer un commentaire