Z80 Routines:Math:Random

From WikiTI
Revision as of 23:29, 28 March 2007 by Jim e (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Ion Random

This is based off the tried and true pseudorandom number generator featured in Ion by Joe Wingbermuehle

;-----> Generate a random number
; ouput a=answer 0<=a<=255
; all registers are preserved except: af
        push    hl
        push    de
        ld      hl,(randData)
        ld      a,r
        ld      d,a
        ld      e,(hl)
        add     hl,de
        add     a,l
        xor     h
        ld      (randData),hl
        pop     de
        pop     hl

randData here must be a 2 byte seed located in ram. While this is a fast generator, it's generally not considered very good in terms of randomness.

Linear Feedback Shift Register

This particular prng is based on Linear feedback shift register. It uses a 64bit seed and generates 8 new bits at every call. LFSRSeed must be an 8 byte seed located in ram.

;James Montelongo
;optimized by Spencer Putt
; a = 8 bit random number
        ld hl,LFSRSeed+4
        ld e,(hl)
        inc hl
        ld d,(hl)
        inc hl
        ld c,(hl)
        inc hl
        ld a,(hl)
        ld b,a
        rl e \ rl d
        rl c \ rla
        rl e \ rl d
        rl c \ rla
        rl e \ rl d
        rl c \ rla
        ld h,a
        rl e \ rl d
        rl c \ rla
        xor b
        rl e \ rl d
        xor h
        xor c
        xor d
        ld hl,LFSRSeed+6
        ld de,LFSRSeed+7
        ld bc,7
        ld (LFSRSeed),a

While this may produces better numbers, it is slower, larger and requires a bigger seed than ionrandom. Assuming theres is a good seed to start, it should generate ~2^56 bytes before repeating. However if there is not a good seed(0 for example), then the numbers created will not be adequate. Unlike Ionrandom and its use of the r register, starting with the same seed the same numbers will be generated. With Ionrandom the code running may have an impact on the number generated. This means this method requires more initialization.

You can initialize with TI-OS's seeds, stored at seed1 and seed2, both are ti-floats but will serve the purpose.