Pure Programmer
Blue Matrix


Cluster Map

Project: LCG Pseudo-Random Number Generator

The [[Linear congruential generator]] (LCG) [[pseudorandom number generator]] is the simplest and most studied way to generate a series of numbers that appear random.

The generator is defined by recurrence relation:

`X_(n+1) = (aX_n+c) mod m`

where `X_0` is the seed or starting value and a, c and m define the period and behavior of the generator. A bad choice of a, c or m results in poorly generated values that repeat too frequently or correlate in other ways.

Write a LCG function to generate pseudorandom numbers. It should maintain an internal state `X_n` as a 64-bit integer but return the low 31-bits as the result of the generator. The function should accept the multiplier (a), increment (c) and modulus (m) as arguments. Start with `X_0` as 3261963.

Write a program to test the function. The program should accept the multiplier (a), increment (c), modulus (m) and number of pseudorandom numbers to generate as arguments on the command line. Each time you call the generator print the raw value in hexadecimal and the floating point fraction in the range [0,1) computed using the raw value divided by `2^31`

Notice that over multiple runs with the same a, c, and m, you will get the same results. This is because the seed is always the same. How could we get a seed that would be different each run?

See [[Linear_congruential_generator#Parameters_in_common_use|Common LCG Parameters]] for some choices to use when testing the LCG.

Output
$ swiftc LCGPseudorandomGenerator.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation)

Solution