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

后端 未结 4 725
夕颜
夕颜 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:11

    +1 on @antonakos's answer. Here's the implementation of Box-Muller that I've been using; it's essentially identical but slightly tighter code:

    class RandomGaussian
      def initialize(mean = 0.0, sd = 1.0, rng = lambda { Kernel.rand })
        @mean, @sd, @rng = mean, sd, rng
        @compute_next_pair = false
      end
    
      def rand
        if (@compute_next_pair = !@compute_next_pair)
          # Compute a pair of random values with normal distribution.
          # See http://en.wikipedia.org/wiki/Box-Muller_transform
          theta = 2 * Math::PI * @rng.call
          scale = @sd * Math.sqrt(-2 * Math.log(1 - @rng.call))
          @g1 = @mean + scale * Math.sin(theta)
          @g0 = @mean + scale * Math.cos(theta)
        else
          @g1
        end
      end
    end
    

    Of course, if you really cared about speed, you should implement the Ziggurat Algorithm :).

提交回复
热议问题