I'm trying to implement a lagged Fibonacci pseudo-random number generator for integers up to some maximum. It maintains an array of values
int values[SIZE] = { /* 55 seed values */ };
and uses the following function to return the next value
unsigned lagfib()
{
static unsigned idx = 0;
int r = values[idx];
/* The following does not work: */
values[idx] = (values[(idx-24) % SIZE] + values[(idx-55) % SIZE])
% MAX_VALUE;
idx = (idx+1) % SIZE;
return r;
}
In effect, values
should be a simple ring buffer that is always full. The subtraction and modulo should wrap the index around to the end of the array. SIZE
should always be at least 55, but I want to round up to 64 to speed up the modulo.
But apparently, I've got the modulo calculations wrong and I don't know how to fix them. Changing the index type to int
doesn't improve things.
(PS.: Yes, static
data is bad style, but I want this to be readable for both C and C++ programmers, since it pertains to both languages.)