1Math::Expression::EvaluUasteorr(C3o)ntributed Perl DocumMeanttha:t:iEoxnpression::Evaluator(3)
2
3
4
6 Math::Expression::Evaluator - parses, compiles and evaluates mathematic
7 expressions
8
10 use Math::Expression::Evaluator;
11 my $m = Math::Expression::Evaluator->new;
12
13 print $m->parse("a = 12; a*3")->val(), "\n";
14 # prints 36
15 print $m->parse("2^(a/3)")->val(), "\n";
16 # prints 8 (ie 2**3)
17 print $m->parse("a / b")->val({ b => 6 }), "\n";
18 # prints 36
19 print $m->parse("log2(16)")->val(), "\n";
20 # prints 4
21
22 # if you care about speed
23 my $func = $m->parse('2 + (4 * b)')->compiled;
24 for (0 .. 100){
25 print $func->({b => $_}), "\n";
26 }
27
29 Math::Expression::Evaluator is a parser, compiler and interpreter for
30 mathematical expressions. It can handle normal arithmetics (includings
31 powers wit "^" or "**"), builtin functions like sin() and variables.
32
33 Multiplication "*", division "/" and modulo "%" have the same
34 precedence, and are evaluated left to right. The modulo operation
35 follows the standard perl semantics, that is is the arguments are
36 castet to integer before preforming the modulo operation.
37
38 Multiple exressions can be seperated by whitespaces or by semicolons
39 ';'. In case of multiple expressions the value of the last expression
40 is returned.
41
42 Variables can be assigned with a single '=' sign, their name has to
43 start with a alphabetic character or underscore "[a-zA-Z_]", and may
44 contain alphabetic characters, digits and underscores.
45
46 Values for variables can also be provided as a hash ref as a parameter
47 to val(). In case of collision the explicitly provided value is used:
48
49 $m->parse("a = 2; a")->val({a => 1});
50
51 will return 1, not 2.
52
53 The following builtin functions are supported atm:
54
55 • trignometric functions: sin, cos, tan
56
57 • inverse trigonomic functions: asin, acos, atan
58
59 • Square root: sqrt
60
61 • exponentials: exp, sinh, cosh
62
63 • logarithms: log, log2, log10
64
65 • constants: pi() (you need the parenthesis to distinguish it from
66 the variable pi)
67
68 • rounding: ceil(), floor()
69
70 • other: theta (theta(x) = 1 for x > 0, theta(x) = 0 for x < 0)
71
73 new
74 generates a new MathExpr object. accepts an optional argument, a hash
75 ref that contains configurations. If this hash sets force_semicolon
76 to true, expressions have to be separated by a semicolon ';'.
77
78 parse
79 Takes a string as argument, and generates an Abstract Syntax
80 Tree(AST) that is stored internally.
81
82 Returns a reference to the object, so that method calls can be
83 chained:
84
85 print MathExpr->new->parse("1+2")->val;
86
87 Parse failures cause this method to die with a stack trace.
88
89 You can call "parse" on an existing Math::Expression::Evaluator
90 object to re-use it, in which case previously set variables and
91 callbacks persist between calls.
92
93 This (perhaps contrived) example explains this:
94
95 my $m = Math::Expression::Evaluator->new('a = 3; a');
96 $m->val();
97 $m->parse('a + 5');
98 print $m->val(), "\n" # prints 8, because a = 3 was re-used
99
100 If that's not what you want, create a new object instead - the
101 constructor is rather cheap.
102
103 compiled
104 Returns an anonymous function that is a compiled version of the
105 current expression. It is much faster to execute than the other
106 methods, but its error messages aren't as informative (instead of
107 complaining about a non-existing variable it dies with "Use of
108 uninitialized value in...").
109
110 Note that variables are not persistent between calls to compiled
111 functions (and it wouldn't make sense anyway, because such a function
112 corresponds always to exactly one expression, not many as a MEE
113 object).
114
115 Variables that were stored at the time when "compiled()" is called
116 are availble in the compiled function, though.
117
118 val
119 Executes the AST generated by parse(), and returns the number that
120 the expression is evaluated to. It accepts an optional hash reference
121 that contain values for variables:
122
123 my $m = MathExpr->new;
124 $m->parse("(x - 1) / (x + 1)");
125 foreach (0 .. 10) {
126 print $_, "\t", $m->val({x => $_}), "\n";
127 }
128
129 optimize
130 Optimizes the internal AST, so that subsequent calls to "val()" will
131 be a bit faster. See "Math::Expression::Evaluator::Optimizer" for
132 performance considerations and informations on the implemented
133 optimizations.
134
135 But note that a call to "optimize()" only pays off if you call
136 "val()" multiple times.
137
138 variables
139 "variables()" returns a list of variables that are used in the
140 expression.
141
142 set_var_callback
143 Allows you to set a callback which the Match::Expression::Evaluator
144 object calls when it can't find a variable. The name of the variable
145 is passed in as the first argument. If the callback function can't
146 handle that variable either, it should die, just like the default one
147 does.
148
149 my $m = Math::Expression::Evaluator->new();
150 $m->parse('1 + a');
151 my $callback = sub { ord($_[0]) };
152 $m->set_var_callback($callback);
153 print $m->val(); # calls $callback, which returns 97
154 # so $m->val() return 98
155
156 The callback will be called every time the variable is accessed, so
157 if it requires expensive calculations, you are encouraged to cache it
158 either yourself our automatically with Memoize.
159
160 set_function
161 Allows to add a user-defined function, or to override a built-in
162 function.
163
164 my $m = Math::Expression::Evaluator->new();
165 $m->set_function('abs', sub { abs($_[0]) });
166 $m->parse('abs(10.6)');
167 print $m->val();
168
169 If you first compile the expression to a perl closure and then call
170 "<$m-"set_function>> again, the compiled function stays unaffected,
171 so
172
173 $m->set_function('f', sub { 42 });
174 my $compiled = $m->parse('f')->compiled;
175 $m->set_function('f', sub { -23 });
176 print $compiled->();
177
178 print out 42, not "-23".
179
180 ast_size
181 "ast_size" returns an integer which gives a crude measure of the
182 logical size of the expression. Note that this value isn't
183 guarantueed to be stable across multiple versions of this module. It
184 is mainly intended for testing.
185
187 MEE isn't as fast as perl, because it is built on top of perl.
188
189 If you execute an expression multiple times, it pays off to either
190 optimize it first, or (even better) compile it to a pure perl function.
191
192 Rate no_optimize optimize opt_compiled compiled
193 no_optimize 83.9/s -- -44% -82% -83%
194 optimize 150/s 78% -- -68% -69%
195 opt_compiled 472/s 463% 215% -- -4%
196 compiled 490/s 485% 227% 4% --
197
198 This shows the time for 200 evaluations of "2+a+5+(3+4)" (with MEE
199 0.0.5). As you can see, the non-optimized version is painfully slow,
200 optimization nearly doubles the execution speed. The compiled and the
201 optimized-and-then-compiled versions are both much faster.
202
203 With this example expression the optimization prior to compilation pays
204 off if you evaluate it more than 1000 times. But even if you call it
205 "10**5" times the optimized and compiled version is only 3% faster than
206 the directly compiled one (mostly due to perl's overhead for method
207 calls).
208
209 So to summarize you should compile your expresions, and if you have
210 really many iterations it might pay off to optimize it first (or to
211 write your program in C instead ;-).
212
214 • Modulo operator produces an unnecessary big AST, making it
215 relatively slow
216
218 The AST can be accessed as "$obj-"{ast}>. Its structure is described in
219 Math::Expression::Evaluator::Parser (or you can use Data::Dumper to
220 figure it out for yourself). Note that the exact form of the AST is
221 considered to be an implementation detail, and subject to change.
222
224 Math::Expression also evaluates mathematical expressions, but also
225 handles string operations.
226
227 If you want to do symbolic (aka algebraic) transformations,
228 Math::Symbolic will fit your needs.
229
231 This module is free software. You may use, redistribute and modify it
232 under the same terms as perl itself.
233
235 Copyright (C) 2007 - 2009 Moritz Lenz, <http://perlgeek.de/>,
236 moritz@faui2k3.org
237
239 You can obtain the latest development version from github
240 <http://github.com/moritz/math-expression-evaluator>.
241
242 git clone git://github.com/moritz/math-expression-evaluator.git
243
244 If you want to contribute something to this module, please ask me for a
245 commit bit to the github repository, I'm giving them out freely.
246
248 The following people have contributed to this module, in no particular
249 order:
250
251 Leonardo Herrera
252 Initial patch for "set_function"
253
254 Tina Müller
255 Helpful feedback
256
257
258
259perl v5.32.1 2021-01-27 Math::Expression::Evaluator(3)