Reputation: 135
I'm trying to implement a pseudo random number generator in MATLAB. I'm building it according to the following recipe:
Create the random number generator seed, x_0. Get and save bits 8...15 of x_0 to the cell named random_numbers.
For Loop: Create the next n numbers using rem( (25173 * previous_number + 13849) + 2^16) ). Save bits 8...15 of number n to the cell named random_numbers. Print number n.
Step 1:
n = 2000;
% Pre-allocate cell with size n numbers
random_numbers = cell(1, n);
% Generate seed in range 1 - 2^16 - 1
x_0 = randi([1, 2^16-1]);
% Save seed as binary array of size 16 bits
x_0 = de2bi(x_0, 16);
% Extract bits 8...15 from seed
x_0 = x_0(8:15);
% Add bits 8...15 from seed to cell
random_numbers{1} = x_0;
Step 2:
for x = 2:n
% Get previous number as base 10 number
previous_number = bi2de(random_numbers{x - 1});
% Calculate random number
random_number = rem( (25173 * previous_number + 13849), 2^16 );
% Convert random number to binary, extract bits 8...15
random_number = de2bi(random_number, 16);
random_number = random_number(8:15);
% Save bits 8...15 of random number to cell
random_numbers{x} = random_number;
% Print bits 8...15 of random number as decimal number
disp(num2str(bi2de(random_number)))
end
So what's the problem? If you run this code you'll notice that the initial numbers are unique. The initial numbers do not repeat themselves. However the remaining numbers created with this algorithm do follow a certain pattern. I want every number to follow the same pattern. It would be very much appreciated if someone could help me figure out what I'm doing wrong.
Upvotes: 1
Views: 821
Reputation: 112669
Your code looks like the classical algorithm for random number generation except for the line
random_number = random_number(8:15);
I assume you added that because you want to generate random numbers from 0 to 255. The problem is that that line is affecting not just the output number, but also the state you save for the next iteration. That's what's likely causing the problem.
If you want to alter the output number, that's fine, but you shouldn't alter the state which will be used for generating the next number. If you do that you are changing the algorithm, and the period of the generator state sequence.
So: move the line random_number = random_number(8:15);
after the line random_numbers{x} = random_number;
.
Upvotes: 1