1 class MathPlugin < Plugin
28 def help(plugin, topic="")
29 "math <expression>, evaluate mathematical expression"
33 m.reply "incorrect usage: " + help(m.plugin)
39 expr.gsub!(/\b#{k}\b/, v)
42 while expr =~ /(exp ([\w\d]+))/
44 val = Math.exp($2).to_s
45 expr.gsub!(/#{Regexp.escape exp}/, "+#{val}")
48 while expr =~ /^\s*(dec2hex\s*(\d+))\s*\?*/
50 val = sprintf("%x", $2)
51 expr.gsub!(/#{Regexp.escape exp}/, "+#{val}")
54 expr.gsub(/\be\b/, Math.exp(1).to_s)
56 while expr =~ /(log\s*((\d+\.?\d*)|\d*\.?\d+))\s*/
63 val = Math.log(res).to_s
66 expr.gsub!(/#{Regexp.escape exp}/, "+#{val}")
69 while expr =~ /(bin2dec ([01]+))/
71 val = join('', unpack('B*', pack('N', $2)))
73 expr.gsub!(/#{Regexp.escape exp}/, "+#{val}")
76 expr.gsub!(/ to the power of /, " ** ")
77 expr.gsub!(/ to the /, " ** ")
78 expr.gsub!(/\btimes\b/, "*")
79 expr.gsub!(/\bdiv(ided by)? /, "/ ")
80 expr.gsub!(/\bover /, "/ ")
81 expr.gsub!(/\bsquared/, "**2 ")
82 expr.gsub!(/\bcubed/, "**3 ")
83 expr.gsub!(/\bto\s+(\d+)(r?st|nd|rd|th)?( power)?/, "**\1 ")
84 expr.gsub!(/\bpercent of/, "*0.01*")
85 expr.gsub!(/\bpercent/, "*0.01")
86 expr.gsub!(/\% of\b/, "*0.01*")
87 expr.gsub!(/\%/, "*0.01")
88 expr.gsub!(/\bsquare root of (\d+)/, "\1 ** 0.5 ")
89 expr.gsub!(/\bcubed? root of (\d+)/, "\1 **(1.0/3.0) ")
90 expr.gsub!(/ of /, " * ")
91 expr.gsub!(/(bit(-| )?)?xor(\'?e?d( with))?/, "^")
92 expr.gsub!(/(bit(-| )?)?or(\'?e?d( with))?/, "|")
93 expr.gsub!(/bit(-| )?and(\'?e?d( with))?/, "& ")
94 expr.gsub!(/(plus|and)/, "+")
96 if (expr =~ /^\s*[-\d*+\s()\/^\.\|\&\*\!]+\s*$/ &&
97 expr !~ /^\s*\(?\d+\.?\d*\)?\s*$/ &&
99 expr !~ /^\s*[( )]+\s*$/)
102 debug "evaluating expression \"#{expr}\""
104 if answer =~ /^[-+\de\.]+$/
105 answer = sprintf("%1.12f", answer)
106 answer.gsub!(/\.?0+$/, "")
107 answer.gsub!(/(\.\d+)000\d+/, '\1')
108 if (answer.length > 30)
109 answer = "a number with >30 digits..."
113 rescue Exception => e
114 error "couldn't evaluate expression \"#{m.params}\": #{e.inspect}"
115 m.reply "illegal expression \"#{m.params}\""
119 m.reply "illegal expression \"#{m.params}\""
124 plugin = MathPlugin.new
125 plugin.register("math")
126 plugin.register("maths")