Nethack RNG Problem

There is a strange bug (reported for Linux in RGRN by Soonki Lee) which under some circumstances causes all Valkyries to become lawful. Further examination shows that it comes from rn2(), which is based on Rand(). Rand() itself is #defined as lrand48() on most UNIX systems, including Linux in it's default configuration. (The rn2() call producing the bug is on line 1001 of role.c in version 3.4.1.)

Rand() is a very fundamental function for Nethack's random number generation. The way Nethack uses it is buggy or it may be argued that lrand48() produces crappy pseudo-random numbers. (However, lrand48() is a library function using a defined PRNG method and any program that uses it should take into account the weaknesses of that method.)

The bug is that Nethack relies (sometimes exclusively as is the case in rn(2)) on the lower bits of the results from lrand48(). Because of this, RNG in the whole game works bad. This is especially noticable before user actions introduce further randomness, i.e. in character generation and first level creation. See message <bgm7t2$hkg$02$1@news.t-online.com> for more info.

Patch

nethack_rand-341.diff

This patch modifies RNG only on systems which use lrand48(). It treats the most critical cases (rn(2^n)) separetly and ignores the rightmost random bits for the other cases, producing acceptable results.

Thanks to Dylan O'Donnel for some clarifications

Stanislav Traykov, Aug 2003.