Home Segments Index Top Previous Next

527: Practice

Smalltalk Express does not come equipped with a random-number generator, but you can implement a simple random-number generator with the following, which is adapted from Smalltalk-80: The Language, by Adele Goldberg and David Robson (Addison-Wesley, 1989); it, in turn, is based on Lehmer's linear congruential method, described in The Art of Computer Programming: Fundamental Algorithms, Volume 1, by Donald Knuth (Addison-Wesley, 1968).

The random numbers vary uniformly from 0.0, exclusively, to 1.0 exclusively. The new: method takes an integer argument that provides a starting point for the generation of random numbers, so that you are not stuck with the same sequence of random numbers each time that you create an instance of the Random class. The bitAnd: method peforms bit-by-bit logic on integers:

Random class definition 
Object subclass: #Random 
  instanceVariableNames: 'seed' 
  classVariableNames: '' 
  poolDictionaries: '' 
Random method definition • class 
new: arg ^ super new initialize: arg. 
Random method definition • instance 
initialize: x seed := x. 
Random method definition • instance 
next 
  | handle | 
  [seed := 13849 + (27181 * seed) bitAnd: 65535. 
   handle := seed / 65536.0. 
   handle = 0] 
    whileTrue: []. 
  ^ handle. 

Now, using an instance of the Random class assigned to Generator, a global variable, you define a method, deliveryInterval that produces random numbers distributed between 0.75 and 1.25.