Odd behavior with Random

There are three problems at play…

  1. In general, using analogRead to initialize the random number generator is a bad idea…

    This is a better choice…

    In your case using analogRead is disastrous because of #3 below.

  2. Using modulus to reduce a Lehmer random number generator is a bad idea. But, the alternatives are annoying so a modulus is usually what is used. If you keep the most-significant-bits as the most-significant-bits instead of using modulus your problem will very likely disappear. However, if you insist on continuing to use analogRead a good hash function will work far better for what you are doing than a random number generator.

  3. Low seed values with some prime number divisors are poison with the Park-Miller generator. I’m too lazy to find the thread but there is a detailed discussion on this forum. Given your experience seven is very likely one of those prime number divisors.

Thanks. I've bookmarked those threads and will read through them when I get a chance. This isn't a mission-critical issue for me, just something I stumbled across while I was trying out various things in some test code.

Add one more item to the long (long) list of things to learn about. ;)


Whandall: I did not locate the source code of srandom(long) and random() yet.


@mjward, you are welcome.

(reseedRandom updated with the new value. The remainder of this post is now trivia.)

Bear in mind you will need to use a much larger prime (the constant named HappyPrime in reseedRandom) It does not have to be a Happy Prime; just a prime number. Ideally you should use something slightly more than the "dead zone". I vaguely recall it being about 1.5 million. It's easy enough to write a little sketch to determine where it ends. The dead zone ends at 127,774...

void setup() 
  uint32_t seed;
  uint8_t choice;
  Serial.begin( 250000 );

  seed = 0;
    randomSeed( seed );
    choice = random( 7 );

    if ( (seed & 0x0000FFFF) == 0 )
      Serial.write( '.' );
  while ( choice == 0 );

  Serial.print( seed );
  Serial.print( F( " --> ") );
  Serial.print( choice );

void loop() 

If we stick with Happy Primes the nearest value greater than 127,774 is #1859 = 127807.