Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Random natural number within range function Typescript returns me not so random numbers

I am currently working on a function which is supposed to generate numbers within a specific range. Example: If the minimum of the range is 1 and the maximum is 5 then it should return a number between 1 and 5 or equal to 1 and 5.

This is the code I have so far:

function getRandomNumber(min: number, max: number): number {
    max = max + 1; // in order to include the max value
    return Math.floor(Math.random() * (max - min) + min);
}

This function does work as intended but unfortunately some numbers get generated quite often in sequence. Example: I define a range of 1 to 5, the output of the function will be something like: 1,1,1,1,1,5,5,5,1,1,1,1,5,1,1,1,5,1,1,4,4,2,2,3,1,1,1,1,5,1,5,1,5,5,1,1,1,1,3

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As we can see all the numbers of the range are being included but for some reason certain numbers e.g 1 and 5 in this case get generated often in sequence and are generally being generated more often than they should to be classified as ‘random’ (imo).

My question is if I have done anything wrong in my code or if this is supposed to be normal behavior.

>Solution :

It looks like it is equally distributed …

function getRandomNumber(min, max) {
    max = max + 1;
    return Math.floor(Math.random() * (max - min) + min);
}

const count = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 };

for (let i = 0; i < 1e6; i++) count[getRandomNumber(1, 5)]++;

console.log(count);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading