From: ptkwt@...1.aracnet.com (Phil Tomson) Date: 2003-01-22T03:57:49+09:00 Subject: Re: redefining rand and srand In article , Park Heesob wrote: >Hi, > >"Phil Tomson" wrote in message >news:b0ivi80pgg@enews3.newsguy.com... >> In article , >> > >> >A couple of questions: >> >1) how good is Ruby's rand function (what's the quality of randomness)? >I >> >suspec that it is just the same as C's rand, so there won't be a >> >difference. >> >2) I'd like to plug in my own random number generator that would probably >> >produce higher-quality random numbers than the current rand does. I'm >> >pretty sure it should be doable and easy, like: >> > >> >module Kernel >> > def rand(max=0) >> > #do random number generation magic here >> > end >> >end >> > >> >> >> Here's what I did. At Robert Feldt's suggestion I used his RandomR >> package which uses the Mersenne Twister to generate random numbers (a much >> better method than whatever is built-in, I'm sure). I then redefined rand >> and srand like so: >> >> require 'random/mersenne_twister' >> module Kernel >> def rand(max=0) >> if not defined? @__rng >> @__rng=Random::MersenneTwister.new Time.now.to_i >> end >> @__rng.rand(max) >> end >> def srand(seed) >> @__rng=Random::MersenneTwister.new seed >> end >> end >> > >How about use native Ruby code instead of extension module? >The following is my rough translation from C code(mt19937ar.c) at >http://www.math.keio.ac.jp/~matumoto/emt.html C code is faster... I'm using this for a genetic algorithms class. 20 runs of 200 generations each on a 28bit chromosome is taking about 5 minutes right now as it is. If I use a pure Ruby RNG that's gonna get slower... However I'm going to experiment later with a RNG based on cellular automata that I don't think would be significantly slower in Ruby vs. C (the next-state calculations are just hash lookups). Thanks for the code, though. Phil -- "Or perhaps the truth is less interesting than the facts?" Amy Weiss (accusing theregister.co.uk of engaging in 'tabloid journalism') Senior VP, Communications Recording Industry Association of America