DistRND is a small PRNG (pseudorandom number generator) which also evenly distributes the random values over the given range.
<script src="DistRND.min.js"></script>
npm i distributed-randomizer
//Add this line when using NPM:
//const DistRND = require('distributed-randomizer');
const rand = new DistRND(min, max);
rand.next();
argument | data type | description | default |
---|---|---|---|
min |
positive int |
Minimum value | |
max |
positive int |
Maximum value | |
spread |
positive int |
High spread will distribute numbers more randomly |
0 |
Note:
next()
will behave more and more likeMath.random()
with increasing highspread
value.Tip: Start with
spread = 1
and increase slowly to see the effects.
Let's assume we want to generate 10.000 random numbers between 1 and 10. We will count the occurrence of each number for demonstrating purposes:
let data1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
let data2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (let i = 0; i < 10000; i++) {
data1[Math.floor(Math.random() * 10)]++; //with Math.random()
data2[rand.next()]++; //with DistRND.js
}
As you can see the normal Math.random()
function can vary quite a bit from the average due to the nature of randomness or at least pseudorandomness in JavaScript. In this case the deviation from 1000
was ~3% on average and ~6.5% maximum.
DistRND.js can generate 1 Mio. random numbers between 1 and 1000 in less than 100 ms.
- Generate random number
x
from active scope - Add 1 to occurrence of
x
- If new occurrence of
x
is greater than the average: Dropx
from active scope - If average updates: Reevaluate active scope
Yes. The numbers in the active scope are still chosen at random with
Math.random()
.
Example 1: When you want to train a Neural Network you could use this to train it with random sample data but also ensure that it won't get overtrained.
Example 2: When you have a game with multiple players you could use this to select random players but also ensure that every player gets the same amount of turns over the entire game.