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

后端 未结 4 729
夕颜
夕颜 2021-02-01 03:32

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

4条回答
  •  滥情空心
    2021-02-01 04:00

    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.

提交回复
热议问题