Created
November 12, 2010 20:55
-
-
Save Vaguery/674663 to your computer and use it in GitHub Desktop.
The StickpigScript class for creating and evaluating random arithmetic expressions in a simple S-expression tree GP language, and two examples from the book I'm working on.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require './stickpig' | |
| 100.times do |i| | |
| stick = StickpigScript.new(0.4) | |
| puts "#{i}, #{stick.script.length}" + | |
| [-20,-10,-1,0,1,10,20].inject("") {|line, x| line + ", #{stick.evaluate(x).round(5)}"} | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class StickpigScript | |
| attr_accessor :script | |
| LEAVES = ["x", "constant"] | |
| BRANCHES = ["negative( # )", "add( #, # )", "subtract( #, # )", "multiply( #, # )", "divide( #, # )"] | |
| def initialize(terminal_chance=0.44) | |
| tree = "#" | |
| while tree.include?("#") && tree.length < 2000 | |
| tree = tree.gsub(/#/) {|point| (Random.rand<terminal_chance) ? LEAVES.sample : BRANCHES.sample} | |
| end | |
| tree = tree.gsub(/#/) {|point| LEAVES.sample} # cleanup | |
| @script=tree.gsub(/constant/) {|k| (Random.rand*100-50).round(3)} | |
| end | |
| def add(arg1, arg2) | |
| arg1 + arg2 | |
| end | |
| def subtract(arg1, arg2) | |
| arg1 - arg2 | |
| end | |
| def multiply(arg1, arg2) | |
| arg1 * arg2 | |
| end | |
| def divide(arg1, arg2) | |
| arg2==0 ? 0 : arg1 / arg2 | |
| end | |
| def negative(arg) | |
| -arg | |
| end | |
| def evaluate(x) | |
| self.instance_eval(@script.gsub("x",x.to_s)) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment