. .

st4u

ST 4U 294: Custom Seeds for Random Numbers in VA Smalltalk

October 10, 2012 10:10:58.628

Today's Smalltalk 4 You looks at customizing the seeds used in random number generation in VA Smalltalk. If you have trouble viewing it here in the browser, you can also navigate directly to YouTube. To watch now, click on the image below:

Seeds.

If you have trouble viewing that directly, you can click here to download the video directly. If you need the video in a Windows Media format, then download that here.

You can also watch it on YouTube:


Today we'll look at customizing the seeds used in random number generation by class EsRandom in VA Smalltalk. First, have a look at the #new method:


new

	"Use linear congruential generator, with a shuffling array.

	 Reference: Numerical Recipes in C, The Art of Scientific Computing
				Press et al., Cambridge University Press 1990, pp. 211, 212"

	| randomStream |
	randomStream := super new.
	randomStream
		seed2: Time millisecondClockValue asFloat;
		basicNext;
		shuffleArray: (Array new: randomStream shuffleSize).
	1 to: randomStream shuffleSize do: [ :index |
		randomStream shuffleArray at: index put: randomStream basicNext].

	randomStream seed1: randomStream seed2.

	^randomStream

Notice how the seeds are set? That's likely good enough for most uses, but if you wanted to customize, all you need to do is replace those seeds - maybe like the following:


	| randomStream |
	randomStream := EsRandom new.
	randomStream
		seed2: AbtTimestamp now asMicroseconds asFloat;
		basicNext;
		shuffleArray: (Array new: randomStream shuffleSize).
	1 to: randomStream shuffleSize do: [ :index |
		randomStream shuffleArray at: index put: randomStream basicNext].

	randomStream seed1: randomStream seed2.

	Transcript show: (randomStream nextInt: 100) printString.
	Transcript cr.
	Transcript show: (randomStream nextInt: 10) printString.
	Transcript cr

That will work fine - try it out for yourself. That's really all there is to it!

Need more help? There's a screencast for other topics like this which you may want to watch. Questions? Try the "Chat with James" Google gadget over in the sidebar.

Technorati Tags: , ,

Enclosures:
[st4u294-iPhone.m4v ( Size: 1906635 )]

posted by James Robertson

 Share Tweet This