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 Numbers In Range Not Random

I’ve been trying to generate random numbers between 1 and 10 million, but was finding that none of the numbers generated were lower than 1 million. I wrote this code to test the problem. This code selects ten million random numbers between 1 and ten million and outputs the lowest number. I’d expect to get at least something in the 100-1000 range at least, but it;s always at least 1 million. What have I missed?

JSFiddle: https://jsfiddle.net/vhLoqz8g/

var lowest=10000000;
for (let i = 0; i < 10000000; i++) {
  var g=Math.floor(Math.random() * (10000000 - 1 + 1)) + 1;
  if (g<lowest)
  {
  lowest=g;
  }
}

document.write(g);

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

>Solution :

You should output lowest and not g at the end of your loop:

var lowest=1e8;
for (let i = 0; i < 1e7; i++) {
  var g=Math.floor(Math.random()* 1e7) + 1;
  if (g<lowest) lowest=g;
}

console.log(lowest)
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