1

Am curious why is math.floor returns good results than math.ceil when I do random words generation and check in console.log.

Why can't math.ceil work perfectly? Is there something about incompatibility of math.ceil with math.random or is it how I assign and array number (item) of string elements?

Shir
  • 1,157
  • 13
  • 35

2 Answers2

6

Math.random() returns a number less than one (non-inclusive) but greater than 0 (inclusive)

Math.floor(Math.random() * 10); // returns a random integer from 0 to 9

Math.ceil(Math.random() * 10); // returns a random integer from 0 to 10 with a very low chance of 0

If Math.random results in 0 exactly, both Math.floor() and Math.ceil() will return 0, but if Math.random() results in 0.00000001, Math.floor() returns 0 and Math.ceil() returns 1.

DenverCoder1
  • 2,253
  • 1
  • 10
  • 23
  • `Math.ceil(Math.random()*10)` return 1 to 10 – MBadrian Mar 01 '20 at 07:33
  • 1
    @MBadrian As explained, because of the way `Math.random()` works, `Math.ceil(Math.random()*10)` can return 0 but with an extremely low probability (https://stackoverflow.com/questions/52089553) – DenverCoder1 Mar 01 '20 at 07:53
0

if you use Math.ceil(Math.random()*10) you lost first number and if you use Math.floor(Math.random()*10) you lost last Number but if you use Math.round(Math.random()*10) you can find 0 to 10 Number

var k=2.1
console.log(Math.ceil(k))
console.log(Math.floor(k))
console.log(Math.round(k))
 k=2.6
console.log(Math.ceil(k))
console.log(Math.floor(k))
console.log(Math.round(k))
MBadrian
  • 409
  • 3
  • 10
  • 1
    Problem with `Math.round()` is that it has unbalanced probabilities for numbers on the end: `0-0.49 => 0` (Probability: 1/6) `0.5-1.49 => 1` (Probability: 1/3) `1.5-2.49 => 2` (Probability: 1/3) `2.5-3 => 3` (Probability: 1/6) – DenverCoder1 Mar 01 '20 at 07:47