After a bit of a faux pas, where I needed to change my code I thought I'd better check the randomness of the code (its so easy in ruby).
class ProbTest
attr_accessor :rules
def initialize
@rules = Hash.new
rules.store(["abc", 0], 0.1)
rules.store(["def", 0], 0.2)
rules.store(["ghi", 0], 0.3)
rules.store(["jkl", 0], 0.4)
end
def stochastic_rule(rules)
target = rand
rules.each do |item, weight|
return item unless target > weight
target -= weight
end
end
def increment(rules)
item = stochastic_rule(rules)
item[1] += 1
return item
end
end
test = ProbTest.new
10000.times do
test.increment(test.rules)
end
puts test.rules
# {["abc", 1002]=>0.1, ["def", 2043]=>0.2, ["ghi", 2980]=>0.3, ["jkl", 3975]=>0.4}
Such a simple check would not satisfy a statistician, but there good enough for me... to see it working in my December 10th post.
No comments:
Post a Comment