jeudi 20 octobre 2022

Generate Uniform Distribution of Floats in Javascript

I'm trying to generate random numbers in javascript that are evenly distributed between 2 floats. I've tried using the method from the mozilla docs to get a random number between 2 values but it appears to cluster on the upper end of the distribution. This script:

function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}

function median(values) {
    if (values.length === 0) throw new Error("No inputs");

    values.sort(function (a, b) {
        return a - b;
    });

    var half = Math.floor(values.length / 2);

    if (values.length % 2)
        return values[half];

    return (values[half - 1] + values[half]) / 2.0;
}

const total = 10_000_000
let acc = []
for (i = 0; i < total; i++) {
    acc.push(getRandomArbitrary(1e-10, 1e-1))
}
console.log(median(acc))

consistently outputs a number close to .05 instead of a number in the middle of the range (5e-5). Is there any way to have the number be distributed evenly?

Thank you!

EDIT: changed script to output median instead of mean.




Aucun commentaire:

Enregistrer un commentaire