Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C++ Program to Generate Random Numbers Using Multiply with Carry Method
The multiply-with-carry method is a variant of the add-with-carry generator introduced by Marsaglia and Zaman (1991). The main advantages of this method are that it invokes simple computer integer arithmetic and leads to a very fast generation of sequences of random numbers with immense periods, ranging from around 260 to 22000000.
In this article, our task is to generate random numbers using the multiply-with-carry method. Here is the formula of multiply-with-carry method:
Multiply With Carry (MWC) Formula
The multiply-with-carry formula is as follows:
X<sub>n</sub> = (a * X<sub>n-1</sub> + C<sub>n-1</sub>) mod 2<sup>32</sup> C<sub>n</sub> = (a * X<sub>n-1</sub> + C<sub>n-1</sub>) / 2<sup>32</sup> Where, X<sub>n</sub> = Next random number C<sub>n</sub> = Carry a = Constant multiplier X<sub>n-1</sub> = Previous random number C<sub>n-1</sub> = Previous carry
Steps for Generate Random Numbers
The following steps implement the multiply-with-carry method to generate random numbers:
- We have used the uint32_t to declare 'x' and 'c'. The uint32_t defines a 32-bit unsigned integer.
- The MWCGenerator constructor sets the starting seed and creates an initial carry using the right shift operator.
- Then, we used the formula of the multiply-with-carry method and stored it in uint64_t t. After that, we have updated the value of the carry and the state.
- In the end, we returned the random number and printed the numbers using the for loop in the main() function.
C++ Program for Generate Random Numbers
Here is the C++ code implementation of the above steps to generate random numbers using the Multiply With Carry method.
#include <iostream>
#include <cstdint>
using namespace std;
class MWCGenerator {
private:
uint32_t x;
uint32_t c; // carry
static constexpr uint32_t a = 4294957665U; // good multiplier
public:
MWCGenerator(uint32_t seed = 12345) : x(seed), c(seed >> 1) {}
uint32_t next() {
uint64_t t = static_cast<uint64_t>(a) * x + c;
c = t >> 32; // upper 32 bits: new carry
x = t & 0xFFFFFFFF; // lower 32 bits: new state
return x;
}
};
int main() {
MWCGenerator rng(123456789); // initialize with a seed
cout << "Multiply with Carry Random Numbers:\n";
for (int i = 0; i < 5; ++i) {
cout << rng.next() << "\n";
}
return 0;
}
The output of the above code is as follows:
Multiply with Carry Random Numbers: 755334527 1171226399 3552970656 515283068 1548961661
