1

For example, if I were to generate random numbers between 5 and 50, I know I could write the code as either:

ranNum = (int)Math.random()*(50-5+1)+5;

Or

ranNum = Math.round(Math.random()*(50-5))+5;

In terms of the process to generate the random numbers, what is the difference between the two? And which would be faster?

jww
  • 90,984
  • 81
  • 374
  • 818
chocotella
  • 89
  • 1
  • 9

1 Answers1

7

Speed is not important here.

ranNum = (int)Math.random()*(50-5+1)+5;

This produces a random number between 5 and 50 where each number has an equal chance of occurring.


ranNum = Math.round(Math.random()*(50-5))+5;

This produces a random number between 5 and 50 however 5 and 50 have half the chance of occuring as the others i.e. before ronding the values has to be < 5.5 to get 5 and >= 49.5 to get 50.


Note: neither is the fastest way to generate a random number in a range.

int n = random.nextInt(50 - 5 + 1) + 5;

This is faster because it uses less random bits.

Peter Lawrey
  • 513,304
  • 74
  • 731
  • 1,106