在 Ruby 中生成高斯(正态分布)随机数的代码
在 ruby 中生成正态分布随机数的代码是什么?
(注意:我回答了我自己的问题,但我会等几天再接受,看看是否有人有更好的答案。)
编辑:
搜索这个,我查看了SO结果的所有页面从两个搜索中:
+“正态分布”红宝石
和
+高斯+随机红宝石
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Python 的 random.gauss()和 Boost 的 normal_distribution 都使用 Box-Muller 变换,所以这对于 Ruby 来说也应该足够好了。
该方法可以封装在一个类中,该类一一返回样本。
(CC0)
在法律允许的范围内,antonakos 已放弃所有版权及相关或邻接权到
RandomGaussian
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.
The method can be wrapped up in a class that returns the samples one by one.
(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.最初的问题要求提供代码,但作者的后续评论暗示了对使用现有库的兴趣。我对此也很感兴趣,我的搜索发现了这两个 ruby gem:
gsl - “GNU Scientific Library 的 Ruby 接口” (需要您安装 GSL)。平均值 = 0 和给定标准差的正态分布随机数的调用序列是
rubystats - “统计库的端口PHPMath”(纯红宝石)。具有给定均值和标准差的正态分布随机数的调用序列为
The original question asked for code, but the author's followup comment implied an interest in using existing libraries. I was interested in the same, and my searches turned up these two ruby gems:
gsl - "Ruby interface to the GNU Scientific Library" (requires you to install GSL). The calling sequence for normally distributed random numbers with mean = 0 and a given standard deviation is
rubystats - "a port of the statistics libraries from PHPMath" (pure ruby). The calling sequence for normally distributed random numbers with a given mean and standard deviation is
对@antonakos 的回答+1。这是我一直在使用的 Box-Muller 的实现;它本质上是相同的,但代码稍微严格一些:
当然,如果您真的关心速度,您应该实现 Ziggurat 算法< /a>:)。
+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:
Of course, if you really cared about speed, you should implement the Ziggurat Algorithm :).
另一种选择是使用 distribution gem,由一位 SciRuby 研究员编写。
我认为使用起来更简单一些。
Another option, this one using the distribution gem, written by one of the SciRuby fellows.
It is a little simpler to use, I think.