bug-bash
[Top][All Lists]

## \$RANDOM not random in 2.05.0(1)-release

 From: David Forrest Subject: \$RANDOM not random in 2.05.0(1)-release Date: Tue, 26 Mar 2002 16:16:54 -0500 (EST)

```    while true; do echo -n " \$(( ( RANDOM >> 5) % 8 ))"; done

Shows a repeat interval of 256 (look for 6 6 0 0 0 1 1)

while true; do
R=\$RANDOM
R=\$(( ( RANDOM >> 5) % 8 ))
echo -n " \$R"
done

Shows the same

Although the basic PRNG is fairly good (period 2^31-1), and BASH strips
off the low order bits already, the net result that appears in \$RANDOM is
horrid for some reason.

### from bash-2.05a/variables.c ######################################
/* A linear congruential random number generator based on the example
on in the ANSI C standard.  This one isn't very good, but a more
complicated one is overkill. */

/* Returns a pseudo-random number between 0 and 32767. */
static int
brand ()
{
rseed = rseed * 1103515245 + 12345;
return ((unsigned int)((rseed >> 16) & 32767));       /* was % 32768 */
}
#######################################################################

#bash shell script equivalent:
RS=\$(( ( RS * 1103515245 +12345  ) )) ; R=\$(( (RS >>16 ) & 32767 ))

# A well tested alternate: The Park & Miller Minimum Standard RNG
RS=\$(( ( RS * 16807 % 2147483647 ) )) ; R=\$(( (RS >>16 ) & 32767 ))

RS=\$RANDOM;
while true; do
RS=\$(( ( RS * 1103515245 +12345 ) ))
R=\$((  ( RS >> 16 ) & 32767 ))
echo -n " \$(( (R >>5) % 8))"
done

This bash code should match what is in the current bash source for the
test above, but is much more reliable for some reason.  Why is the \$RANDOM