# Equation Parser

**URL:** https://forum.kirupa.com/t/equation-parser/217268
**Category:** open source
**Created:** [February 25, 2007, 12:05am UTC](https://forum.kirupa.com/t/equation-parser/217268 "2007-02-25T00:05:45Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![TheCanadian](https://avatars.discourse-cdn.com/v4/letter/t/67e7ee/32.png) [@TheCanadian](https://forum.kirupa.com/u/TheCanadian)
#### Post date: [February 25, 2007, 12:05am UTC](https://forum.kirupa.com/t/equation-parser/217268/1 "2007-02-25T00:05:45Z")

</div>

This class will take a function of x as a string and then evaluates that equation at a value. This class requires my extended math class which can be found here:

> **[kirupaForum](https://forum.kirupa.com)**
>
> Got a web design/development question or just want to hang out with the most awesome people on the planet? Drop on in!

**The Class:**

```auto
package {
 public class Equation extends Object {
  
  private static const PAREN_PATTERN:RegExp = /(?:\(|^)([^()]+)(?:\)|$)/;
  private static const VARIABLE_PATTERN:RegExp = /[xpie]{1,2}/g;
  private static const FUNCTION_PATTERN:RegExp = /([a-z]+)\(([^\(\)]+)\)/;
  private static const POWER_PATTERN:RegExp = /(-?\d+(?:\.\d+)?)([\^])(-?\d+(?:\.\d+)?)/;
  private static const MUL_DIV_PATTERN:RegExp = /(-?\d+(?:\.\d+)?)([*\/%])(-?\d+(?:\.\d+)?)/;
  private static const ADD_SUB_PATTERN:RegExp = /(-?\d+(?:\.\d+)?)([+\-])(-?\d+(?:\.\d+)?)/;
  
  private var currX:Number;
  
  public var equation:String;
  
  public function Equation(eq:String) {
   this.equation = eq;
  }
  public function evaluate(x:Number = 0):Number {
   this.currX = x;
   var eq:String = this.equation.split(" ").join("");
   while(Equation.FUNCTION_PATTERN.test(eq)) {
    eq = eq.replace(Equation.FUNCTION_PATTERN, this.evaluateFunction);
   }
   eq = eq.replace(Equation.VARIABLE_PATTERN, this.evaluateVariable);
   while(isNaN(Number(eq))) {
    eq = eq.replace(Equation.PAREN_PATTERN, this.recursiveEvaluation(Equation.PAREN_PATTERN.exec(eq)[1]));
   }
   return Number(eq);
  }
  private function evaluateVariable(match:String, index:uint, original:String):String {
   var r:Number;
   switch(match) {
    case "x" :
     r = this.currX;
     break;
    case "pi" :
     r = MathExt.PI;
     break;
    case "e" :
     r = MathExt.E;
     break;
   }  
   return String(r);
  }
  private function evaluateFunction(match:String, f:String, a:String, index:uint, original:String):String {
   var args:Array = a.split(",");     
   for(var i:Number = 0; i < args.length; i++) {
    args* = new Equation(args*).evaluate(this.currX);
   }
   return String(MathExt[f].apply(null, args).toFixed(20));
  }
  private function evaluateOperation(match:String, a:String, o:String, b:String, index:uint, original:String):String {
   var an:Number = Number(a);
   var bn:Number = Number(b);
   var r:Number;
   switch(o) {
    case "^" :
     r = Math.pow(an, bn);
     break;
    case "*" :
     r = an * bn;
     break;
    case "/" : 
     r = an / bn;
     break;
    case "%" :
     r = an % bn;
     break;
    case "+" :
     r = an + bn;
     break
    case "-" :
     r = an - bn;
     break;
   }
   return String(r.toFixed(20));
  }
  private function recursiveEvaluation(eq:String):String {
   while(Equation.POWER_PATTERN.test(eq)) {
    eq = eq.replace(Equation.POWER_PATTERN, this.evaluateOperation);
   }
   while(Equation.MUL_DIV_PATTERN.test(eq)) {
    eq = eq.replace(Equation.MUL_DIV_PATTERN, this.evaluateOperation);
   }
   while(Equation.ADD_SUB_PATTERN.test(eq)) {    
    eq = eq.replace(Equation.ADD_SUB_PATTERN, this.evaluateOperation);
   }
   return eq;
  }
 }
}

```

**Currently Supports:**  
[LIST]  
[_]Simple arithmetic operations including addition, subtraction, multiplication and division  
[_]More complex operations including modulus  
[_]Powers written as a^b  
[_]Parenthetical grouping  
[_]X as a variable  
[_]Multi-argument mathematical functions from my [MathExt class](http://www.kirupa.com/forum/showthread.php?p=2071909#post2071909) including sin, cos, tan, asin, acos, atan, csc, sec, cot, acsc, asec, acot, log, ln, sqrt, root, pow, exp, abs, round, ceil, floor, gcd, lcm, random, factorial, perm and comb  
[\*]Mathematical constants including pi and e  
[/LIST]

**To Do:**  
[list]  
[_]Support for degree constant (pi/180)  
[_]Allow the use of pipes | to denote absolute value expressions  
[\*]Support for factorials denoted by !  
[/list]

**Examples:**

Simple Arithmetic:

```auto
var eq:Equation = new Equation("x+x*x-x/x");
trace(eq.evaluate(2)); //5

```

Parenthetical Grouping:

```auto
var eq:Equation = new Equation("(x+x)*(x-x)/x");
trace(eq.evaluate(2)); //0

```

Powers:

```auto
var eq:Equation = new Equation("x^(1/2)");
trace(eq.evaluate(9)); //3

```

Math Functions and Constants:

```auto
var eq:Equation = new Equation("root(abs(cos(pi)-ln(e))*4,3)");
trace(eq.evaluate()); //2

```

If you have a questions, suggestions or errors please feel free to post. I hope this is useful to some people :hoser:
