-1

My goal is to generate random integers between 1 and 100 in JavaScript.

I'm currently using this:

const random = Math.ceil(Math.random() * 100)
console.log(random)

But I saw a lot of places an alternate solution,

const random = Math.floor(Math.random() * 100 + 1)
console.log(random)

which produces the same results.

My question is that:

Why is the second code better (if better at all) than my first code?
Isn't it better to perform one operation rather than two (Math.floor() and +1)?

Thanks for your time and answers!

Salman A
  • 262,204
  • 82
  • 430
  • 521
FZs
  • 16,581
  • 13
  • 41
  • 50
  • 4
    The first example produces numbers between 0 (inclusive) and 100 (inclusive), the second produces numbers between 1 (inclusive) and 100 (inclusive). They are not the same. – str Mar 14 '19 at 21:17

3 Answers3

3

There is one notable difference between these two

Math.ceil(Math.random() * 100)
Math.floor(Math.random() * 100 + 1)

The first has a theoretical possibility to produce 0 with a very tiny probability, the second not.

trincot
  • 317,000
  • 35
  • 244
  • 286
1

Both produce nearly the same result. You could take a quantitative test and have a look to the count of the drawn numbers.

const
    getRandomCeil = () => Math.ceil(Math.random() * 100),       // 0 ... 100 0 is less likely
    getRandomFloor = () => Math.floor(Math.random() * 100 + 1); // 1 ... 100

var i,
    count = { ceil: {}, floor: {} };

for (i = 0; i < 1e7; i++) {
    value = getRandomCeil();
    count.ceil[value] = (count.ceil[value] || 0) + 1;
    value = getRandomFloor();
    count.floor[value] = (count.floor[value] || 0) + 1;
}
console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Math.random produces number in the range [0, 1) which means 0 is inclusive and 1 is not. Looking at the two extreme cases:

// When Math.random() returns 0
Math.ceil(0 * 100)         // returns 0 since ceiling of 0 is 0
Math.floor(0 * 100 + 1)    // returns 1

// When Math.random() returns 0.999999...
Math.ceil(0.999999 * 100)  // returns 100
Math.floor(0.999999 + 1)   // returns 100

The ceil variant has the potential of returning 0 when random function returns exactly 0; although the probability is very, very little.

Salman A
  • 262,204
  • 82
  • 430
  • 521