Experiments with ruby-processing (processing-2.2.1) and JRubyArt for processing-3.0

Saturday, 2 January 2010

Checking the probabilities

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

Followers

Blog Archive

About Me

My photo
I have developed JRubyArt and propane new versions of ruby-processing for JRuby-9.1.5.0 and processing-3.2.2