Posted By
IstvanV on 2011-02-28 08:28:46
| Re: Random for Real
This very simple code I have tried combines the use of a timer ($FF02) and a 15-bit LFSR:
. 2100 A5 D0 LDA $D0 . 2102 4D 02 FF EOR $FF02 . 2105 AA TAX . 2106 0A ASL . 2107 A5 D1 LDA $D1 . 2109 2A ROL . 210A 86 D1 STX $D1 . 210C 45 D1 EOR $D1 . 210E 85 D0 STA $D0 . 2110 60 RTS
. 2000 78 SEI . 2001 20 00 21 JSR $2100 . 2004 8D 19 FF STA $FF19 . 2007 4C 01 20 JMP $2001 It takes 25 cycles to execute without the JSR/RTS. The quality of the generated random numbers is probably not very good for serious uses, but this algorithm could be usable in a game or demo. Some quick tests I have done on it: a sample of 1000000 bytes of output could not be compressed with various compressors I have tried. With a 10000000 byte sample, 7-Zip was able to reduce the size by about 1.5%. On the larger sample, 3 of the 15 "DIEHARD" randomness tests (5, 6, 7) have obviously failed, while about 2 more looked not very good; however, it is not easy to write a routine consisting of only a few 6502 instructions that passes all of these tests. Of course, since it uses a timer, the intervals at which the code is called have an effect on the quality of the randomness: it could be worse, but also better (e.g. if not called in a simple loop, but rather more "randomly"). Replacing the EOR $FF02 with something else may also have a useful effect. The X register can be used for 16-bit output, but it is just an EOR between the previous value and the timer, so it is not as good as calling the routine twice.
|