vendredi 5 février 2021

C++ quadratic congruential generator

I'm rather new to C++ and I'm trying to implement a simple quadratic congruential random number generator. It seems to work alright but when I test it's period (repeat interval) it doesn't seem to repeat at all. I store the first random number in a variable and then compare the new numbers until the first one is encountered again, and this comparison doesn't ever get triggered. Is my if-statement wrong somehow? Apologies if this is about a stupid bug I can't see.

#include <iostream>
#include <string>
#include <math.h>

using namespace std;

class QCG {
public:
    int seed;
    int m;
    int a;
    int b;
    int c;

    QCG(int seed) {
        seed = seed;
        m = 1162261467;
        a = 14348907;
        b = 14348908;
        c = 65536;
    }

    int rand() {
        seed = (a*(int)pow(seed, 2) + b*seed + c) % m;
        return seed;
    }
};

//testing repeat interval
int main() {
    QCG qcg(1);

    //generate the first number and store it
    int first = qcg.rand();
    int i = 1;

    while (true) {
        //this gets triggered when the first value is reached again, i.e. when the period is completed
        if (qcg.rand() == first) {
            std::cout << "success! period is " << i << std::endl;
            break;
        }
        //this gets triggered if the previous condition isn't met by the maximum possible period
        if (i == 1162261468) {
            std::cout << "failed" << std::endl;
            break;            
        }
        ++i;
    }
    return 0;
}



Aucun commentaire:

Enregistrer un commentaire