[NCLUG] Python v.s. Ruby, and PRNGs

Stephen Warren swarren at wwwdotorg.org
Thu Apr 10 10:40:37 MDT 2008


On Thu, April 10, 2008 9:46 am, Stephen Warren wrote:
> On Wed, April 9, 2008 11:15 pm, Sean Reifschneider wrote:
>> D1=`od --read-bytes=1 -t u1 /dev/random | head -1 | sed 's/.* //'`
>> D1=$[(D1%6)+1]
>
> I think that'll introduce some slight bias in the results...
>
> The impact of this could be somewhat reduced by pulling 16-bit numbers
> from /dev/random, to reduce the proportion of the range that's a "partial
> die". Or, perhaps we could do the experiment with 8-sided dice, so mod 8.

According to the last post here:

http://www.unix.com/unix-dummies-questions-answers/34913-dev-urandom.html

The correct way to fix this is:

        bytes = self.f.read(2)
        value = (ord(bytes[0]) << 8) | ord(bytes[1])
        #roll = (value % 6) + 1
        roll = int((value * 6) / 65536) + 1

i.e. don't use modulus at all.

I get the following results from 1000 runs of 10000 dice rolls using
/dev/urandom on my probably-not-that-random machine:

Min:   1.86
Mean:  9.97
Max:  29.92
SD:    4.32

So, also pretty variable, as expected, and pretty similar to the Python
results.

I wonder if /dev/random would be any different, but that's far too slow
for me.

(Anyway, this is probably getting a little off-topic. Let me know if
anyone doesn't want to hear about this any more...)




More information about the NCLUG mailing list