mersenne-twister icon indicating copy to clipboard operation
mersenne-twister copied to clipboard

Bug with MT_UNROLL_MORE

Open mrmbernardi opened this issue 2 years ago • 3 comments

The following code is bugged when MT_UNROLL_MORE is set.

    // i = [0 ... 226]
    while (i < DIFF)
    {
        /*
         * We're doing 226 = 113*2, an even number of steps, so we can safely
         * unroll one more step here for speed:
         */
        UNROLL(i + PERIOD);

#ifdef MT_UNROLL_MORE
        UNROLL(i + PERIOD);
#endif
    }

With MT_UNROLL_MORE, the last iteration begins with i set to 226. The loop enters and completes two more iterations, ending with i = 228, completing one more iteration than it should've. Interestingly, G++ is smart enough to produce a warning about this.

With MT_UNROLL_MORE, the following code fixes the bug and produces the same output as without MT_UNROLL_MORE:

    while (i < DIFF - 2)
    {
        /*
         * We're doing 226 = 113*2, an even number of steps, so we can safely
         * unroll one more step here for speed:
         */
        UNROLL(i + PERIOD);

#ifdef MT_UNROLL_MORE
        UNROLL(i + PERIOD);
#endif
    }
    UNROLL(i + PERIOD);

mrmbernardi avatar Jun 27 '22 21:06 mrmbernardi

I agree - subscripts from 0 to 226 actually iterate 227 times.

zhao-shihan avatar Sep 06 '22 10:09 zhao-shihan