Generate Array of Numbers that fit to a Probability Distribution in Ruby?

谁说我不能喝 提交于 2019-11-30 16:43:14

You can generate UNIX timestamps which are really just integers. First figure out when you want to start, for example now:

start = DateTime::now().to_time.to_i

Find out when the end of your interval should be (say 1 week later):

finish = (DateTime::now()+1.week).to_time.to_i

Ruby uses this algorithm to generate random numbers. It is almost uniform. Then generate random numbers between the two:

r = Random.new.rand(start..finish)

Then convert that back to a date:

d = Time.at(r)

This looks promising as well: http://rb-gsl.rubyforge.org/files/rdoc/randist_rdoc.html

And this too: http://rb-gsl.rubyforge.org/files/rdoc/rng_rdoc.html

jabbrwcky

I recently came across croupier, a ruby gem that aims to generate numbers according to a variety of statistical distributions.

I have yet to try it but it sounds quite promising.

Mitch Wheat

From wiki:

There are a couple of methods to generate a random number based on a probability density function. These methods involve transforming a uniform random number in some way. Because of this, these methods work equally well in generating both pseudo-random and true random numbers.

One method, called the inversion method, involves integrating up to an area greater than or equal to the random number (which should be generated between 0 and 1 for proper distributions).

A second method, called the acceptance-rejection method, involves choosing an x and y value and testing whether the function of x is greater than the y value. If it is, the x value is accepted. Otherwise, the x value is rejected and the algorithm tries again.

The first method is the one used in the accepted answer in your SO linked question: Generate Random Numbers with Probabilistic Distribution

Another option is the Distribution gem under SciRuby. You can generate normal numbers by:

require 'distribution'

rng = Distribution::Normal.rng
random_numbers = Array.new(100).map { rng.call }

There are RNGs for various other distributions as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!