0

I just started learning java through w3schools and one of the methods(?) was Math.random() and they had this example:

enter image description here

I am not quite sure why they've done Math.random() * 101. Why did they use 101 instead of 100?

Thank you

  • 1
    I fail to see why this was marked as a duplicate of that other question? They don't look similar to me. – Stef Aug 02 '21 at 12:57
  • 2
    Short answer: Casting to int cuts of any decimal places of a number, and since Math.random will not return 1.0 itself, multiplying what Math.random returns with 100 will result in a max value of 99.999.... and when cast to an int turns to 99. Since the randomly generated number is supposed to include 100 you'll have to multiply with 101. Multiplying with 100 will result in a max int value of 99. – OH GOD SPIDERS Aug 02 '21 at 12:58
  • 6
    For future reference, don't put pictures of code, it should be text. – Thomas Jager Aug 02 '21 at 13:20

2 Answers2

5

From the Oracle documentation:

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

The expression Math.random() * 101 therefore evaluates to some floating point number in the range 0 to less than 101. Since casting to an integer truncates, instead of rounding, this will be reduced to integers in the range 0 to 100, inclusively, with a (roughly) even distribution.

If this was Math.random() * 100, the number 100 could never be generated. There are 101 values from 0 to 100, inclusive, so you need to go to 101.

Thomas Jager
  • 4,836
  • 2
  • 16
  • 30
  • this document is for JavaScript, which has nothing to do with Java – phuclv Aug 06 '21 at 02:48
  • @phuclv Huh, good point, I didn't even notice the tags, I saw it because of [tag:math]. It happens to be the same answer (since every function I've ever seen that's similar behaves the same way), but I'll update the source. – Thomas Jager Aug 06 '21 at 15:00
1

The random method generates random numbers between 0 and .9999999... inclusive. If you multiply by 101 you get between 0 and 100.999999... inclusive. Assuming the largest possible number is generated that would be (int)(100.9999999...) which results in 100since the fraction will be dropped when cast to an int.

WJS
  • 36,363
  • 4
  • 24
  • 39