ILIAS  release_5-0 Revision 5.0.0-1144-gc4397b1f870
EvalMath Class Reference
+ Collaboration diagram for EvalMath:

Public Member Functions

 EvalMath ()
 
 e ($expr)
 
 evaluate ($expr)
 
 vars ()
 
 funcs ()
 
 nfx ($expr)
 
 pfx ($tokens, $vars=array())
 
 trigger ($msg)
 
 from_hexbin ($token)
 

Data Fields

 $suppress_errors = false
 
 $last_error = null
 
 $v = array('e'=>2.71,'pi'=>3.14)
 
 $f = array()
 
 $vb = array('e', 'pi')
 
 $fb
 

Detailed Description

Definition at line 89 of file class.EvalMath.php.

Member Function Documentation

◆ e()

EvalMath::e (   $expr)

Definition at line 113 of file class.EvalMath.php.

113 {
114 return $this->evaluate($expr);
115 }
evaluate($expr)

References evaluate().

+ Here is the call graph for this function:

◆ EvalMath()

EvalMath::EvalMath ( )

Definition at line 103 of file class.EvalMath.php.

103 {
104 // make the variables a little more accurate
105 $this->v['pi'] = pi();
106 $this->v['exp'] = exp(1);
107 // PATCH BEGIN
108 $this->v['e'] = exp(1); // different result for exp(1) and e
109 $this->fb[] = 'exp'; // usage of php exp function in formula
110 // PATCH END
111 }
v($data, $pos)

References v().

+ Here is the call graph for this function:

◆ evaluate()

EvalMath::evaluate (   $expr)

Definition at line 117 of file class.EvalMath.php.

117 {
118 // convert exponential notation
119 $expr = preg_replace("/(\\d{0,1})e(-{0,1}\\d+)/eis", "'\\1'.((strlen('\\1')) ? '*' : '').'10^(\\2)'", $expr);
120 // standard functionality
121 $this->last_error = null;
122 $expr = trim($expr);
123 if (substr($expr, -1, 1) == ';') $expr = substr($expr, 0, strlen($expr)-1); // strip semicolons at the end
124 //===============
125 // is it a variable assignment?
126 if (preg_match('/^\s*([a-z]\w*)\s*=\s*(.+)$/', $expr, $matches)) {
127 if (in_array($matches[1], $this->vb)) { // make sure we're not assigning to a constant
128 return $this->trigger("cannot assign to constant '$matches[1]'");
129 }
130 if (($tmp = $this->pfx($this->nfx($matches[2]))) === false) return false; // get the result and make sure it's good
131 $this->v[$matches[1]] = $tmp; // if so, stick it in the variable array
132 return $this->v[$matches[1]]; // and return the resulting value
133 //===============
134 // is it a function assignment?
135 } elseif (preg_match('/^\s*([a-z]\w*)\s*\‍(\s*([a-z]\w*(?:\s*,\s*[a-z]\w*)*)\s*\‍)\s*=\s*(.+)$/', $expr, $matches)) {
136 $fnn = $matches[1]; // get the function name
137 if (in_array($matches[1], $this->fb)) { // make sure it isn't built in
138 return $this->trigger("cannot redefine built-in function '$matches[1]()'");
139 }
140 $args = explode(",", preg_replace("/\s+/", "", $matches[2])); // get the arguments
141 if (($stack = $this->nfx($matches[3])) === false) return false; // see if it can be converted to postfix
142 for ($i = 0; $i<count($stack); $i++) { // freeze the state of the non-argument variables
143 $token = $stack[$i];
144 if (preg_match('/^[a-z]\w*$/', $token) and !in_array($token, $args)) {
145 if (array_key_exists($token, $this->v)) {
146 $stack[$i] = $this->v[$token];
147 } else {
148 return $this->trigger("undefined variable '$token' in function definition");
149 }
150 }
151 }
152 $this->f[$fnn] = array('args'=>$args, 'func'=>$stack);
153 return true;
154 //===============
155 } else {
156 return $this->pfx($this->nfx($expr)); // straight up evaluation, woo
157 }
158 }
pfx($tokens, $vars=array())

References nfx(), pfx(), trigger(), and v().

Referenced by e().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ from_hexbin()

EvalMath::from_hexbin (   $token)

Definition at line 380 of file class.EvalMath.php.

380 {
381 if (strtoupper(substr($token, -1, 1))=='H') return hexdec($token);
382 if (strtoupper(substr($token, -1, 1))=='B') return bindec($token);
383 return FALSE;
384 }

Referenced by pfx().

+ Here is the caller graph for this function:

◆ funcs()

EvalMath::funcs ( )

Definition at line 167 of file class.EvalMath.php.

167 {
168 $output = array();
169 foreach ($this->f as $fnn=>$dat)
170 $output[] = $fnn . '(' . implode(',', $dat['args']) . ')';
171 return $output;
172 }

◆ nfx()

EvalMath::nfx (   $expr)

Definition at line 177 of file class.EvalMath.php.

177 {
178
179 $index = 0;
180 $stack = new EvalMathStack;
181 $output = array(); // postfix form of expression, to be passed to pfx()
182 $expr = trim(strtolower($expr));
183
184 $ops = array('+', '-', '*', '/', '^', '_');
185 $ops_r = array('+'=>0,'-'=>0,'*'=>0,'/'=>0,'^'=>1); // right-associative operator?
186 $ops_p = array('+'=>0,'-'=>0,'*'=>1,'/'=>1,'_'=>1,'^'=>2); // operator precedence
187
188 $expecting_op = false; // we use this in syntax-checking the expression
189 // and determining when a - is a negation
190
191 if (preg_match("/[^\w\s+*^\/()\.,-]/", $expr, $matches)) { // make sure the characters are all good
192 return $this->trigger("illegal character '{$matches[0]}'");
193 }
194
195 while(1) { // 1 Infinite Loop ;)
196 $op = substr($expr, $index, 1); // get the first character at the current index
197 // find out if we're currently at the beginning of a number/variable/function/parenthesis/operand
198 $ex = preg_match('/^([01]+[bB]|[\da-fA-F]+[hH]|[a-z]\w*\‍(?|\d+(?:\.\d*)?|\.\d+|\‍()/', substr($expr, $index), $match);
199 //===============
200 if ($op == '-' and !$expecting_op) { // is it a negation instead of a minus?
201 $stack->push('_'); // put a negation on the stack
202 $index++;
203 } elseif ($op == '_') { // we have to explicitly deny this, because it's legal on the stack
204 return $this->trigger("illegal character '_'"); // but not in the input expression
205 //===============
206 } elseif ((in_array($op, $ops) or $ex) and $expecting_op) { // are we putting an operator on the stack?
207 if ($ex) { // are we expecting an operator but have a number/variable/function/opening parethesis?
208 $op = '*'; $index--; // it's an implicit multiplication
209 }
210 // heart of the algorithm:
211 while($stack->count > 0 and ($o2 = $stack->last()) and in_array($o2, $ops) and ($ops_r[$op] ? $ops_p[$op] < $ops_p[$o2] : $ops_p[$op] <= $ops_p[$o2])) {
212 $output[] = $stack->pop(); // pop stuff off the stack into the output
213 }
214 // many thanks: http://en.wikipedia.org/wiki/Reverse_Polish_notation#The_algorithm_in_detail
215 $stack->push($op); // finally put OUR operator onto the stack
216 $index++;
217 $expecting_op = false;
218 //===============
219 } elseif ($op == ')' and $expecting_op) { // ready to close a parenthesis?
220 while (($o2 = $stack->pop()) != '(') { // pop off the stack back to the last (
221 if (is_null($o2)) return $this->trigger("unexpected ')'");
222 else $output[] = $o2;
223 }
224 if (preg_match("/^([a-z]\w*)\‍($/", $stack->last(2), $matches)) { // did we just close a function?
225 $fnn = $matches[1]; // get the function name
226 $arg_count = $stack->pop(); // see how many arguments there were (cleverly stored on the stack, thank you)
227 $output[] = $stack->pop(); // pop the function and push onto the output
228 if (in_array($fnn, $this->fb)) { // check the argument count
229 if($arg_count > 1)
230 return $this->trigger("too many arguments ($arg_count given, 1 expected)");
231 } elseif (array_key_exists($fnn, $this->f)) {
232 if ($arg_count != count($this->f[$fnn]['args']))
233 return $this->trigger("wrong number of arguments ($arg_count given, " . count($this->f[$fnn]['args']) . " expected)");
234 } else { // did we somehow push a non-function on the stack? this should never happen
235 return $this->trigger("internal error");
236 }
237 }
238 $index++;
239 //===============
240 } elseif ($op == ',' and $expecting_op) { // did we just finish a function argument?
241 while (($o2 = $stack->pop()) != '(') {
242 if (is_null($o2)) return $this->trigger("unexpected ','"); // oops, never had a (
243 else $output[] = $o2; // pop the argument expression stuff and push onto the output
244 }
245 // make sure there was a function
246 if (!preg_match("/^([a-z]\w*)\‍($/", $stack->last(2), $matches))
247 return $this->trigger("unexpected ','");
248 $stack->push($stack->pop()+1); // increment the argument count
249 $stack->push('('); // put the ( back on, we'll need to pop back to it again
250 $index++;
251 $expecting_op = false;
252 //===============
253 } elseif ($op == '(' and !$expecting_op) {
254 $stack->push('('); // that was easy
255 $index++;
256 $allow_neg = true;
257 //===============
258 } elseif ($ex and !$expecting_op) { // do we now have a function/variable/number?
259 $expecting_op = true;
260 $val = $match[1];
261 if (preg_match("/^([a-z]\w*)\‍($/", $val, $matches)) { // may be func, or variable w/ implicit multiplication against parentheses...
262 if (in_array($matches[1], $this->fb) or array_key_exists($matches[1], $this->f)) { // it's a func
263 $stack->push($val);
264 $stack->push(1);
265 $stack->push('(');
266 $expecting_op = false;
267 } else { // it's a var w/ implicit multiplication
268 $val = $matches[1];
269 $output[] = $val;
270 }
271 } else { // it's a plain old var or num
272 $output[] = $val;
273 }
274 $index += strlen($val);
275 //===============
276 } elseif ($op == ')') { // miscellaneous error checking
277 return $this->trigger("unexpected ')'");
278 } elseif (in_array($op, $ops) and !$expecting_op) {
279 return $this->trigger("unexpected operator '$op'");
280 } else { // I don't even want to know what you did to get here
281 return $this->trigger("an unexpected error occured");
282 }
283 if ($index == strlen($expr)) {
284 if (in_array($op, $ops)) { // did we end with an operator? bad.
285 return $this->trigger("operator '$op' lacks operand");
286 } else {
287 break;
288 }
289 }
290 while (substr($expr, $index, 1) == ' ') { // step the index past whitespace (pretty much turns whitespace
291 $index++; // into implicit multiplication if no operator is there)
292 }
293
294 }
295 while (!is_null($op = $stack->pop())) { // pop everything off the stack and push onto output
296 if ($op == '(') return $this->trigger("expecting ')'"); // if there are (s on the stack, ()s were unbalanced
297 $output[] = $op;
298 }
299 return $output;
300 }

References trigger().

Referenced by evaluate().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ pfx()

EvalMath::pfx (   $tokens,
  $vars = array() 
)

Definition at line 303 of file class.EvalMath.php.

303 {
304
305 if ($tokens == false) return false;
306
307 $stack = new EvalMathStack;
308
309 foreach ($tokens as $token) { // nice and easy
310 // if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on
311 if (in_array($token, array('+', '-', '*', '/', '^'))) {
312 if (is_null($op2 = $stack->pop())) return $this->trigger("internal error");
313 if (is_null($op1 = $stack->pop())) return $this->trigger("internal error");
314 include_once "class.ilMath.php";
315 switch ($token) {
316 case '+':
317 $stack->push(ilMath::_add($op1,$op2)); break;
318 case '-':
319 $stack->push(ilMath::_sub($op1,$op2)); break;
320 case '*':
321 $stack->push(ilMath::_mul($op1,$op2)); break;
322 case '/':
323 if ($op2 == 0) return $this->trigger("division by zero");
324 $stack->push(ilMath::_div($op1,$op2)); break;
325 case '^':
326 $stack->push(ilMath::_pow($op1,$op2)); break;
327 }
328 // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
329 } elseif ($token == "_") {
330 $stack->push(-1*$stack->pop());
331 // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
332 } elseif (preg_match("/^([a-z]\w*)\‍($/", $token, $matches)) { // it's a function!
333 $fnn = $matches[1];
334 if (in_array($fnn, $this->fb)) { // built-in function:
335 if (is_null($op1 = $stack->pop())) return $this->trigger("internal error");
336 $fnn = preg_replace("/^arc/", "a", $fnn); // for the 'arc' trig synonyms
337 if ($fnn == 'log') {
338 $fnn = 'log10';
339 } elseif ($fnn == 'ln') {
340 $fnn = 'log';
341 }
342 eval('$stack->push(' . $fnn . '($op1));'); // perfectly safe eval()
343 } elseif (array_key_exists($fnn, $this->f)) { // user function
344 // get args
345 $args = array();
346 for ($i = count($this->f[$fnn]['args'])-1; $i >= 0; $i--) {
347 if (is_null($args[$this->f[$fnn]['args'][$i]] = $stack->pop())) return $this->trigger("internal error");
348 }
349 $stack->push($this->pfx($this->f[$fnn]['func'], $args)); // yay... recursion!!!!
350 }
351 // if the token is a number or variable, push it on the stack
352 } else {
353 if (is_numeric($token)) {
354 $stack->push($token);
355 } elseif (($hex=$this->from_hexbin($token))!==FALSE) {
356 $stack->push($hex);
357 } elseif (array_key_exists($token, $this->v)) {
358 $stack->push($this->v[$token]);
359 } elseif (array_key_exists($token, $vars)) {
360 $stack->push($vars[$token]);
361 } else {
362 return $this->trigger("undefined variable '$token'");
363 }
364 }
365 }
366 // when we're out of tokens, the stack should have a single element, the final result
367 if ($stack->count != 1) return $this->trigger("internal error");
368 return $stack->pop();
369 }
from_hexbin($token)
static _mul($left_operand, $right_operand, $scale=50)
static _div($left_operand, $right_operand, $scale=50)
static _pow($left_operand, $right_operand, $scale=50)
static _sub($left_operand, $right_operand, $scale=50)
static _add($left_operand, $right_operand, $scale=50)

References ilMath\_add(), ilMath\_div(), ilMath\_mul(), ilMath\_pow(), ilMath\_sub(), from_hexbin(), pfx(), trigger(), and v().

Referenced by evaluate(), and pfx().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ trigger()

EvalMath::trigger (   $msg)

Definition at line 372 of file class.EvalMath.php.

372 {
373 $this->last_error = $msg;
374 if (!$this->suppress_errors) trigger_error($msg, E_USER_WARNING);
375 return false;
376 }

Referenced by evaluate(), nfx(), and pfx().

+ Here is the caller graph for this function:

◆ vars()

EvalMath::vars ( )

Definition at line 160 of file class.EvalMath.php.

160 {
161 $output = $this->v;
162 unset($output['pi']);
163 unset($output['e']);
164 return $output;
165 }

References $v.

Field Documentation

◆ $f

EvalMath::$f = array()

Definition at line 95 of file class.EvalMath.php.

◆ $fb

EvalMath::$fb
Initial value:
= array(
'sin','sinh','arcsin','asin','arcsinh','asinh',
'cos','cosh','arccos','acos','arccosh','acosh',
'tan','tanh','arctan','atan','arctanh','atanh',
'sqrt','abs','ln','log')

Definition at line 97 of file class.EvalMath.php.

◆ $last_error

EvalMath::$last_error = null

Definition at line 92 of file class.EvalMath.php.

◆ $suppress_errors

EvalMath::$suppress_errors = false

Definition at line 91 of file class.EvalMath.php.

◆ $v

EvalMath::$v = array('e'=>2.71,'pi'=>3.14)

Definition at line 94 of file class.EvalMath.php.

Referenced by vars().

◆ $vb

EvalMath::$vb = array('e', 'pi')

Definition at line 96 of file class.EvalMath.php.


The documentation for this class was generated from the following file: