eXept Software AG Logo

Smalltalk/X Webserver

Documentation of class 'Random':

Home

Documentation
www.exept.de
Everywhere
for:
[back]

Class: Random


Inheritance:

   Object
   |
   +--Stream
      |
      +--Random
         |
         +--RandomGNUSmalltalk
         |
         +--RandomGenerator

Package:
stx:libbasic2
Category:
Magnitude-Numbers-Random
Version:
rev: 1.83 date: 2023/06/04 13:56:30
user: cg
file: Random.st directory: libbasic2
module: stx stc-classLibrary: libbasic2

Description:


A facade to the actual RandomGenerator.
In previous versions, Random was a very bad fallback random generator,
with an included warning, to not use it.

Now this old generator was renamed to RandomGNUSmalltalk,
and the default generator used is the one provided by the much
better RandomGenerator class.

    Random new next:10   

copyright

COPYRIGHT (c) 1989 by Claus Gittinger All Rights Reserved This software is furnished under a license and may be used only in accordance with the terms of that license and with the inclusion of the above copyright notice. This software may not be provided or otherwise made available to, or used by, any other person. No title to or ownership of the software is hereby transferred.

Class protocol:

instance creation
o  new
return a new random generator.
Here, this instance creation message is forwarded to the standardGenerator

Usage example(s):

     Random new

o  random
return a new random generator.
Defined here for compatibility with StreamCipher

o  seed: seedValue
return a new random generator with initial seed.
Here, this instance creation message is forwarded to the standardGenerator

o  sharedGenerator
return a shared random generator.

o  standard
return the 'standard' generator

o  standardGeneratorClass
return the class used for the 'standard' generator

random numbers
o  next: n
return the next n random numbers in the range 0..1
This method behaves like the corresponding instance method,
but allows generation of random numbers without
a need for an instance of Random to be kept around.
This uses a common, shared generator.

Usage example(s):

     Transcript showCR:(Random next:10).

o  next: n between: start and: stop
return n random numbers between start and stop.
This method behaves like the corresponding instance method,
but allows generation of random numbers without
a need for an instance of Random to be kept around.
This uses a common, shared generator.

Usage example(s):

     Transcript showCR:(Random next:10 between:1 and:100).

o  nextBetween: start and: stop
return a random number between start and stop.
This method behaves like the corresponding instance method,
but allows generation of random numbers without
a need for an instance of Random to be kept around.
This uses a common, shared generator.

Usage example(s):

     Transcript showCR:(Random nextBetween:1 and:100).
     Transcript showCR:(Random nextBetween:1 and:100).
     Transcript showCR:(Random nextBetween:1 and:100).
     Transcript showCR:(Random nextBetween:1 and:100).

o  nextBoolean
return a boolean random.
This method behaves like the corresponding instance method,
but allows generation of random numbers without
a need for an instance of Random to be kept around.
This uses a common, shared generator.

Usage example(s):

     Transcript showCR:(Random nextBoolean).
     Transcript showCR:(Random nextBoolean).
     Transcript showCR:(Random nextBoolean).
     Transcript showCR:(Random nextBoolean).

o  nextBytes: nBytes
return nBytes random bytes
This method behaves like the corresponding instance method,
but allows generation of random numbers without
a need for an instance of Random to be kept around.
This uses a common, shared generator.

Usage example(s):

     Transcript showCR:(Random nextBytes:10).
     Transcript showCR:(Random nextBytes:20).
     Transcript showCR:(Random nextBytes:1).

o  nextInteger
return an integral random number.
This method behaves like the corresponding instance method,
but allows generation of random numbers without
a need for an instance of Random to be kept around.
This uses a common, shared generator.

Usage example(s):

     Transcript showCR:(Random nextInteger).
     Transcript showCR:(Random nextInteger).
     Transcript showCR:(Random nextInteger).
     Transcript showCR:(Random nextInteger).

o  nextIntegerBetween: start and: stop
return an integral random number between start and stop.
This method behaves like the corresponding instance method,
but allows generation of random numbers without
a need for an instance of Random to be kept around.
This uses a common, shared generator.

Usage example(s):

     Transcript showCR:(Random nextIntegerBetween:1 and:10).
     Transcript showCR:(Random nextIntegerBetween:1 and:10).
     Transcript showCR:(Random nextIntegerBetween:1 and:10).
     Transcript showCR:(Random nextIntegerBetween:1 and:10).

o  nextLettersOrDigits: count
get the next count printable letters or digits [0-9A-Za-z].

Usage example(s):

     Transcript showCR:(Random nextLettersOrDigits:10).
     Transcript showCR:(Random nextLettersOrDigits:10).
     Transcript showCR:(Random nextLettersOrDigits:10).
     Transcript showCR:(Random nextLettersOrDigits:10).

reading
o  next
return the next random number in the range 0..1
This method behaves like the corresponding instance method,
but allows generation of random numbers without
a need for an instance of Random to be kept around.
This uses a common, shared generator.

Usage example(s):

     Transcript showCR:(Random next).
     Transcript showCR:(Random next).
     Transcript showCR:(Random next).
     Transcript showCR:(Random next).

seeding
o  randomSeed
return a number useful for seeding.
This takes the current processor's time, plus the processor's process id,
plus some value depending on the memory allocation state,
plus a random salt, and shuffles those bits around.
The entropy returned should be reasonable enough for a good seed of a good rnd
generator. However, keep in mind, that it only has a limited number of entropy bits
(in the order of 32).
But it should be much better than what is commonly used in older
programs (current time) or even a constant.

Usage example(s):

     10 timesRepeat:[Transcript showCR:self randomSeed].
     10 timesRepeat:[Transcript showCR:(self randomSeed bitAnd:16rFFFF)].
     self randomSeed bitAnd:16rFFFFFFFF

testing
o  bucketTest: randy
A quick-and-dirty bucket test. Prints nbuckets values on the Transcript.
Each should be 'near' the value of ntries. Any run with any value 'far' from ntries
indicates something is very wrong. Each run generates different values.
For a slightly better test, try values of nbuckets of 200-1000 or more;
go get coffee.
This is a poor test; see Knuth.
Some 'OK' runs:
1000 1023 998 969 997 1018 1030 1019 1054 985 1003
1011 987 982 980 982 974 968 1044 976
1029 1011 1025 1016 997 1019 991 954 968 999 991
978 1035 995 988 1038 1009 988 993 976

Usage example(s):

Execute this:  
         self bucketTest: self new
         self bucketTest: RandomGenerator new

o  chiSquareTest
Chi-Squared Test - from R.Sedgewick's 1st ed. of 'Algorithms',
o N = number of samples
o r = range of random numners is [0,r) -- condition: N >= 10r.
o Random number generator 'passes' if chisquare value is very close to r
o Repeat test several times, since it may be *wrong* 1 out of 10 trials.

Usage example(s):

     self chiSquareTest 
     RandomGenerator chiSquareTest

Usage example(s):

    |fail|
    fail := 0.
    10 timesRepeat:[
        |testResult|
        testResult := RandomGenerator chiSquareTest.
        (100 - testResult) abs > 20 ifTrue:[Transcript showCR:testResult. fail := fail + 1].
    ].
    fail > 1 ifTrue:[self error:'test failed'].


Instance protocol:

Compatibility-Squeak
o  nextFrom: lowerBound to: upperBound
( an extension from the stx:libcompat package )
return a random integer in the given range

Usage example(s):

     Random new nextFrom:0.5 to:3.5 

o  nextInt: upperBound
( an extension from the stx:libcompat package )
Answer a random integer in the interval [1, anInteger].

Usage example(s):

     Random new nextInt:10

o  nextIntFrom: lowerBound to: upperBound
( an extension from the stx:libcompat package )
return a random integer in the given range

Usage example(s):

     Random new nextIntFrom:5 to:10

o  nextInteger: upperBound
( an extension from the stx:libcompat package )
Answer a random integer in the interval [1, anInteger].

o  seed: anInteger

accessing-reading
o  next: count
return the next count random numbers in the range ]0..1[

Usage example(s):

     (RandomGenerator new) next:10

o  next: count between: min and: max
return the next count random numbers in min..max

Usage example(s):

     (RandomGenerator new) next:10 between:0 and:100 

o  next: count integerBetween: min and: max
return the next count random integers in min..max

Usage example(s):

     (RandomGenerator new) next:100 integerBetween:0 and:100

o  nextBetween: start and: stop
return a random number in the range ]start..stop[.
claus: the original GNU version has a bug in returning values
from the interval [start .. stop+1]

Usage example(s):

     |r|
     r := Random new.
     Transcript showCR:(r nextBetween:1 and:10).
     Transcript showCR:(r nextBetween:1 and:10).
     Transcript showCR:(r nextBetween:1 and:10).
     Transcript showCR:(r nextBetween:1 and:10).

o  nextBoolean
return true or false by random

Usage example(s):

    |r|
     r := Random new.
     Transcript showCR:r nextBoolean.
     Transcript showCR:r nextBoolean.
     Transcript showCR:r nextBoolean.
     Transcript showCR:r nextBoolean.

Usage example(s):

     |r bag|
     r := Random new.
     bag := Bag new.
     1000000 timesRepeat:[
         bag add:(r nextBoolean).
     ].
     Transcript showCR:bag contents

o  nextByte
return the next integral random number byte in the range 0 .. 16rFF

Usage example(s):

     |r|
     r := self new.
     Transcript showCR:r nextByte.
     Transcript showCR:r nextByte.
     Transcript showCR:r nextByte.
     Transcript showCR:r nextByte.

o  nextBytes: count
return count random bytes (0..16rFF each)

Usage example(s):

     Transcript showCR:(RandomGenerator new nextBytes:20).  

o  nextBytesNonZero: count
return count random bytes, none of which is zero (i.e. 1..16rFF each)

Usage example(s):

     Transcript showCR:(Random new nextBytesNonZero:20).

o  nextCharacters: count
get the next cnt printable characters.
We answer printable characters in the ascii range (codepoints 32 - 126)

Usage example(s):

      RandomGenerator new nextCharacters:8 

o  nextHumanReadableStringOfSize: length
->

Usage example(s):

     (1 to:1000) collect:[:n | Random new nextHumanReadableStringOfSize:6 ] as:Bag   

o  nextInteger
return the next integral random number,
in the range 0 .. self maxInteger

** This method must be redefined in concrete classes (subclassResponsibility) **

o  nextIntegerBetween: startIn and: stopIn
return an integral random number in [start..stop] (inclusive)

Usage example(s):

shows pair-combination counts

     |r v prev this counts|

     v := TextView new .
     v extent:500@250.
     v list:#('xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx'
              'xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx'
              'xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx'
              'xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx'
              'xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx'
              'xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx'
              'xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx'
              'xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx'
              'xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx'
              'xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx').
     v openAndWaitUntilVisible.
     counts := (1 to:10) collect:[:row | Array new:10 withAll:0].

     r := self new.
     prev := r nextIntegerBetween:1 and:10.
     10000 timesRepeat:[
         100 timesRepeat:[
            this := r nextIntegerBetween:1 and:10.
            (counts at:this) at:prev put:((counts at:this) at:prev)+1.
         ].
         v list:(counts collect:[:row |
                    '%4d %4d %4d %4d %4d %4d %4d %4d %4d %4d'printf:row ]).
         prev := this.
     ].

Usage example(s):

     |r|
     r := self new.
     Transcript showCR:(r nextIntegerBetween:1 and:10).
     Transcript showCR:(r nextIntegerBetween:1 and:10).
     Transcript showCR:(r nextIntegerBetween:1 and:10).
     Transcript showCR:(r nextIntegerBetween:1 and:10).

Usage example(s):

     |r|
     r := self new.
     Transcript showCR:(r nextIntegerBetween:1 and:1000000).
     Transcript showCR:(r nextIntegerBetween:1 and:1000000).
     Transcript showCR:(r nextIntegerBetween:1 and:1000000).
     Transcript showCR:(r nextIntegerBetween:1 and:1000000).

Usage example(s):

     |r bag|
     r := self new.
     bag := Bag new.
     1000000 timesRepeat:[
         bag add:(r nextIntegerBetween:-1 and:1).
     ].
     Transcript showCR:bag sortedCounts.

Usage example(s):

     |r bag|
     r := self new.
     bag := Bag new.
     1000000 timesRepeat:[
         bag add:(r nextIntegerBetween:1 and:3).
     ].
     Transcript showCR:bag sortedCounts.
     TestCase assert:(bag standardDeviation closeTo:(((3 squared - 1)/12) sqrt)).

Usage example(s):

     |r bag|
     r := self new.
     bag := Bag new.
     1000000 timesRepeat:[
         bag add:(r nextIntegerBetween:1 and:32).
     ].
     Transcript showCR:bag sortedCounts.
     TestCase assert:(bag standardDeviation closeTo:(((32 squared - 1)/12) sqrt)).

Usage example(s):

     |r bag|
     r := self new.
     bag := Bag new.
     100000000 timesRepeat:[
         bag add:(r nextIntegerBetween:1 and:400000).
     ].
     Transcript showCR:bag sortedCounts.
     TestCase assert:(bag standardDeviation closeTo:(((400000 squared - 1)/12) sqrt)).

Usage example(s):

     |r|
     
     r := self new.
     100000000 timesRepeat:[
         self assert:((r nextIntegerBetween:1 and:3) between:1 and:3).
     ].

o  nextLettersOrDigits: count
get a random string consisting of count printable letters or digits [0-9A-Za-z].

Usage example(s):

      Random new nextLettersOrDigits:40 

blocked methods
o  contents
blocked from use - contents makes no sense for random generators

o  nextPut: value
blocked from use - it makes no sense for randoms

initialization
o  initialize
(comment from inherited method)
just to ignore initialize to objects which do not need it

private
o  addEntropy: entropyBytes
add some entropy - ignored here

o  seed

o  setSeed
set the initial seed value based on the current time and processId.
These numbers implement a maximum period generator which passes
the spectral test for randomness for dimensions 2 3 4 5 6 and
the product does not overflow 2 raisedTo:29.

Use both time and processId for seed, to make different processes
return different Random numbers

o  setSeed: seedValue
set the initial seed and intialize the PRNG parameters.

** This method must be redefined in concrete classes (subclassResponsibility) **

o  step
compute the next random integer

** This method must be redefined in concrete classes (subclassResponsibility) **

reading
o  next
return the next random number in the range ]0..1[

** This method must be redefined in concrete classes (subclassResponsibility) **

testing
o  atEnd
instances of Random can always give more numbers

o  isReadable

o  isWritable
return true, if writing is supported by the receiver.
Random Generators never are

o  maxInteger
the max value returned by self nextInteger

** This method must be redefined in concrete classes (subclassResponsibility) **


Examples:


    |rnd|

    rnd := Random new.
    10 timesRepeat:[
        Transcript showCR:(rnd next)
    ]
rolling a dice:
    |rnd|

    rnd := Random new.
    10 timesRepeat:[
        Transcript showCR:(rnd nextIntegerBetween:1 and:6)
    ]


ST/X 7.7.0.0; WebServer 1.702 at 20f6060372b9.unknown:8081; Mon, 18 Nov 2024 06:45:51 GMT