Posted: 04:16am 05 Aug 2020 |
Copy link to clipboard |
 Print this post |
|
Partly due to my own curiosity and partly due to several requests here on TBS, I decided to play with LFSR pseudo-random number generators.
The following function implements a 16-Bit LFSR "random" number generator as used on the 8-bit computers of the '80's It will generate a repeating sequence of 65535 numbers with a fairly good random distribution.
The sample program will plot the distribution of the numbers. If you watch carefully, you will see the plot "flat-line" every 65536 calls and the sequence then repeats.
Warning: This function does not produce truly random numbers! Do not use for any kind of security purposes. The algorithm is simple and common. The sequence can be easily determined! The Rnd() function built in to MMBasic produces better random numbers and does it 15X faster. This function is for nostalgic purposes and those rare cases when a repeatable sequence of numbers may be needed.
I chose to use the syntax from the C64 for the parameter:
'16 Bit Galois LFSR Pseudo Random Number Generator 'Returns pseudo random numbers in range of 0(inclusive) to 1.0(exclusive) 'Par = <positive number> Return next number in sequence 'Par = <0> Seed from system Timer 'Par = <negative number> use Par as the seed 'Note:Calling Rand(0) repeatedly will not give a good distribution - ' due to low resolution of the system timer
'Random number distribution Histogram
Mode 1,8
C = RGB(white) DIM A%(800)
CLS
'R = Rand(-1)'Seed the LFSR with "1" R = Rand(0) 'Seed the LFSR from the system Timer
Do R = 800 * Rand(1) 'Get the next number in the sequence A%(R) = A%(R) + 1 Pixel R,600 - A%(R),C Loop While A%(R) <= 600
'16 Bit Galois LFSR Pseudo Random Number Generator 'Returns pseudo random numbers in range of 0(inclusive) to 1.0(exclusive) 'Par = <positive number> Return next number in sequence 'Par = <0> Seed from system Timer 'Par = <negative number> use Par as the seed 'Note:Calling Rand(0) repeatedly will not give a good distribution - ' due to low resolution of the system timer Function Rand(Par) STATIC LFSR% = &hAAAA LOCAL LSB%
If Par = 0 Then LFSR% = Timer Mod &hFFFF ElseIf Par < 0 Then LFSR% = ABS(Par) Mod &hFFFF EndIf LSB% = LFSR% AND 1 LFSR% = LFSR% >> 1 If LSB% Then LFSR% = LFSR% XOR &hB400 Rand = (LFSR% - 1) / &hFFFF End Function
-Carl |