1

Here's a very basic issue that i cannot resolve on my mind:

In JS if i do:

Math.random() i will get random numbers between 0 and 1 (including 0, not including 1)

So, if i do Math.ceil(Math.random() * 100) i will get random numbers between 0 and 100. Am i right?

I will get 0 if Math.random() was exactly 0, which is possible as i read in the documentation.

However I read everywhere that doing this "Math.ceil(Math.random() * 100)" i will get numbers between 1 and 100.

Please, can someone clarify this situation?

Thanks!

Math.random () -> [0; 1) Math.ceil(Math.random()) -> [0; 100]

lezammm
  • 23
  • 2
  • 3
    Does this answer your question? [What are the chances of Math.random returning 0?](https://stackoverflow.com/questions/52089553/what-are-the-chances-of-math-random-returning-0) – pilchard Jul 22 '23 at 22:01
  • `0.9900000000000001 * 100 = 99.00000000000001` and the ceiling of `99.00000000000001` is `100`, so anything above `0.99` will result in `100` – Arleigh Hix Jul 22 '23 at 22:07
  • if you, for example, try to excecute Math.ceil(0.1) or Math.ceil(0.2) primitives values, you'll always get 1 as a result of calling the `.ceil`. Therefore, you'll always get the 100% or 1 (it's the same) – Lucas David Ferrero Jul 22 '23 at 22:28
  • @LucasDavidFerrero the OP is multiplying by 100 *before* rounding – pilchard Jul 22 '23 at 22:56

1 Answers1

0

Math.random() will give you a random number between 0 (inclusive) and 1 (exclusive), but the chance that it's exactly 0 is incredibly low.

Math.ceil() rounds up. Given that the chances you get exactly 0 are astronomically low, you will likely get something above 0 from Math.random(), so it's almost (but not entirely) impossible to get 0 from Math.ceil(Math.random()*100).

So Math.ceil(Math.random()*100)) will give you a tiny tiny chance to get 0, but usually between 1 and 100 (inclusive).

Usually what you want to do is Math.floor(), which rounds down. It doesn't have this edge case because Math.random() never gives you 1 so there's never a small chance that Math.floor(Math.random()*100)) gives you 100. It's always 0-99 inclusive evenly distributed.

Evert
  • 93,428
  • 18
  • 118
  • 189
  • 1
    Sorry, I downvoted you by mistake and didn't see it until a few minutes had passed, so I cant undo it until the post is edited. – some Jul 22 '23 at 22:18
  • Its very strange I got *2* downvotes for this though. Is it just people piling on? I thought it was kind of an interesting answer.. wtf – Evert Jul 22 '23 at 22:19
  • 1
    It is an interesting answer. I must have accidentally downvoted when changing windows. – some Jul 22 '23 at 22:22