Array with unsigned module

I am trying to implement a Fibonacci delayed pseudo random number generator for integers to a certain maximum. It supports 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;
}

Essentially, it valuesshould be a simple ring buffer that is always full. Subtraction and modulo should wrap the index at the end of the array. SIZEthere should always be at least 55, but I want to round to 64 to speed up the work modulo.

But, apparently, I have incorrect modulo calculations, and I don’t know how to fix them. Changing the index type to intdoes not improve the situation.

(PS.: , static , , C ++, .)

+3
3

, , idx 24, wraparound unsigned int. 55 , . 2 ^ 32, .

:

  • idx, 24 55 .
  • , . (idx - 24 + SIZE) % SIZE.

, , :

idx = ((SIZE-1) == idx) ? 0 : (idx+1);

, , , .

+2

idx = 0 SIZE = 64.

(idx-24) % SIZE (4294967272 32- int), idx , .

, SIZE :

(idx-24+SIZE) % SIZE (0-24+64)%64, 40.

+3

You get access to values ​​with a negative index. For instance:

-24 % 55 == -24

So, you will need logic to wrap it to the end of the array. C / C ++ does not do this for you.

0
source

Source: https://habr.com/ru/post/1770103/


All Articles