jeudi 14 mars 2019

Better algorithm generating random numbers in JS

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!




Aucun commentaire:

Enregistrer un commentaire