Module: TinyMonte
- Defined in:
- lib/tiny_monte.rb
Overview
a Monte Carlo simulator
Class Method Summary collapse
-
._trial(samples_per_trial, probability) ⇒ Object
returns an array of samples constituting a single trial run.
-
.median_result(results) ⇒ Object
returns the median result from the output of the ::monte method.
-
.monte(trials, samples_per_trial, probability) ⇒ Object
returns the result set from running the specified number of Monte Carlo simulations with the specified probability.
Class Method Details
._trial(samples_per_trial, probability) ⇒ Object
returns an array of samples constituting a single trial run
ex:
_trial(100, 0.5) # => [0, 1, 1, 0, ...] <100 times long>
32 33 34 |
# File 'lib/tiny_monte.rb', line 32 def _trial(samples_per_trial, probability) (1..samples_per_trial).map{|i| rand() <= probability ? 1 : 0 } end |
.median_result(results) ⇒ Object
21 22 23 24 25 26 |
# File 'lib/tiny_monte.rb', line 21 def median_result(results) sorted = results.sort sorted_count = sorted.count working_median = sorted_count.odd? ? sorted[((sorted_count + 1) / 2) - 1] : (sorted[(sorted_count - 1) / 2] + sorted[((sorted_count) / 2)] / 2.0) working_median == working_median.to_i ? working_median.to_i : working_median end |
.monte(trials, samples_per_trial, probability) ⇒ Object
returns the result set from running the specified number of Monte Carlo simulations with the specified probability.
trials: the number of trials to perform samples_per_trial: the number of samples to generate per trial probability: the probability of success in each trial
ex:
TinyMonte.monte(1000, 0.5) # => [51, 48, 52, ...]
13 14 15 |
# File 'lib/tiny_monte.rb', line 13 def monte(trials, samples_per_trial, probability) (1..trials).map{|i| _trial(samples_per_trial, probability).count(1) } end |