Home > database >  Generate Uniform Distribution of Floats in Javascript
Generate Uniform Distribution of Floats in Javascript

Time:10-21

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.

CodePudding user response:

function log10(x) { return Math.log(x)/Math.LN10; }

function getLogRandomArbitrary(min, max) {
  return Math.pow(10, log10(min)   (Math.random() * (log10(max) - log10(min))));
}

function median(values) {
  if(values.length === 0) throw new Error("No inputs");
  let a = [...values].sort((a,b)=>a-b);
  return a[Math.floor(a.length/2)];
}

const iterations = 1_000_000;
let a = [];
for (let i=0; i<iterations; i  ) {
  a.push(getLogRandomArbitrary(1e-10, 1e-1));
}

console.log(median(a));
console.log(log10(median(a)));

  • Related