1 class MathPlugin < Plugin
25 def help(plugin, topic="")
26 "math <expression>, evaluate mathematical expression"
30 m.reply "incorrect usage: " + help(m.plugin)
36 expr.gsub!(/\b#{k}\b/, v)
39 while expr =~ /(exp ([\w\d]+))/
41 val = Math.exp($2).to_s
42 expr.gsub!(/#{Regexp.escape exp}/, "+#{val}")
45 while expr =~ /^\s*(dec2hex\s*(\d+))\s*\?*/
47 val = sprintf("%x", $2)
48 expr.gsub!(/#{Regexp.escape exp}/, "+#{val}")
51 expr.gsub(/\be\b/, Math.exp(1).to_s)
53 while expr =~ /(log\s*((\d+\.?\d*)|\d*\.?\d+))\s*/
60 val = Math.log(res).to_s
63 expr.gsub!(/#{Regexp.escape exp}/, "+#{val}")
66 while expr =~ /(bin2dec ([01]+))/
68 val = join('', unpack('B*', pack('N', $2)))
70 expr.gsub!(/#{Regexp.escape exp}/, "+#{val}")
73 expr.gsub!(/ to the power of /, " ** ")
74 expr.gsub!(/ to the /, " ** ")
75 expr.gsub!(/\btimes\b/, "*")
76 expr.gsub!(/\bdiv(ided by)? /, "/ ")
77 expr.gsub!(/\bover /, "/ ")
78 expr.gsub!(/\bsquared/, "**2 ")
79 expr.gsub!(/\bcubed/, "**3 ")
80 expr.gsub!(/\bto\s+(\d+)(r?st|nd|rd|th)?( power)?/, "**\1 ")
81 expr.gsub!(/\bpercent of/, "*0.01*")
82 expr.gsub!(/\bpercent/, "*0.01")
83 expr.gsub!(/\% of\b/, "*0.01*")
84 expr.gsub!(/\%/, "*0.01")
85 expr.gsub!(/\bsquare root of (\d+)/, "\1 ** 0.5 ")
86 expr.gsub!(/\bcubed? root of (\d+)/, "\1 **(1.0/3.0) ")
87 expr.gsub!(/ of /, " * ")
88 expr.gsub!(/(bit(-| )?)?xor(\'?e?d( with))?/, "^")
89 expr.gsub!(/(bit(-| )?)?or(\'?e?d( with))?/, "|")
90 expr.gsub!(/bit(-| )?and(\'?e?d( with))?/, "& ")
91 expr.gsub!(/(plus|and)/, "+")
93 if (expr =~ /^\s*[-\d*+\s()\/^\.\|\&\*\!]+\s*$/ &&
94 expr !~ /^\s*\(?\d+\.?\d*\)?\s*$/ &&
96 expr !~ /^\s*[( )]+\s*$/)
99 debug "evaluating expression \"#{expr}\""
101 if answer =~ /^[-+\de\.]+$/
102 answer = sprintf("%1.12f", answer)
103 answer.gsub!(/\.?0+$/, "")
104 answer.gsub!(/(\.\d+)000\d+/, '\1')
105 if (answer.length > 30)
106 answer = "a number with >30 digits..."
110 rescue Exception => e
111 puts "couldn't evaluate expression \"#{m.params}\": #{e}"
112 m.reply "illegal expression \"#{m.params}\""
116 m.reply "illegal expression \"#{m.params}\""
121 plugin = MathPlugin.new
122 plugin.register("math")