/
Manual_implementation_of_the_Mersenne_twister_PseudoRandom_Number_Generator__PRNG_.py
1715 lines (1045 loc) · 59 KB
/
Manual_implementation_of_the_Mersenne_twister_PseudoRandom_Number_Generator__PRNG_.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
# # Table of Contents
# <p><div class="lev1 toc-item"><a href="#Manual-implementation-of-the-Mersenne-twister-PseudoRandom-Number-Generator-(PRNG)" data-toc-modified-id="Manual-implementation-of-the-Mersenne-twister-PseudoRandom-Number-Generator-(PRNG)-1"><span class="toc-item-num">1 </span>Manual implementation of the Mersenne twister PseudoRandom Number Generator (PRNG)</a></div><div class="lev2 toc-item"><a href="#Common-API-for-the-PRNG-defined-here" data-toc-modified-id="Common-API-for-the-PRNG-defined-here-11"><span class="toc-item-num">1.1 </span>Common API for the PRNG defined here</a></div><div class="lev2 toc-item"><a href="#First-example:-a-simple-linear-congruential-generator" data-toc-modified-id="First-example:-a-simple-linear-congruential-generator-12"><span class="toc-item-num">1.2 </span>First example: a simple linear congruential generator</a></div><div class="lev2 toc-item"><a href="#Trying-to-write-a-cell-in-cython,-for-speeding-things-up" data-toc-modified-id="Trying-to-write-a-cell-in-cython,-for-speeding-things-up-13"><span class="toc-item-num">1.3 </span>Trying to write a cell in <a href="http://cython.org/" target="_blank"><code>cython</code></a>, for speeding things up</a></div><div class="lev2 toc-item"><a href="#Checking-and-plotting-the-result?" data-toc-modified-id="Checking-and-plotting-the-result?-14"><span class="toc-item-num">1.4 </span>Checking and plotting the result?</a></div><div class="lev2 toc-item"><a href="#A-second-example:-Multiple-Recursive-Generator" data-toc-modified-id="A-second-example:-Multiple-Recursive-Generator-15"><span class="toc-item-num">1.5 </span>A second example: Multiple-Recursive Generator</a></div><div class="lev2 toc-item"><a href="#A-third-example:-combined-Multiple-Recursive-Generator,-with-MRG32k3a" data-toc-modified-id="A-third-example:-combined-Multiple-Recursive-Generator,-with-MRG32k3a-16"><span class="toc-item-num">1.6 </span>A third example: combined Multiple-Recursive Generator, with <code>MRG32k3a</code></a></div><div class="lev2 toc-item"><a href="#Finally,-the-Mersenne-twister-PRNG" data-toc-modified-id="Finally,-the-Mersenne-twister-PRNG-17"><span class="toc-item-num">1.7 </span>Finally, the Mersenne twister PRNG</a></div><div class="lev3 toc-item"><a href="#Period" data-toc-modified-id="Period-171"><span class="toc-item-num">1.7.1 </span>Period</a></div><div class="lev3 toc-item"><a href="#Random-seeds" data-toc-modified-id="Random-seeds-172"><span class="toc-item-num">1.7.2 </span>Random seeds</a></div><div class="lev3 toc-item"><a href="#Implementing-the-Mersenne-twister-algorithm" data-toc-modified-id="Implementing-the-Mersenne-twister-algorithm-173"><span class="toc-item-num">1.7.3 </span>Implementing the Mersenne twister algorithm</a></div><div class="lev3 toc-item"><a href="#Small-review-of-bitwise-operations" data-toc-modified-id="Small-review-of-bitwise-operations-174"><span class="toc-item-num">1.7.4 </span>Small review of bitwise operations</a></div><div class="lev3 toc-item"><a href="#Mersenne-twister-algorithm-in-cython" data-toc-modified-id="Mersenne-twister-algorithm-in-cython-175"><span class="toc-item-num">1.7.5 </span>Mersenne twister algorithm in <a href="http://www.cython.org/" target="_blank"><code>cython</code></a></a></div><div class="lev3 toc-item"><a href="#Testing-our-implementations" data-toc-modified-id="Testing-our-implementations-176"><span class="toc-item-num">1.7.6 </span>Testing our implementations</a></div><div class="lev2 toc-item"><a href="#Conclusion" data-toc-modified-id="Conclusion-18"><span class="toc-item-num">1.8 </span>Conclusion</a></div><div class="lev1 toc-item"><a href="#Generating-samples-from-other-distributions" data-toc-modified-id="Generating-samples-from-other-distributions-2"><span class="toc-item-num">2 </span>Generating samples from other distributions</a></div><div class="lev2 toc-item"><a href="#Bernoulli-distribution" data-toc-modified-id="Bernoulli-distribution-21"><span class="toc-item-num">2.1 </span>Bernoulli distribution</a></div><div class="lev2 toc-item"><a href="#Uniform-distribution-on-$[a,-b)$,-for-floats-and-integers" data-toc-modified-id="Uniform-distribution-on-$[a,-b)$,-for-floats-and-integers-22"><span class="toc-item-num">2.2 </span>Uniform distribution on $[a, b)$, for floats and integers</a></div><div class="lev2 toc-item"><a href="#Exponential-distribution" data-toc-modified-id="Exponential-distribution-23"><span class="toc-item-num">2.3 </span>Exponential distribution</a></div><div class="lev2 toc-item"><a href="#Gaussian-distribution-(normal)" data-toc-modified-id="Gaussian-distribution-(normal)-24"><span class="toc-item-num">2.4 </span>Gaussian distribution (normal)</a></div><div class="lev2 toc-item"><a href="#Erlang-distribution" data-toc-modified-id="Erlang-distribution-25"><span class="toc-item-num">2.5 </span>Erlang distribution</a></div><div class="lev2 toc-item"><a href="#Gamma-distribution" data-toc-modified-id="Gamma-distribution-26"><span class="toc-item-num">2.6 </span>Gamma distribution</a></div><div class="lev2 toc-item"><a href="#Beta-distribution" data-toc-modified-id="Beta-distribution-27"><span class="toc-item-num">2.7 </span>Beta distribution</a></div><div class="lev2 toc-item"><a href="#Integer-Beta-distribution" data-toc-modified-id="Integer-Beta-distribution-28"><span class="toc-item-num">2.8 </span>Integer Beta distribution</a></div><div class="lev2 toc-item"><a href="#Binomial-distribution" data-toc-modified-id="Binomial-distribution-29"><span class="toc-item-num">2.9 </span>Binomial distribution</a></div><div class="lev2 toc-item"><a href="#Geometric-distribution" data-toc-modified-id="Geometric-distribution-210"><span class="toc-item-num">2.10 </span>Geometric distribution</a></div><div class="lev2 toc-item"><a href="#Poisson-distribution" data-toc-modified-id="Poisson-distribution-211"><span class="toc-item-num">2.11 </span>Poisson distribution</a></div><div class="lev2 toc-item"><a href="#Conclusion" data-toc-modified-id="Conclusion-212"><span class="toc-item-num">2.12 </span>Conclusion</a></div><div class="lev1 toc-item"><a href="#Generating-vectors" data-toc-modified-id="Generating-vectors-3"><span class="toc-item-num">3 </span>Generating vectors</a></div><div class="lev2 toc-item"><a href="#Discrete-distribution" data-toc-modified-id="Discrete-distribution-31"><span class="toc-item-num">3.1 </span>Discrete distribution</a></div><div class="lev2 toc-item"><a href="#Generating-a-random-vector-uniformly-on-a-n-dimensional-ball" data-toc-modified-id="Generating-a-random-vector-uniformly-on-a-n-dimensional-ball-32"><span class="toc-item-num">3.2 </span>Generating a random vector uniformly on a n-dimensional ball</a></div><div class="lev2 toc-item"><a href="#Generating-a-random-permutation" data-toc-modified-id="Generating-a-random-permutation-33"><span class="toc-item-num">3.3 </span>Generating a random permutation</a></div><div class="lev2 toc-item"><a href="#Conclusion" data-toc-modified-id="Conclusion-34"><span class="toc-item-num">3.4 </span>Conclusion</a></div>
# # Manual implementation of the Mersenne twister PseudoRandom Number Generator (PRNG)
# This small notebook is a short experiment, to see if I can implement the [Mersenne twister](https://en.wikipedia.org/wiki/Mersenne_twister) PseudoRandom Number Generator ([PRNG](https://en.wikipedia.org/wiki/Pseudo-random_number_generator)).
#
# And then I want to use it to define a `rand()` function, and use it to samples from the most famous discrete and continuous probability distributions.
# Random permutations will also be studied.
#
# - *Reference*: [Wikipedia](https://en.wikipedia.org/wiki/Mersenne_twister), and this book: ["Simulation and the Monte-Carlo method", by R.Y.Rubinstein & D.P.Kroese](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118632168.html) ([Rubinstein & Kroese, 2017]), chapter 2 pages 52-53. If you are curious, [this webpage](https://realpython.com/python-random/) is a good explanation of the difference between PRNG, Cryptographically Secure PRNG (CSPRNG) and "True" NRG.
# - *Date*: 11 March 2017.
# - *Author*: [Lilian Besson](https://GitHub.com/Naereen/notebooks).
# - *License*: [MIT Licensed](https://lbesson.mit-license.org/).
#
# ----
# ## Common API for the PRNG defined here
# First, I want to define a simple object-oriented API, in order to write all the examples of PNRG with the same interface.
# In[131]:
import numpy as np
# In[132]:
class PRNG(object):
"""Base class for any Pseudo-Random Number Generator."""
def __init__(self, X0=0):
"""Create a new PRNG with seed X0."""
self.X0 = X0
self.X = X0
self.t = 0
self.max = 0
def __iter__(self):
"""self is already an iterator!"""
return self
def seed(self, X0=None):
"""Reinitialize the current value with X0, or self.X0.
- Tip: Manually set the seed if you need reproducibility in your results.
"""
self.t = 0
self.X = self.X0 if X0 is None else X0
def __next__(self):
"""Produce a next value and return it."""
# This default PRNG does not produce random numbers!
self.t += 1
return self.X
def randint(self, *args, **kwargs):
"""Return an integer number in [| 0, self.max - 1 |] from the PRNG."""
return self.__next__()
def int_samples(self, shape=(1,)):
"""Get a numpy array, filled with integer samples from the PRNG, of shape = shape."""
# return [ self.randint() for _ in range(size) ]
return np.fromfunction(np.vectorize(self.randint), shape=shape, dtype=int)
def rand(self, *args, **kwargs):
"""Return a float number in [0, 1) from the PRNG."""
return self.randint() / float(1 + self.max)
def float_samples(self, shape=(1,)):
"""Get a numpy array, filled with float samples from the PRNG, of shape = shape."""
# return [ self.rand() for _ in range(size) ]
return np.fromfunction(np.vectorize(self.rand), shape=shape, dtype=int)
# ----
# ## First example: a simple linear congruential generator
# Let me start by implementing a simple linear congruential generator, with three parameters $m$, $a$, $c$, defined like this :
#
# - Start from $X_0$,
# - And then follow the recurrence equation: $$ X_{t+1} = (a X_t + c) \mod m. $$
#
# This algorithm produces a sequence $(X_t)_{t\in\mathbb{N}} \in \mathbb{N}^{\mathbb{N}}$.
# In[133]:
class LinearCongruentialGenerator(PRNG):
"""A simple linear congruential Pseudo-Random Number Generator."""
def __init__(self, m, a, c, X0=0):
"""Create a new PRNG with seed X0."""
super(LinearCongruentialGenerator, self).__init__(X0=X0)
self.m = self.max = m
self.a = a
self.c = c
def __next__(self):
"""Produce a next value and return it, following the recurrence equation: X_{t+1} = (a X_t + c) mod m."""
self.t += 1
x = self.X
self.X = (self.a * self.X + self.c) % self.m
return x
# The values recommended by the authors, Lewis, Goodman and Miller, are the following:
# In[134]:
m = 1 << 31 - 1 # 1 << 31 = 2**31
a = 7 ** 4
c = 0
# The seed is important. If $X_0 = 0$, this first example PRNG will only produce $X_t = 0, \forall t$.
# In[135]:
FirstExample = LinearCongruentialGenerator(m=m, a=a, c=c)
# In[136]:
def test(example, nb=3):
for t, x in enumerate(example):
print("{:>3}th value for {.__class__.__name__} is X_t = {:>10}".format(t, example, x))
if t >= nb - 1:
break
# In[137]:
test(FirstExample)
# But with any positive seed, the sequence will appear random.
# In[138]:
SecondExample = LinearCongruentialGenerator(m=m, a=a, c=c, X0=12011993)
# In[139]:
test(SecondExample)
# The sequence is completely determined by the seed $X_0$:
# In[140]:
SecondExample.seed(12011993)
test(SecondExample)
# > Note: I prefer to use this custom class to define iterators, instead of a simple generator (with `yield` keyword) as I want them to have a `.seed(X0)` method.
# ## Trying to write a cell in [`cython`](http://cython.org/), for speeding things up
# > For more details, see [this blog post](https://acsgsoc15.wordpress.com/2015/04/07/using-cython-in-ipython/), and [this other one](https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/#22-writing-functions-in-other-languages).
# In[141]:
# Thanks to https://nbviewer.jupyter.org/gist/minrk/7715212
from __future__ import print_function
from IPython.core import page
def myprint(s):
try:
print(s['text/plain'])
except (KeyError, TypeError):
print(s)
page.page = myprint
# In[142]:
get_ipython().run_line_magic('load_ext', 'cython')
# Then we define a function `LinearCongruentialGenerator_next`, in a Cython cell.
# In[143]:
get_ipython().run_cell_magic('cython', '', 'def nextLCG(int x, int a, int c, int m):\n """Compute x, nextx = (a * x + c) % m, x in Cython."""\n cdef int nextx = (a * x + c) % m\n return (x, nextx)')
# In[144]:
from __main__ import nextLCG
nextLCG
get_ipython().run_line_magic('pinfo', 'nextLCG')
# Then it's easy to use it to define another Linear Congruential Generator.
# In[145]:
class CythonLinearCongruentialGenerator(LinearCongruentialGenerator):
"""A simple linear congruential Pseudo-Random Number Generator, with Cython accelerated function __next__."""
def __next__(self):
"""Produce a next value and return it, following the recurrence equation: X_{t+1} = (a X_t + c) mod m."""
self.t += 1
x, self.X = nextLCG(self.X, self.a, self.c, self.m)
return x
# Let compare it with the first implementation (using pure Python).
# In[146]:
NotCythonSecondExample = LinearCongruentialGenerator(m=m, a=a, c=c, X0=13032017)
CythonSecondExample = CythonLinearCongruentialGenerator(m=m, a=a, c=c, X0=13032017)
# They both give the same values, that's a relief.
# In[147]:
test(NotCythonSecondExample)
test(CythonSecondExample)
# The speedup is not great, but still visible.
# In[148]:
get_ipython().run_line_magic('timeit', '[ NotCythonSecondExample.randint() for _ in range(1000000) ]')
get_ipython().run_line_magic('timeit', '[ CythonSecondExample.randint() for _ in range(1000000) ]')
# In[149]:
get_ipython().run_line_magic('prun', 'min(CythonSecondExample.randint() for _ in range(1000000))')
# ----
# ## Checking and plotting the result?
# First, we can generate a matrix of samples, as random floats in $[0, 1)$, and check that the mean is about $1/2$:
# In[150]:
shape = (400, 400)
image = SecondExample.float_samples(shape)
# In[151]:
np.mean(image), np.var(image)
# What about the speed? Of course, a hand-written Python code will always be really slower than a C-extension code, and the PRNG from the modules `random` or `numpy.random` are written in C (or Cython), and so will always be faster.
# But how much faster?
# In[152]:
import random
import numpy.random
print(np.mean(SecondExample.float_samples(shape)))
print(np.mean([ [ random.random() for _ in range(shape[0]) ] for _ in range(shape[1]) ]))
print(np.mean(numpy.random.random(shape)))
# In[153]:
get_ipython().run_line_magic('timeit', 'SecondExample.float_samples(shape)')
get_ipython().run_line_magic('timeit', '[ [ random.random() for _ in range(shape[0]) ] for _ in range(shape[1]) ]')
get_ipython().run_line_magic('timeit', 'numpy.random.random(shape)')
# This was expected: of course `numpy.random.` functions are written and optimized to generate thousands of samples quickly, and of course my hand-written Python implementation for `LinearCongruentialGenerator` is slower than the C-code generating the module `random`.
# ----
# We can also plot this image as a grayscaled image, in order to visualize this "randomness" we just created.
# In[268]:
get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt
def showimage(image):
plt.figure(figsize=(8, 8))
plt.imshow(image, cmap='gray', interpolation='none')
plt.axis('off')
plt.show()
# In[269]:
showimage(image)
# It looks good already! We can't see any recurrence, but we see a regularity, with small squares.
#
# And it does not seem to depend too much on the seed:
# In[270]:
SecondExample.seed(11032017)
image = SecondExample.float_samples((10, 10))
showimage(image)
# In[271]:
SecondExample.seed(1103201799)
image = SecondExample.float_samples((10, 10))
showimage(image)
# We can also visualize the generated numbers with a histogram, to visually check that the random numbers in $[0, 1)$ are indeed "uniformly" located.
# In[272]:
def plotHistogram(example, nb=100000, bins=200):
numbers = example.float_samples((nb,))
plt.figure(figsize=(16, 5))
plt.hist(numbers, bins=bins, normed=True, alpha=0.8)
plt.xlabel("Random numbers in $[0, 1)$")
plt.ylabel("Mass repartition")
plt.title("Repartition of ${}$ random numbers in $[0, 1)$".format(nb))
plt.show()
# In[273]:
plotHistogram(SecondExample, 1000000, 200)
# ----
# ## A second example: Multiple-Recursive Generator
# Let start by writing a generic Multiple Recursive Generator, which is defined by the following linear recurrence equation, of order $k \geq 1$:
#
# - Start from $X_0$, with a false initial history of $(X_{-k+1}, X_{-k}, \dots, X_{-1})$,
# - And then follow the recurrence equation: $$ X_{t} = (a_1 X_{t-1} + \dots + a_k X_{t-k}) \mod m. $$
#
# This algorithm produces a sequence $(X_t)_{t\in\mathbb{N}} \in \mathbb{N}^{\mathbb{N}}$.
# In[160]:
class MultipleRecursiveGenerator(PRNG):
"""A Multiple Recursive Pseudo-Random Number Generator (MRG), with one sequence (X_t)."""
def __init__(self, m, a, X0):
"""Create a new PRNG with seed X0."""
assert np.shape(a) == np.shape(X0), "Error: the weight vector a must have the same shape as X0."
super(MultipleRecursiveGenerator, self).__init__(X0=X0)
self.m = self.max = m
self.a = a
def __next__(self):
"""Produce a next value and return it, following the recurrence equation: X_t = (a_1 X_{t-1} + ... + a_k X_{t-k}) mod m."""
self.t += 1
x = self.X[0]
nextx = (np.dot(self.a, self.X)) % self.m
self.X[1:] = self.X[:-1]
self.X[0] = nextx
return x
# For example, with an arbitrary choice of $k = 3$, of weights $a = [10, 9, 8]$ and $X_0 = [10, 20, 30]$:
# In[161]:
m = (1 << 31) - 1
X0 = np.array([10, 20, 30])
a = np.array([10, 9, 8])
ThirdExample = MultipleRecursiveGenerator(m, a, X0)
test(ThirdExample)
# We can again check for the mean and the variance of the generated sequence:
# In[275]:
shape = (400, 400)
image = ThirdExample.float_samples(shape)
np.mean(image), np.var(image)
# This Multiple Recursive Generator is of course slower than the simple Linear Recurrent Generator:
# In[163]:
get_ipython().run_line_magic('timeit', 'SecondExample.float_samples(shape)')
get_ipython().run_line_magic('timeit', 'ThirdExample.float_samples(shape)')
# And it seems to work fine as well:
# In[276]:
showimage(image)
# In[277]:
plotHistogram(ThirdExample, 1000000, 200)
# > It looks also good!
# ----
# ## A third example: combined Multiple-Recursive Generator, with `MRG32k3a`
#
# Let start by writing a generic Multiple Recursive Generator, which is defined by the following coupled linear recurrence equation, of orders $k_1, k_2 \geq 1$:
#
# - Start from $X_0$ and $Y_0$, with a false initial history of $(X_{-k_1 + 1}, X_{-k_1}, \dots, X_{-1})$ and $(Y_{-k_2 + 1}, Y_{-k_2}, \dots, Y_{-1})$,
# - And then follow the recurrence equation: $$ X_{t} = (a_1 X_{t-1} + \dots + a_{k_1} X_{t-k_1}) \mod m. $$ and $$ Y_{t} = (b_1 Y_{t-1} + \dots + b_{k_2} Y_{t-k_2}) \mod m. $$
#
# This algorithm produces two sequences $(X_t)_{t\in\mathbb{N}} \in \mathbb{N}^{\mathbb{N}}$ and $(X_t)_{t\in\mathbb{N}} \in \mathbb{N}^{\mathbb{N}}$, and usually the sequence used for the output is $U_t = X_t - Y_t + \max(m_1, m_2)$.
# In[166]:
class CombinedMultipleRecursiveGenerator(PRNG):
"""A Multiple Recursive Pseudo-Random Number Generator (MRG), with two sequences (X_t, Y_t)."""
def __init__(self, m1, a, X0, m2, b, Y0):
"""Create a new PRNG with seeds X0, Y0."""
assert np.shape(a) == np.shape(X0), "Error: the weight vector a must have the same shape as X0."
assert np.shape(b) == np.shape(Y0), "Error: the weight vector b must have the same shape as Y0."
self.t = 0
# For X
self.m1 = m1
self.a = a
self.X0 = self.X = X0
# For Y
self.m2 = m2
self.b = b
self.Y0 = self.Y = Y0
# Maximum integer number produced is max(m1, m2)
self.m = self.max = max(m1, m2)
def __next__(self):
"""Produce a next value and return it, following the recurrence equation: X_t = (a_1 X_{t-1} + ... + a_k X_{t-k}) mod m."""
self.t += 1
# For X
x = self.X[0]
nextx = (np.dot(self.a, self.X)) % self.m1
self.X[1:] = self.X[:-1]
self.X[0] = nextx
# For Y
y = self.Y[0]
nexty = (np.dot(self.b, self.Y)) % self.m2
self.Y[1:] = self.Y[:-1]
self.Y[0] = nexty
# Combine them
u = x - y + (self.m1 if x <= y else 0)
return u
# To obtain the well-known `MRG32k3a` generator, designed by L'Ecuyer in 1999, we choose these parameters:
# In[167]:
m1 = (1 << 32) - 209 # important choice!
a = np.array([0, 1403580, -810728]) # important choice!
X0 = np.array([1000, 10000, 100000]) # arbitrary choice!
m2 = (1 << 32) - 22853 # important choice!
b = np.array([527612, 0, -1370589]) # important choice!
Y0 = np.array([5000, 50000, 500000]) # arbitrary choice!
MRG32k3a = CombinedMultipleRecursiveGenerator(m1, a, X0, m2, b, Y0)
test(MRG32k3a)
# We can again check for the mean and the variance of the generated sequence:
# In[278]:
shape = (400, 400)
image = MRG32k3a.float_samples(shape)
np.mean(image), np.var(image)
# This combined Multiple Recursive Generator is of course slower than the simple Multiple Recursive Generator and the simple Linear Recurrent Generator:
# In[169]:
get_ipython().run_line_magic('timeit', 'SecondExample.float_samples(shape)')
get_ipython().run_line_magic('timeit', 'ThirdExample.float_samples(shape)')
get_ipython().run_line_magic('timeit', 'MRG32k3a.float_samples(shape)')
# In[279]:
showimage(image)
# In[280]:
plotHistogram(MRG32k3a, 1000000, 200)
# > This one looks fine too!
# ----
# ## Finally, the Mersenne twister PRNG
#
# I won't explain all the details, and will follow closely the notations from my reference book [Rubinstein & Kroese, 2017].
# It will be harder to implement!
#
# First, let us compute the period of the PRNG we will implement, with the default values for the parameters $w = 32$ (word length) and $n = 624$ ("big" integer).
# ### Period
# In[172]:
w = 32
n = 624
# In[173]:
def MersenneTwisterPeriod(n, w):
return (1 << (w * (n - 1) + 1)) - 1
MersenneTwisterPeriod(n, w) == (2 ** 19937) - 1
# ### Random seeds
# Then we need to use a previously defined PRNG to set the random seeds.
#
# To try to have "really random" seeds, let me use that classical trick of using the system time as a source of initial randomness.
#
# - Namely, I will use the number of microseconds in the current time stamp as the seed for a `LinearCongruentialGenerator`,
# - Then use it to generate the seeds for a `MRG32k3a` generator,
# - And finally use it to get the seed for the Mersenne twister.
# In[174]:
from datetime import datetime
def get_seconds():
d = datetime.today().timestamp()
s = 1e6 * (d - int(d))
return int(s)
# In[175]:
get_seconds() # Example
# In[176]:
def seed_rows(example, n, w):
return example.int_samples((n,))
def random_Mersenne_seed(n, w):
linear = LinearCongruentialGenerator(m=(1 << 31) - 1, a=7 ** 4, c=0, X0=get_seconds())
assert w == 32, "Error: only w = 32 was implemented"
m1 = (1 << 32) - 209 # important choice!
a = np.array([0, 1403580, -810728]) # important choice!
X0 = np.array(linear.int_samples((3,))) # random choice!
m2 = (1 << 32) - 22853 # important choice!
b = np.array([527612, 0, -1370589]) # important choice!
Y0 = np.array(linear.int_samples((3,))) # random choice!
MRG32k3a = CombinedMultipleRecursiveGenerator(m1, a, X0, m2, b, Y0)
seed = seed_rows(MRG32k3a, n, w)
assert np.shape(seed) == (n,)
return seed
example_seed = random_Mersenne_seed(n, w)
example_seed
# In[177]:
for xi in example_seed:
print("Integer xi = {:>12} and in binary, bin(xi) = {:>34}".format(xi, bin(xi)))
# ### Implementing the Mersenne twister algorithm
# Finally, the Mersenne twister can be implemented like this:
# In[179]:
class MersenneTwister(PRNG):
"""The Mersenne twister Pseudo-Random Number Generator (MRG)."""
def __init__(self, seed=None,
w=32, n=624, m=397, r=31,
a=0x9908B0DF, b=0x9D2C5680, c=0xEFC60000,
u=11, s=7, v=15, l=18):
"""Create a new Mersenne twister PRNG with this seed."""
self.t = 0
# Parameters
self.w = w
self.n = n
self.m = m
self.r = r
self.a = a
self.b = b
self.c = c
self.u = u
self.s = s
self.v = v
self.l = l
# For X
if seed is None:
seed = random_Mersenne_seed(n, w)
self.X0 = seed
self.X = np.copy(seed)
# Maximum integer number produced is 2**w - 1
self.max = (1 << w) - 1
def __next__(self):
"""Produce a next value and return it, following the Mersenne twister algorithm."""
self.t += 1
# 1. --- Compute x_{t+n}
# 1.1.a. First r bits of x_t : left = (x_t >> (w - r)) << (w - r)
# 1.1.b. Last w - r bits of x_{t+1} : right = x & ((1 << (w - r)) - 1)
# 1.1.c. Concatenate them together in a binary vector x : x = left + right
left = self.X[0] >> (self.w - self.r)
right = (self.X[1] & ((1 << (self.w - self.r)) - 1))
x = (left << (self.w - self.r)) + right
xw = x % 2 # 1.2. get xw
if xw == 0:
xtilde = (x >> 1) # if xw = 0, xtilde = (x >> 1)
else:
xtilde = (x >> 1) ^ self.a # if xw = 1, xtilde = (x >> 1) ⊕ a
nextx = self.X[self.m] ^ xtilde # 1.3. x_{t+n} = x_{t+m} ⊕ \tilde{x}
# 2. --- Shift the content of the n rows
oldx0 = self.X[0] # 2.a. First, forget x0
self.X[:-1] = self.X[1:] # 2.b. shift one index on the left, x1..xn-1 to x0..xn-2
self.X[-1] = nextx # 2.c. write new xn-1
# 3. --- Then use it to compute the answer, y
y = nextx # 3.a. y = x_{t+n}
y ^= (y >> self.u) # 3.b. y = y ⊕ (y >> u)
y ^= ((y << self.s) & self.b) # 3.c. y = y ⊕ ((y << s) & b)
y ^= ((y << self.v) & self.c) # 3.d. y = y ⊕ ((y << v) & c)
y ^= (y >> self.l) # 3.e. y = y ⊕ (y >> l)
return y
# ### Small review of bitwise operations
#
# The Python documentation explains how to [use bitwise operations easily](https://docs.python.org/3/library/stdtypes.html?highlight=bitwise#bitwise-operations-on-integer-types), and also [this page](https://wiki.python.org/moin/BitwiseOperators) and [this StackOverflow answer](http://stackoverflow.com/a/1746642/).
#
# The only difficult part of the algorithm is the first step, when we need to take the first $r$ bits of $X_t =$ `X[0]`, and the last $w - r$ bits of $X_{t+1} =$ `X[1]`.
# On some small examples, let quickly check that I implemented this correctly:
# In[180]:
def testsplit(x, r=None, w=None):
if w is None:
w = x.bit_length()
if r is None:
r = w - 1
assert x.bit_length() == w
left = x >> (w - r)
right = x % 2 if w == 1 else x & ((1 << (w-r) - 1))
x2 = (left << (w - r)) + right
assert x == x2
print("x = {:10} -> left r={} = {:10} and right w-r={} = {:4} -> x2 = {:10}".format(bin(x), r, bin(left), w-r, bin(right), bin(x2)))
x = 0b10011010
testsplit(x)
x = 0b10010011
testsplit(x)
x = 0b10011111
testsplit(x)
x = 0b11110001
testsplit(x)
x = 0b00110001
testsplit(x)
# ### Mersenne twister algorithm in [`cython`](http://www.cython.org/)
# As for the first example, let us write a Cython function to (try to) compute the next numbers more easily.
#
# My reference was [this page of the Cython documentation](http://docs.cython.org/en/latest/src/userguide/numpy_tutorial.html).
# In[262]:
get_ipython().run_cell_magic('cython', '', 'from __future__ import division\nimport cython\nimport numpy as np\n# "cimport" is used to import special compile-time information\n# about the numpy module (this is stored in a file numpy.pxd which is\n# currently part of the Cython distribution).\ncimport numpy as np\n\n# We now need to fix a datatype for our arrays. I\'ve used the variable\n# DTYPE for this, which is assigned to the usual NumPy runtime\n# type info object.\nDTYPE = np.int64\n# "ctypedef" assigns a corresponding compile-time type to DTYPE_t. For\n# every type in the numpy module there\'s a corresponding compile-time\n# type with a _t-suffix.\nctypedef np.int64_t DTYPE_t\n\n\n@cython.boundscheck(False) # turn off bounds-checking for entire function\ndef nextMersenneTwister(np.ndarray[DTYPE_t, ndim=1] X, unsigned long w, unsigned long m, unsigned long r, unsigned long a, unsigned long u, unsigned long s, unsigned long b, unsigned long v, unsigned long c, unsigned long l):\n """Produce a next value and return it, following the Mersenne twister algorithm, implemented in Cython."""\n assert X.dtype == DTYPE\n # 1. --- Compute x_{t+n}\n # 1.1.a. First r bits of x_t : left = (x_t >> (w - r)) << (w - r)\n # 1.1.b. Last w - r bits of x_{t+1} : right = x & ((1 << (w - r)) - 1)\n # 1.1.c. Concatenate them together in a binary vector x : x = left + right\n cdef unsigned long x = ((X[0] >> (w - r)) << (w - r)) + (X[1] & ((1 << (w - r)) - 1))\n cdef unsigned long xtilde = 0\n if x % 2 == 0: # 1.2. get xw\n xtilde = (x >> 1) # if xw = 0, xtilde = (x >> 1)\n else:\n xtilde = (x >> 1) ^ a # if xw = 1, xtilde = (x >> 1) ⊕ a\n cdef unsigned long nextx = X[m] ^ xtilde # 1.3. x_{t+n} = x_{t+m} ⊕ \\tilde{x}\n # 2. --- Shift the content of the n rows\n # oldx0 = X[0] # 2.a. First, forget x0\n X[:-1] = X[1:] # 2.b. shift one index on the left, x1..xn-1 to x0..xn-2\n X[-1] = nextx # 2.c. write new xn-1\n # 3. --- Then use it to compute the answer, y\n cdef unsigned long y = nextx # 3.a. y = x_{t+n}\n y ^= (y >> u) # 3.b. y = y ⊕ (y >> u)\n y ^= ((y << s) & b) # 3.c. y = y ⊕ ((y << s) & b)\n y ^= ((y << v) & c) # 3.d. y = y ⊕ ((y << v) & c)\n y ^= (y >> l) # 3.e. y = y ⊕ (y >> l)\n return y')
# In[263]:
nextMersenneTwister
get_ipython().run_line_magic('pinfo', 'nextMersenneTwister')
# That should be enough to define a Cython version of our `MersenneTwister` class.
# In[264]:
class CythonMersenneTwister(MersenneTwister):
"""The Mersenne twister Pseudo-Random Number Generator (MRG), accelerated with Cython."""
def __next__(self):
"""Produce a next value and return it, following the Mersenne twister algorithm."""
self.t += 1
return nextMersenneTwister(self.X, self.w, self.m, self.r, self.a, self.u, self.s, self.b, self.v, self.c, self.l)
# ### Testing our implementations
# In[265]:
ForthExample = MersenneTwister(seed=example_seed)
CythonForthExample = CythonMersenneTwister(seed=example_seed)
# In[266]:
ForthExample.int_samples((10,))
CythonForthExample.int_samples((10,))
# Which one is the quickest?
# In[267]:
get_ipython().run_line_magic('timeit', '[ ForthExample.randint() for _ in range(100000) ]')
get_ipython().run_line_magic('timeit', '[ CythonForthExample.randint() for _ in range(100000) ]')
# Using Cython gives only a speedup of $2 \times$, that's disappointing!
# In[187]:
get_ipython().run_line_magic('prun', '[ ForthExample.randint() for _ in range(1000000) ]')
# In[188]:
get_ipython().run_line_magic('prun', '[ CythonForthExample.randint() for _ in range(1000000) ]')
# $\implies$ the Cython version is twice as fast as the pure-Python version.
# We can still improve this, I am sure.
#
# ----
# We can again check for the mean and the variance of the generated sequence.
# Mean should be $\frac12 = 0.5$ and variance should be $\frac{(b-a)^2}{12} = \frac{1}{12} = 0.08333\dots$:
# In[189]:
shape = (400, 400)
image = ForthExample.float_samples(shape)
np.mean(image), np.var(image)
# This Python hand-written Mersenne twister is of course slower than the previous PRNG defined above (combined Multiple Recursive Generator, simple Multiple Recursive Generator, and the simple Linear Recurrent Generator):
# In[190]:
get_ipython().run_line_magic('timeit', 'SecondExample.float_samples(shape)')
get_ipython().run_line_magic('timeit', 'ThirdExample.float_samples(shape)')
get_ipython().run_line_magic('timeit', 'MRG32k3a.float_samples(shape)')
get_ipython().run_line_magic('timeit', 'ForthExample.float_samples(shape)')
# That's not too bad, for $400 \times 400 = 160000$ samples, but obviously it is incredibly slower than the optimized PRNG found in the [`numpy.random`](https://docs.scipy.org/doc/numpy/reference/routines.random.html) package.
# In[191]:
get_ipython().run_line_magic('timeit', 'numpy.random.random_sample(shape)')
# A good surprise is that this implementation Mersenne appears faster than the combined MRG of order $k = 3$ (i.e., `MRG32k3a`).
# In[192]:
showimage(image)
# In[193]:
plotHistogram(ForthExample, 1000000, 200)
# ----
# ## Conclusion
# Well, that's it, I just wanted to implement a few Pseudo-Random Number Generators, and compare them.
#
# I should finish the job:
# - implement a test for "randomness", and check the various PRNG I implemented against it,
# - use these various `rand()` functions (uniform in $[0,1)$) to generate other distributions.
# ----
# # Generating samples from other distributions
# So far, I implemented some PRNG, which essentially give a function `rand()` to produce float number uniformly sampled from $[0, 1)$.
#
# Let use it to generate samples from other distributions.
# In[194]:
def newrand():
"""Create a new random function rand()."""
mersenne = MersenneTwister()
rand = mersenne.rand
return rand
rand = newrand()
# We will need an easy way to visualize the repartition of samples for the distributions defined below.
# In[195]:
def plotHistogramOfDistribution(distr, nb=10000, bins=200):
numbers = [ distr() for _ in range(nb) ]
plt.figure(figsize=(14, 3))
plt.hist(numbers, bins=bins, normed=True, alpha=0.8)
plt.xlabel("Random numbers from function %s" % distr.__name__)
plt.ylabel("Mass repartition")
plt.title("Repartition of ${}$ random numbers".format(nb))
plt.show()
# ----
# ## Bernoulli distribution
# It is the simplest example, $X \in \{0, 1\}$, $\mathbb{P}(X = 0) = p$ and $\mathbb{P}(X = 1) = 1 - p$ for some parameter $p \in [0,1]$.
# In[196]:
def bernoulli(p=0.5):
"""Get one random sample X ~ Bern(p)."""
assert 0 <= p <= 1, "Error: the parameter p for a bernoulli distribution has to be in [0, 1]."
return int(rand() < p)
# In[197]:
print([ bernoulli(0.5) for _ in range(20) ])
print([ bernoulli(0.1) for _ in range(20) ]) # lots of 0
print([ bernoulli(0.9) for _ in range(20) ]) # lots of 1
# We can quickly check that the frequency of $1$ in a large sample of size $n$ will converge to $p$ as $n \to +\infty$:
# In[198]:
def delta_p_phat_bernoulli(p, nb=100000):
samples = [ bernoulli(p) for _ in range(nb) ]
return np.abs(np.mean(samples) - p)
# In[199]:
print(delta_p_phat_bernoulli(0.5))
print(delta_p_phat_bernoulli(0.1))
print(delta_p_phat_bernoulli(0.9))
# That's less than $1\%$ of absolute error, alright.
# In[200]:
plotHistogramOfDistribution(bernoulli)
# ----
# ## Uniform distribution on $[a, b)$, for floats and integers
# This one is obvious too:
# In[201]:
def uniform(a, b):
"""Uniform float number in [a, b)."""
assert a < b, "Error: for uniform(a, b), a must be < b."
return a + (b - a) * rand()
# In[202]:
def uniform_3_5():
return uniform(3, 5)
plotHistogramOfDistribution(uniform_3_5, 100000)
# For integers, it is extremely similar:
# In[203]:
def randint(a, b):
"""Uniform float number in [a, b)."""
assert a < b, "Error: for randint(a, b), a must be < b."
assert isinstance(a, int), "Error: for randint(a, b), a must be an integer."
assert isinstance(b, int), "Error: for randint(a, b), a must be an integer."
return int(a + (b - a) * rand())
# In[204]:
def uniform_int_18_42():
return randint(18, 42)
plotHistogramOfDistribution(uniform_int_18_42, 100000)
# ----
# ## Exponential distribution
# If $X \sim \mathrm{Exp}(\lambda)$, $F(x) = 1 - \mathrm{e}^{- \lambda x}$, and so $F^{-1}(u) = -\frac1{\lambda} \ln(1 - u)$.
# The inversion method is easy to apply here:
# In[205]:
from math import log
def exponential(lmbda=1):
"""Get one random sample X ~ Exp(lmbda)."""
assert lmbda > 0, "Error: the parameter lmbda for exponential(lmbda) must be > 0."
u = rand() # 1 - u ~ U([0, 1]), so u and 1 - u follow the same distribution
return -(1.0 / lmbda) * log(u)
# The resulting histogram has the shape we know as "exponential":
# In[206]:
plotHistogramOfDistribution(exponential)
# We can compare its efficiency with [`numpy.random.exponential()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.exponential.html#numpy.random.exponential), and of course it is slower.
# In[207]:
get_ipython().run_line_magic('timeit', '[ exponential(1.) for _ in range(10000) ]')