Reputation: 749
I am trying to recreate a multiplicative congruential algorithm that is used in Matlab (Found it here, section 9.2, read it for a little context)
Basically, I have 4 variables
a = 13
c = 0
m = 31
And this last one, which I can't format to code because it breaks the subscript:
x0= 1
And with those four, I'd like to reproduce something like this :
xk+1 = a *
xk + c mod m
So far, I've got :
a = 13
c = 0
m = 31
base = 2 # Does not work with 0 for some reason
x = int(x='1', base=base)
for i in range(8):
rand = a * x + c % m
base += 1
x = int(x='1', base=base)
print(rand)
And my output is :
13, 13, 13, 13, 13, 13, 13, 13...
Even though, according to the document, should be :
1, 13, 14, 27, 10, 6, 16, 22...
So I'm not sure if I completely misunderstood the question, or if what I'm trying to accomplish is simply not possible in Python, or if I'm just going bonkers, but I desperately need some advice. Any insights are greatly appreciated.
Upvotes: 2
Views: 87
Reputation: 698
It looks like the problem is that the formula should be
xk+1 = (a * xk + c) mod m
which isn't clear from the document, but if you use c mod m as they have it, you would be performing the same operation every time (0mod31). This segment of python code runs as it should:
a = 13
c = 0
m = 31
x = [1]
for i in range(1, 9):
x.append( (a * x[i-1] + c)%m )
print x[i],
13 14 27 10 6 16 22 7
Upvotes: 2