/**************************************************************** Copyright (C) : University of Michigan Project: NERS 544 - Class example File: lcrng32.cpp Purpose: An example of a linear congruential random number generator in 32 bits Compiler: g++ -ansi -pedantic -Wconversion Use -O2 as well Programmer: Alex Bielajew Revision Date: 09/12/2016 Conversion to a double would be via the following statement below lines : double r = 0.5 + in*2.328306436538696e-10; ****************************************************************/ #include #include using namespace std; int rand(int in, int iOffset) {return 69069*in + iOffset;} // The magic multiplier 69069 is cited by Marsaglia as the "best" for 32 bits int main(void) { cout << "Starting seed = "; int iFirst; cin >> iFirst; if (iFirst%2 == 0) { cout << "*** Starting seed must be an odd number. Exiting! ***\n"; return 1; } cout << "Offset = "; int iOffset; cin >> iOffset; if (iOffset%2 == 0) { cout << "*** Offset must be an odd number. Exiting! ***\n"; return 2; } cout << "Starting seed: " << iFirst << " Offset:" << iOffset << "\n\n\n\n"; int in = iFirst; in = rand(in, iOffset); // Next in series to start double r = 0.5 + in*2.328306436538696e-10; cout << in << ":" << setprecision(16) << r << endl; unsigned int i = 0; while(in != iFirst) { i = i + 1; in = rand(in, iOffset); // Update double r = 0.5 + in*2.328306436538696e-10; if (i < 10) cout << in << ":" << setprecision(16) << r << endl; int N = 10000000; if (i%N == 0) cout << "." << flush; } // Exits when repeats if (i < 2000000000) cout << "\n# loops = " << i + 1 << "\n\n"; else cout << "\n# loops = " << i << " + 1 = " << i + 1 << "\n\n"; for (int i = 1; i <= 10; i = i + 1) { in = rand(in, iOffset); double r = 0.5 + in*2.328306436538696e-10; cout << in << ":" << setprecision(16) << r << endl; } return 0; }