Browse code

Added a second PRNG with longer period

Andrew Alderwick authored on 25/08/2021 20:59:30
Showing 1 changed files
... ...
@@ -1,7 +1,6 @@
1
-( pseudo-random number generator )
2
-
3
-( based on 16-bit xorshift algorithm discussed on
4
-  http://www.retroprogramming.com/2017/07/xorshift-pseudorandom-numbers-in-z80.html )
1
+( pseudo-random number generator,
2
+  based on two 16-bit xorshift algorithms by George Marsaglia
3
+  http://www.jstatsoft.org/v08/i14/paper )
5 4
 
6 5
 ( devices )
7 6
 
... ...
@@ -18,17 +17,22 @@
18 17
 |0100 ( -> )
19 18
 	( init )
20 19
 	;on-frame .Screen/vector DEO2
20
+
21 21
 	( seed prng (must be nonzero) )
22
-	.DateTime/month DEI .DateTime/day DEI
23
-	#00 .DateTime/second #a0 SFT2 EOR2
24
-	#00 .DateTime/minute #40 SFT2 EOR2
25
-	.DateTime/hour EOR
22
+	#00 .DateTime/second DEI
23
+	#00 .DateTime/minute DEI #60 SFT2 EOR2
24
+	#00 .DateTime/hour   DEI #c0 SFT2 EOR2 ;prng2/x STA2
25
+	#00 .DateTime/hour   DEI #04 SFT2
26
+	#00 .DateTime/day    DEI #10 SFT2 EOR2
27
+	#00 .DateTime/month  DEI #60 SFT2 EOR2
28
+	#00 .DateTime/year   DEI #a0 SFT2 EOR2 ;prng2/y STA2
29
+	;prng2/x LDA2 ;prng2/y LDA2 EOR2
26 30
 	ORAk ,&non-zero JCN INC2 &non-zero
27 31
 	;prng/seed STA2
28 32
 
29 33
 	( theme )
30
-	#0fe5 .System/r DEO2 
31
-	#0fc5 .System/g DEO2 
34
+	#0fe5 .System/r DEO2
35
+	#0fc5 .System/g DEO2
32 36
 	#0f25 .System/b DEO2
33 37
 	BRK
34 38
 
... ...
@@ -42,16 +46,17 @@
42 46
 	BRK
43 47
 
44 48
 @draw-pixel
45
-	,prng JSR
49
+	,prng2 JSR
46 50
 	#00 SWP .Screen/x DEO2
47 51
 	#00 SWP .Screen/y DEO2
48 52
 	#01 .Screen/pixel DEO
49 53
 	JMP2r
50 54
 
51 55
 @prng ( -- number* )
52
-	( returns the next number in the 65,535-long sequence,
56
+	( returns the next number in a 65,535-long sequence,
53 57
 	  which is never zero but every other 16-bit number
54 58
 	  appears once before the sequence repeats )
59
+	( http://www.retroprogramming.com/2017/07/ xorshift-pseudorandom-numbers-in-z80.html )
55 60
 	,&seed LDR2
56 61
 	DUP2 #70 SFT2 EOR2
57 62
 	DUP2 #09 SFT2 EOR2
... ...
@@ -61,3 +66,17 @@
61 66
 
62 67
 	&seed $2
63 68
 
69
+@prng2 ( -- number* )
70
+	( returns the next number in a (2^32-1)-long sequence )
71
+	( http://b2d-f9r.blogspot.com/2010/08/ 16-bit-xorshift-rng-now-with-more.html )
72
+	,&x LDR2
73
+	DUP2 #50 SFT2 EOR2
74
+	DUP2 #03 SFT2 EOR2
75
+	,&y LDR2 DUP2 ,&x STR2
76
+	DUP2 #01 SFT2 EOR2 EOR2
77
+	,&y STR2k POP
78
+	JMP2r
79
+
80
+	&x $2
81
+	&y $2
82
+