class Rust::RandomVariable
Constants
- COIN
- DICE
- ENGLISH_ALPHABET
- EPSILON
Attributes
values[R]
Public Class Methods
complete(hash, key=0)
click to toggle source
# File lib/rust-probabilities.rb, line 183 def self.complete(hash, key=0) hash[key] = 1 - hash.values.sum return RandomVariable.new(hash) end
new(values = {0 => 1.0}, exact = false)
click to toggle source
# File lib/rust-probabilities.rb, line 92 def initialize(values = {0 => 1.0}, exact = false) @values = values @exact = exact raise "All the probabilities should be in the range [0, 1]" unless @values.values.all? { |v| v.between? 0, 1 } raise "The cumulative probability must be exactly 1 (#{@values.values.sum} instead)" unless @values.values.sum.between? 1-EPSILON, 1+EPSILON approx! end
Public Instance Methods
*(times)
click to toggle source
# File lib/rust-probabilities.rb, line 120 def *(times) if times.is_a? Integer return rep(times) elsif times.is_a? RandomVariable return mul(times) else raise "The argument must be an Integer or a RandomVariable" end end
+(other)
click to toggle source
# File lib/rust-probabilities.rb, line 106 def +(other) new_hash = {} @values.each do |my_key, my_value| other.values.each do |other_key, other_value| sum_key = my_key + other_key new_hash[sum_key] = new_hash[sum_key].to_f + (my_value * other_value) end end return RandomVariable.new(new_hash, @exact) end
approx!()
click to toggle source
# File lib/rust-probabilities.rb, line 157 def approx! return if @exact to_delete = [] @values.each do |v, probability| to_delete.push v if probability <= EPSILON end to_delete.each do |v| probability = @values.delete v nearest = @values.keys.min_by { |k| k.distance v } @values[nearest] += probability end end
exact!()
click to toggle source
# File lib/rust-probabilities.rb, line 153 def exact! @exact = true end
extract()
click to toggle source
# File lib/rust-probabilities.rb, line 172 def extract v = rand cumulative = 0 @values.each do |key, prob| cumulative += prob return key if cumulative >= v end end
mul(other)
click to toggle source
# File lib/rust-probabilities.rb, line 130 def mul(other) new_hash = {} @values.each do |my_key, my_value| other.values.each do |other_key, other_value| mul_key = my_key * other_key new_hash[mul_key] = new_hash[mul_key].to_f + (my_value * other_value) end end return RandomVariable.new(new_hash, @exact) end
probability(v)
click to toggle source
# File lib/rust-probabilities.rb, line 102 def probability(v) return @values[v].to_f end
rep(times)
click to toggle source
# File lib/rust-probabilities.rb, line 144 def rep(times) rv = self (times-1).times do rv += self end return rv end