You call int result = random.nextInt(101) which creates uniformly distributed integers in [0,100], which can take 101 different values. If you check if (result > 49) then you have 51 possible values ([50,100]) and in the else case you have only 50 values ([0,49]). Thus the result is more likely to be in the upper part. To fix it you can do int result = random.nextInt(100).
You call int result = random.nextInt(101) which creates uniformly distributed integers in [0,100], which can take 101 different values. If you check if (result > 49) then you have 51 possible values ([50,100]) and in the else case you have only 50 values ([0,49]). Thus the result is more likely to be in the upper part. To fix it you can do int result = random.nextInt(100).
you are testing 51 possibilities for a positive outcome and only 50 possibilities for a negative outcome.
- 100-50 = 51 possibilities
- 0-49 = 50 possibilities.
Videos
Today I find myself in an interesting position where half of my program's performance is being hogged by nextInt. Therefor I would like to share a bit of my findings on the subject in hopes it might be of interest to others.
Interestingly enough, Java divides the method of finding a random integer into two separate procedures based off of the passed maximum.
IF the number is a power of 2, as calculated below:
(n & -n) == n
A quick procedure is preformed. If, as calculated above, the number is a power of two, Java uses very little calculation power in order to find the requested random number.
However, if the maximum is not a power of 2, the operation speed varies greatly depending on the current seed.
If you can manage, use ThreadLocalRandom over Random - it's much faster, because it does not need to synchronize.
Look at the java-performance.info page for Random vs. ThreadLocalRandom for further information and benchmarks.
I think that you should read this series of blog posts. It's enlightening about RNG performance in the JRE.
tl;dr use a Mersenne twister RNG implementation if you need speed over cryptographically sound results.