The Trunk: Kernel-nice.902.mcz

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

The Trunk: Kernel-nice.902.mcz

commits-2
Nicolas Cellier uploaded a new version of Kernel to project The Trunk:
http://source.squeak.org/trunk/Kernel-nice.902.mcz

==================== Summary ====================

Name: Kernel-nice.902
Author: nice
Time: 13 February 2015, 11:39:01.472 pm
UUID: 056a5cce-fafc-4bd8-a6e2-e85f9114b48a
Ancestors: Kernel-eem.901

Generate large random integers a bit more fairly.

The idea is just to generate a large bit sequence by gathering enough pseudo random chunks.

Note that this implementation knows that Random cannot fairly generate 32 bits, so limit itself to 24 bits chunk.

It knows two much about Random already and should better delegate, but since we have a single Pseudo Random Number Generator so far, don't bother too much.

=============== Diff against Kernel-eem.901 ===============

Item was added:
+ ----- Method: LargePositiveInteger>>atRandom: (in category 'truncation and round off') -----
+ atRandom: aGenerator
+ "Answer a random integer from 1 to self picked from aGenerator."
+
+ | chunkByteLength chunkBitLength chunkCount chunkMax bigRandomInteger |
+ chunkByteLength := 3.
+ chunkBitLength := chunkByteLength * 8.
+ chunkCount :=
+ self highBitOfMagnitude + chunkBitLength - 1 // chunkBitLength "self would fit in that many chunks..."
+ + 2. "and two more chunks (48 bits) so as to have a pretty fair distribution"
+ chunkMax := 1<<chunkBitLength-1.
+
+ "fill a big random integer by chunks of 3 bytes (24 bits)"
+ bigRandomInteger := self class new: chunkCount*chunkByteLength neg: false.
+ 0 to: chunkCount*chunkByteLength - 1 by: chunkByteLength do: [:byteOffset |
+ | chunk |
+ chunk := (aGenerator nextInt: chunkMax) - 1.
+ 1 to: chunkByteLength do: [:byteIndex |
+ bigRandomInteger digitAt: byteOffset + byteIndex put: (chunk digitAt: byteIndex)]].
+
+ ^self * bigRandomInteger >> (chunkCount * chunkBitLength) + 1!