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

Eponymous picture Eponymous · Apr 29, 2011 · Viewed 21.3k times · Source

What is some code to generate normally distributed random numbers in ruby?

(Note: I answered my own question, but I'll wait a few days before accepting to see if anyone has a better answer.)

EDIT:

Searching for this, I looked at all pages on SO resulting from the two searches:

+"normal distribution" ruby

and

+gaussian +random ruby

Answer

antonakos picture antonakos · May 30, 2011

Python's random.gauss() and Boost's normal_distribution both use the Box-Muller transform, so that should be good enough for 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 be wrapped up in a class that returns the samples one by 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 then
      @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 the extent possible under law, antonakos has waived all copyright and related or neighboring rights to the RandomGaussian Ruby class. This work is published from: Denmark.


The license statement does not mean I care about this code. On the contrary, I don't use the code, I haven't tested it, and I don't program in Ruby.