Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with using $RANDOM + $FLOOR in bash?

Tags:

bash

random

Reading this: http://www.tldp.org/LDP/abs/html/randomvar.html

#  If you need a random integer greater than a lower bound,
#+ then set up a test to discard all numbers below that.

FLOOR=200

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

   # 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 have been not able to come up with a decent answer to the question in the last comment. That's the way I always generated my pseudorandom numbers in other languages (C/C++, Pascal), and had no problems -- is this something relevant only to Bash?

like image 375
pchr8 Avatar asked Jul 17 '26 14:07

pchr8


1 Answers

In programming languages where your random-number generator could give you values up to just below the overflow point, the latter code would have a bug wherein items within the range between MAXINT - FLOOR and MAXINT would overflow.

Bash does not have this bug, but the reference you are reading is evidently written without that awareness.

like image 111
Charles Duffy Avatar answered Jul 20 '26 04:07

Charles Duffy