Code to generate Gaussian (normally distributed) random numbers in Ruby -


what code generate distributed random numbers in ruby?

(note: answered own question, i'll wait few days before accepting see if has better answer.)

edit:

searching this, looked @ pages on resulting 2 searches:

+"normal distribution" ruby

and

+gaussian +random ruby

python's random.gauss() , boost's normal_distribution both use box-muller transform, should enough ruby too.

def gaussian(mean, stddev, rand)   theta = 2 * math::pi * rand.call   rho = math.sqrt(-2 * math.log(1 - rand.call))   scale = stddev * rho   x = mean + scale * math.cos(theta)   y = mean + scale * math.sin(theta)   return x, y end 

the method can wrapped in class returns samples 1 one.

class randomgaussian   def initialize(mean, stddev, rand_helper = lambda { kernel.rand })     @rand_helper = rand_helper     @mean = mean     @stddev = stddev     @valid = false     @next = 0   end    def rand     if @valid       @valid = false       return @next     else       @valid = true       x, y = self.class.gaussian(@mean, @stddev, @rand_helper)       @next = y       return x     end   end    private   def self.gaussian(mean, stddev, rand)     theta = 2 * math::pi * rand.call     rho = math.sqrt(-2 * math.log(1 - rand.call))     scale = stddev * rho     x = mean + scale * math.cos(theta)     y = mean + scale * math.sin(theta)     return x, y   end end 

cc0 (cc0)

to extent possible under law, antonakos has waived copyright , related or neighboring rights randomgaussian ruby class. work published from: denmark.


the license statement not mean care code. on contrary, don't use code, haven't tested it, , don't program in ruby.


Comments