RandomParkMiller.st
author Claus Gittinger <cg@exept.de>
Tue, 02 Oct 2001 11:33:33 +0200
changeset 977 a7e2a422bfdb
child 998 5f66a2dd6b7d
permissions -rw-r--r--
initial checkin

"{ Package: 'stx:libbasic2' }"

Object subclass:#RandomParkMiller
	instanceVariableNames:'seed'
	classVariableNames:'PMa PMm PMmu1 PMq PMr'
	poolDictionaries:''
	category:'Magnitude-Numbers'
!

!RandomParkMiller class methodsFor:'documentation'!

documentation
"
    NO WARRANTY

    Another pseudo-random number generator

    |r|

    r := self new.
    (1 to:10) collect:[:i | r next]

    -> should be
        #(
            0.1492432697 
            0.3316330217 
            0.7561964480 
            0.3937015400 
            0.9417831814 
            0.5499291939 
            0.6599625962 
            0.9913545591 
            0.6960744326 
            0.9229878997
        #)
"
! !

!RandomParkMiller class methodsFor:'initialization'!

initialize
    PMa := 16807.
    PMm := 2147483647.    " magic constant = 16807 "
    PMq := 127773.        " magic constant = 2147483647 "
    PMr := 2836.          " quotient (m quo: a) = 44488 "
    PMmu1 := 4.65661E-10  " remainder (m \\ a). = 2836 "
! !

!RandomParkMiller class methodsFor:'instance creation'!

new
    self initialize.
    ^ super new initialize
! !

!RandomParkMiller methodsFor:'accessing-reading'!

next
    " This method generates random instances of Float in the interval 0.0 to 1.0 "

    seed := self nextInteger.
    ^ seed * PMmu1
!

nextInteger
    " This method generates random instances of Integer in the interval 0 to 16r7FFFFFFF. "

    seed := self peekInteger.
    ^ seed
! !

!RandomParkMiller methodsFor:'initialization'!

initialize
    " Set a reasonable Park-Miller starting seed "

    seed := 2345678901
!

seed:anInteger 
    seed := anInteger
! !

!RandomParkMiller methodsFor:'private'!

peek
    " This method answers the next random number that will be generated as a Float in the range [0..1). It answers the same value for all successive message sends. "

    ^ self peekInteger * PMmu1
!

peekInteger
    " This method generates random instances of Integer in the interval 0 to 16r7FFFFFFF. This method does NOT update the seed; repeated sends answer the same value. The algorithm is described in detail in 'Random Number Generators: Good Ones Are Hard to Find' by Stephen K. Park and Keith W. Miller, (Comm. Asso. Comp. Mach., 31(10):1192--1201, 1988). "

    |lo hi aLoRHi answer|

    hi := seed quo:PMq.
    lo := seed rem:PMq.
    aLoRHi := (PMa * lo) - (PMr * hi).
    (aLoRHi > 0) ifTrue:[ ^ aLoRHi ].
    ^ aLoRHi + PMm
! !

!RandomParkMiller class methodsFor:'documentation'!

version
    ^ '$Header: /cvs/stx/stx/libbasic2/RandomParkMiller.st,v 1.1 2001-10-02 09:33:33 cg Exp $'
! !
RandomParkMiller initialize!