private List <EquationComponent> ParseExpression(string expression) { List <EquationComponent> result = new List <EquationComponent>(); string currentValue = string.Empty; string currentFunction = string.Empty; char last = ' '; for (int i = 0; i < expression.Length; i++) { char c = expression[i]; if (char.IsNumber(c) || c == '.' || c == 'e' || (last == 'e' && (c == '-' || c == '+'))) { currentValue += c; } else if (char.IsLetter(c)) { currentFunction += c; } else { if (currentValue != string.Empty) { result.Add(new EquationComponent(Precedence.Number, currentValue)); } if (currentFunction != string.Empty) { result.Add(new EquationComponent(Precedence.Function, currentFunction.ToLower())); } currentFunction = string.Empty; currentValue = string.Empty; if (c != ' ') { Precedence previous = Precedence.None; if (result.Count > 0) { previous = result.Last().ComponentType; } Precedence currentPrecedence = EquationComponent.GetComponentType(c.ToString(), previous); if (currentPrecedence == Precedence.Negation && previous == Precedence.Negation) { result.Remove(result.Last()); if (result.Last().Component != "+") { result.Add(new EquationComponent(Precedence.AdditionSubtraction, "+")); } } else { result.Add(new EquationComponent(currentPrecedence, c.ToString())); } } } last = c; } if (currentValue != string.Empty) { result.Add(new EquationComponent(Precedence.Number, currentValue)); } if (currentFunction != string.Empty) { result.Add(new EquationComponent(Precedence.Function, currentFunction.ToLower())); } return(result); }
private double PerformOperation(Stack <double> operands, EquationComponent item) { double op2 = 0; double op1 = 0; switch (item.Component) { case "&": op2 = operands.Pop(); op1 = operands.Pop(); return(Math.Pow(op1, op2)); case "*": op2 = operands.Pop(); op1 = operands.Pop(); return(op1 * op2); case "/": op2 = operands.Pop(); op1 = operands.Pop(); return(op1 / op2); case "+": op2 = operands.Pop(); op1 = operands.Pop(); return(op1 + op2); case "-": if (item.ComponentType == Precedence.Negation) { op1 = operands.Pop(); return(op1 * -1); } else { op2 = operands.Pop(); op1 = operands.Pop(); return(op1 - op2); } case "log": op1 = operands.Pop(); return(Math.Log(op1)); case "ln": op1 = operands.Pop(); return(Math.Log(op1)); case "exp": op1 = operands.Pop(); return(Math.Exp(op1)); case "sqrt": op1 = operands.Pop(); return(Math.Sqrt(op1)); case "abs": op1 = operands.Pop(); return(Math.Abs(op1)); case "atan": op1 = operands.Pop(); return(Math.Atan(op1)); case "acos": op1 = operands.Pop(); return(Math.Acos(op1)); case "asin": op1 = operands.Pop(); return(Math.Asin(op1)); case "sinh": op1 = operands.Pop(); return(Math.Sinh(op1)); case "cosh": op1 = operands.Pop(); return(Math.Cosh(op1)); case "tanh": op1 = operands.Pop(); return(Math.Tanh(op1)); case "tan": op1 = operands.Pop(); return(Math.Tan(op1)); case "sin": op1 = operands.Pop(); return(Math.Sin(op1)); case "cos": op1 = operands.Pop(); return(Math.Cos(op1)); } return(double.NaN); }