问题描述
在 ruby 中生成正态分布随机数的代码是什么?
(注意:我回答了我自己的问题,但我会等几天再接受,看看是否有人有更好的答案.)
为此,我查看了两次搜索导致的 SO 上的所有页面:
+正态分布"红宝石
和
+高斯+随机红宝石
Python 的
在法律允许的范围内,antonakos 已放弃 RandomGaussian 的所有版权和相关或邻接权
Ruby 类.本作品发表于:丹麦.
许可声明并不意味着我关心这段代码.相反,我不使用代码,我没有测试过,我也不会用 Ruby 编程.
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
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
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.
这篇关于在 Ruby 中生成高斯(正态分布)随机数的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!