On Wed, Sep 16, 2015 at 11:22 PM, Henrik Nergaard <[email protected]> wrote:
> The method #nextValue actually calculates the next value the seed should be,
> the current value can be accessed by sending #seed.
>
> I do agree that #nextValue might not be the clearest method name for its
> use; perhaps #nextSeed would be a better name?

Yes. Thats better again.  Now its a private method, so there should be
problem changing it ;) ??anyone


Continuing on another Random topic related to..
https://pharo.fogbugz.com/default.asp?16577

I notice that Collection>>atRandom is protected by a mutex but
Collection>>atRandom: is not.  This makes me believe the protection is
for the Random generator and not for the actual picking of the element
from the collection.  So it seems that #atRandom holds the mutex too
long - for both random generation and element picking.

Thus I wonder if rather than copying the existing pattern of
Collection>>atRandom to GlobalSharedRandom>>generateFor:  it might be
better to make a more generic SharedRandom as follows...

"Old calls to #next changed to private #nextValue"

Random>>nextValue
    | lo hi aLoRHi answer |
    hi := (seed quo: q) asFloat.
    lo := seed - (hi * q).  " = seed rem: q"
    aLoRHi := (a * lo) - (r * hi).
    seed := (aLoRHi > 0.0)
         ifTrue:  [aLoRHi]
         ifFalse: [aLoRHi + m].
    ^ seed / m  "this line moved here from old #next"

Random>>next
     ^ self nextValue

Random>>next: anInteger into: anArray
    1 to: anInteger do: [:index | anArray at: index put: self nextValue].
    ^ anArray

Random>>nextInt: anInteger
    anInteger strictlyPositive ifFalse: [ self error: 'Range must be
positive' ].
    anInteger asFloat isInfinite
        ifTrue: [^(self nextValue asFraction * anInteger) truncated + 1].
    ^ (self nextValue * anInteger) truncated + 1


"SharedRandom protects all calls to private #nextValue"

Random subclass: SharedRandom
     instanceVariableNames: 'mutex'

SharedRandom>>initialize
     mutex := Semaphore forMutualExclusion.

SharedRandom>>next
    ^ mutex critical: [ self nextValue ]

SharedRandom>>next: anInteger into: anArray
    ^ mutex critical: [ super next: anInteger into: anArray ].

SharedRandom>>nextInt: anInteger
    ^ mutex critical: [ nextInt: anInteger ].


Then...

Object subclass: GlobalSharedRandom
    classVariables: 'sharedRandom'

GlobalSharedRandom class>>initialize
    sharedRandom := SharedRandom new.

GlobalSharedRandom class>>generator
    ^ sharedRandom


And finally...

Collection>>atRandom
    ^ self randomAt: GlobalSharedRandom generator.


What do you think?
cheers, Ben

Reply via email to