Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
790 views
in Technique[技术] by (71.8m points)

random - 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;
}
question from:https://stackoverflow.com/questions/66067052/c-quadratic-congruential-generator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It goes in a 'rho' shape - first there are some unique numbers, then there is a loop. It doesn't loop back to the first number, but to some further number. Look up Pollard's rho algorithm, or Brent's cycle detection algorithm


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...