bashrandomprng

Generate a random number which is greater than a specific number


In Advanced Bash-Scripting Guide Chaper 9.3. $RANDOM: generate random integer

It illustrates how to generate a random number greater than a specific number:

FLOOR=200

number=0   #initialize
while [ "$number" -le $FLOOR ]
do
  number=$RANDOM
done
echo "Random number greater than $FLOOR ---  $number"
echo

And then the comment says:

# Let's examine a simple alternative to the above loop, namely
#       let "number = $RANDOM + $FLOOR"
# That would eliminate the while-loop and run faster.
# But, there might be a problem with that. What is it?

I think it is still randomness and greater than $FLOOR, so I don't know what the problem it is.


Solution

  • The problem probably comes from overflow. Let say your prng generate a number between 0 and maxint. If you simply add the floor, what occur when the addition gives a number greater than maxint? Of course, you could simply reject those numbers, but it would result in the same algorithm as the one you proposed.

    Depending on what is the floor, some tricks could be used to minimize rejection. For example, if needed number is greater than maxint / 2, you could systematically set the higher bit before testing for rejection.