Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array wraparound with modulo of unsigned

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.)

like image 708
Fred Foo Avatar asked Mar 04 '26 07:03

Fred Foo


1 Answers

Lets take idx = 0 and SIZE = 64.

(idx-24) % SIZE will be a very large value (4294967272 for a 32-bit int )as idx is unsigned, making it an invalid index.

To get the circular effect you should add SIZE before taking modulus:

(idx-24+SIZE) % SIZE will be (0-24+64)%64 which evaluates to 40.

like image 184
codaddict Avatar answered Mar 05 '26 21:03

codaddict



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!