help-smalltalk
[Top][All Lists]

## Re: [Help-smalltalk] help with random numbers?

 From: Ralph Boland Subject: Re: [Help-smalltalk] help with random numbers? Date: Sat, 31 Jul 2010 12:18:24 -0600

```Eons ago I generated a bug report on Random numbers.
If my memory is correct as part of the report I pointed out that
(Random>nextValue) asInteger generates a LargeInteger 50% of the time.
Since I need random small integers I use the following code:

nextSmallIntegerUpdatingSeed
seed := self nextValue.
^seed asInteger // 2.

Regards,

Ralph Boland

Original post:

Eval [
| n k r |
r := Random new.
n := 100000.
k := 500.
(1 to: n) select: [:x |
(r between: 1 and: n) <= k
ifTrue: [ n := n - 1. k := k - 1] ifFalse: [n := n - 1];
yourself ]
]

and I noticed that it spends 75% of the time generating random
numbers.  Bytecode-wise it's not bad (30 bytecodes per random number),
but floating point causes a large number of garbage collections.
Anybody wants to give a shot at reimplementing Random with a good,
fast rng? Remember that on 32-bit machines SmallIntegers are only from
-2^30 to 2^30-1.

FWIW, here is a "more optimized" version of the above:

o := OrderedCollection new.
1 to: n do: [:x |
((r between: 0 and: (n := n - 1)) < k
ifTrue: [o add: x. k := k - 1]) notNil ]

Either program is a good benchmark for your rng.

Paolo

```