From: Jérôme Benoit Date: Mon, 24 Oct 2022 12:18:08 +0000 (+0200) Subject: Improve random number array generation X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=feb629fe63173338456067e55db0aca40c4fdf4f;p=benchmarks-js.git Improve random number array generation Signed-off-by: Jérôme Benoit --- diff --git a/benchmark-utils.js b/benchmark-utils.js index 50aa39c..961043b 100644 --- a/benchmark-utils.js +++ b/benchmark-utils.js @@ -33,13 +33,33 @@ function generateRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) { * * @param size * @param max + * @param numberGenerator */ -function generateRandomIntegerArray (size, max = Number.MAX_SAFE_INTEGER) { - const integerArray = [] +function generateRandomNumberArray ( + size, + max = Number.MAX_VALUE, + numberGenerator = generateRandomFloat +) { + const array = [] for (let i = 0; i < size; i++) { - integerArray.push(generateRandomInteger(max)) + array.push(numberGenerator(max)) } - return integerArray + return array +} + +/** + * + * @param max + * @param min + * @param negative + */ +function generateRandomFloat (max = Number.MAX_VALUE, min = 0, negative = true) { + if (max < min || min < 0 || max < 0) { + throw new RangeError('Invalid interval') + } + const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff + const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1 + return sign * (randomPositiveFloat * (max - min) + min) } /** @@ -57,7 +77,8 @@ const LIST_FORMATTER = new Intl.ListFormat('en-US', { module.exports = { generateRandomInteger, - generateRandomIntegerArray, + generateRandomFloat, + generateRandomNumberArray, sleep, secureRandom, LIST_FORMATTER diff --git a/empty-array.js b/empty-array.js index 52f836e..a6a8acd 100644 --- a/empty-array.js +++ b/empty-array.js @@ -1,7 +1,7 @@ const Benchmark = require('benny') -const { generateRandomIntegerArray } = require('./benchmark-utils') +const { generateRandomNumberArray } = require('./benchmark-utils') -let testArray = generateRandomIntegerArray(10000) +let testArray = generateRandomNumberArray(10000) Benchmark.suite( 'Empty array', diff --git a/max.js b/max.js index 367a859..bfa521c 100644 --- a/max.js +++ b/max.js @@ -1,7 +1,7 @@ const Benchmark = require('benny') -const { generateRandomIntegerArray } = require('./benchmark-utils') +const { generateRandomNumberArray } = require('./benchmark-utils') -const testArray = generateRandomIntegerArray(10000) +const testArray = generateRandomNumberArray(10000) /** *