# parsingmathexpression式

` `Expression e = new Expression("1 + pi"); double v = e.calculate();` `

` `Argument x = new Argument("x = 2"); Constant a = new Constant("a = sin(10)"); Function f = new Function("f(t) = t^2"); Expression e = new Expression("2*x + a - f(10)", x, a, f); double v = e.calculate();` `

Spring.NET框架的expression式评估function是您可能想要考虑的另一个选项。 它可以做比math更多的事情。

` ` Mathos.Parser.MathParser parser = new Mathos.Parser.MathParser(); string expr = "(x+(2*x)/(1-x))"; // the expression decimal result = 0; // the storage of the result parser.LocalVariables.Add("x", 41); // 41 is the value of x result = parser.Parse(expr); // parsing Console.WriteLine(result); // 38.95` `

` `// parse string to IExpression (symbolic type) IExpression expression = BaseExpression.Parse("(x+(2*x)/(1-x))"); // create your own collection for attributes var attributes = new MathAttributeCollection(); // create local variable named "x" with value 5 var attributeX = new ScalarAttrInt("x") {Value = new ScalarConstInt(5)}; attributes.Add(attributeX); // execute math expression where x=5 var result = expression.Execute(attributes); MessageBox.Show(result.GetText()); // result: 2.5` `

` `public class ExpressionParser { public double eval(String exp, Map<String, Double> vars){ int bracketCounter = 0; int operatorIndex = -1; for(int i=0; i<exp.length(); i++){ char c = exp.charAt(i); if(c == '(') bracketCounter++; else if(c == ')') bracketCounter--; else if((c == '+' || c == '-') && bracketCounter == 0){ operatorIndex = i; break; } else if((c == '*' || c == '/') && bracketCounter == 0 && operatorIndex < 0){ operatorIndex = i; } } if(operatorIndex < 0){ exp = exp.trim(); if(exp.charAt(0) == '(' && exp.charAt(exp.length()-1) == ')') return eval(exp.substring(1, exp.length()-1), vars); else if(vars.containsKey(exp)) return vars.get(exp); else return Double.parseDouble(exp); } else{ switch(exp.charAt(operatorIndex)){ case '+': return eval(exp.substring(0, operatorIndex), vars) + eval(exp.substring(operatorIndex+1), vars); case '-': return eval(exp.substring(0, operatorIndex), vars) - eval(exp.substring(operatorIndex+1), vars); case '*': return eval(exp.substring(0, operatorIndex), vars) * eval(exp.substring(operatorIndex+1), vars); case '/': return eval(exp.substring(0, operatorIndex), vars) / eval(exp.substring(operatorIndex+1), vars); } } return 0; }` `

}

` ` ExpressionParser p = new ExpressionParser(); Map vars = new HashMap<String, Double>(); vars.put("x", 2.50); System.out.println(p.eval(" 5 + 6 * x - 1", vars));` `