public static double get_value(IGetVariable p, string s) { if (char.IsLetter(s, 0)) { return(p.GetVariable(s)); } else { return(double.Parse(s)); } }
public double GetValue(IGetVariable gv) { if (user) { return(val); } else { return(Expr.Evaluate(expr, gv)); } }
public static double Evaluate(string s, IGetVariable p) { string[] toks = lex(s); Stack <string> stk = new Stack <string>(); Stack <double> stk2 = new Stack <double>(); for (int i = 0; i < toks.Length; i++) { string t = toks[i]; string tnext = null; string tprev = null; if ((i + 1) < toks.Length) { tnext = toks[i + 1]; } if (i > 0) { tprev = toks[i - 1]; } if (t == "(") { stk.Push(t); } else if (t == ")") { while (true) { if (stk.Count == 0) { throw new Exception("Unbalanced paren"); } string q = (string)stk.Pop(); if (q == "(") { break; } else { do_op(stk2, q); } } } else if (is_operand(t)) { stk2.Push(get_value(p, t)); } else if ( (t == "-") && (tnext != null) && (is_operand(tnext)) && ( is_operator(tprev) || ( (stk.Count == 0) && (stk2.Count == 0) ) ) ) { stk2.Push(-get_value(p, tnext)); i++; } else { Debug.Assert(is_operator(t)); do { if (stk.Count == 0) { stk.Push(t); break; } else if (((string)stk.Peek()) == "(") { stk.Push(t); break; } else if (op_precedence(t) > op_precedence((string)stk.Peek())) { stk.Push(t); break; } else { do_op(stk2, (string)stk.Pop()); } } while (true); } } while (stk.Count > 0) { do_op(stk2, (string)stk.Pop()); } double result = (double)stk2.Pop(); if (stk2.Count > 0) { throw new Exception("Stack should be empty at the end of the expression"); } return(result); }