public void DetailedSpeedTestWithOptimization() { var mp = new MathParser(); mp.LocalVariables.Add("x", 5); var expr = "(3x+2)(2(2x+1))"; int itr = 3000; double creationTimeAndTokenization = BenchmarkUtil.Benchmark(() => mp.GetTokens(expr), 1); var tokens = mp.GetTokens(expr); double parsingTime = BenchmarkUtil.Benchmark(() => mp.Parse(tokens), itr); double totalTime = creationTimeAndTokenization + parsingTime; //var mp = new MathParser(); //mp.LocalVariables.Add("x", 5); //var expr = "(3x+2)(2(2x+1))"; //int itr = 50; double parsingTime2 = BenchmarkUtil.Benchmark(() => mp.Parse(expr), itr); double totalTime2 = parsingTime2; }
public void CustomFunctionsWithSeveralArguments() { /* * This example demonstrates the "anonymous method" way of adding * a function that can take more than one agument. */ var parser = new MathParser(false); parser.LocalFunctions.Add("log", delegate(double[] input) { // input[0] is the number // input[1] is the base if (input.Length == 1) { return(Math.Log(input[0])); } if (input.Length == 2) { return(Math.Log(input[0], input[1])); } return(0); }); Assert.AreEqual(0.693147181, parser.Parse("log(2)"), 0.000000001); Assert.AreEqual(0.63093, parser.Parse("log(2,3)"), 0.000001); }
public void CustomFunctions() { /* * This test demonstrates three ways of adding a function * to the Math Parser * * 1) directly pointing to the function * 2) lambda expression * 3) anonymous method */ MathParser parser = new MathParser(); //for long functions parser.LocalFunctions.Add("numberTimesTwo", NumberTimesTwoCustomFunction); // adding the function decimal resultA = parser.Parse("numberTimesTwo(3)"); //for short functions, use lambda expression, or anonymous method // 1) using lambda epxression (recommended) parser.LocalFunctions.Add("square", x => x[0] * x[0]); decimal resultB = parser.Parse("square(4)"); // 2) using anonymous method parser.LocalFunctions.Add("cube", delegate(decimal[] x) { return(x[0] * x[0] * x[0]); }); decimal resultC = parser.Parse("cube(2)"); }
public void ExceptionCatching() { var parser = new MathParser(); parser.Parse("(-1"); parser.Parse("rem(20,1,,,,)"); }
public void BuiltInFunctions() { var parser = new MathParser(); Assert.AreEqual(21, parser.Parse("round(21.333333333333)")); Assert.AreEqual(1, parser.Parse("pow(2,0)")); }
public void CustomFunctionsWithSeverelArguments() { /* * This example demonstrates the "anonymous method" way of adding * a function that can take more than one agument. */ MathParser parser = new MathParser(loadPreDefinedFunctions: false); //for long functions parser.LocalFunctions.Add("log", delegate(decimal[] input) // adding the function { // input[0] is the number // input[1] is the base if (input.Length == 1) { return((decimal)Math.Log((double)input[0])); } else if (input.Length == 2) { return((decimal)Math.Log((double)input[0], (double)input[1])); } else { return(0); // false } }); decimal resultA = parser.Parse("log(2)"); decimal resultB = parser.Parse("log(2,3)"); }
private double ParseCoefficient(string expression, string variable, List <string> variables) { var parser = new MathParser(); var variablePosition = expression.IndexOf(variable, StringComparison.Ordinal); if (variablePosition == 0) { return(1); } var leftVariables = variables .Where(x => x != variable && expression.Contains(x) && variablePosition - expression.IndexOf(x, StringComparison.Ordinal) > 0) .OrderBy(x => variablePosition - expression.IndexOf(x, StringComparison.Ordinal)); if (!leftVariables.Any()) { return((double)parser.Parse(expression.Substring(0, expression.IndexOf(variable, StringComparison.Ordinal)))); } var leftVariable = leftVariables.First(); var leftVariablePosition = expression.IndexOf(leftVariable, StringComparison.Ordinal); var str = leftVariablePosition < 0 ? expression.Substring(0, expression.IndexOf(variable, StringComparison.Ordinal)) : expression.Substring(leftVariablePosition + 2, variablePosition - leftVariablePosition - 2); if (str.Length == 1) { return(1); } return((double)parser.Parse(str)); }
public void BasicArithmetics() { var parser = new MathParser(); Assert.AreEqual(7, parser.Parse("5+2")); Assert.AreEqual(11, parser.Parse("5+2*3")); }
public void AdvancedArithmetic() { var parser = new MathParser(); Assert.AreEqual(30, parser.Parse("3(7+3)")); Assert.AreEqual(20, parser.Parse("(2+3)(3+1)")); }
public void CustomFunctions() { /* * This test demonstrates three ways of adding a function * to the Math Parser * * 1) directly pointing to the function * 2) lambda expression * 3) anonymous method */ var parser = new MathParser(); parser.LocalFunctions.Add("numberTimesTwo", NumberTimesTwo); Assert.AreEqual(6, parser.Parse("numberTimesTwo(3)")); parser.LocalFunctions.Add("square", x => x[0] * x[0]); Assert.AreEqual(16, parser.Parse("square(4)")); parser.LocalFunctions.Add("cube", delegate(double[] x) { return(x[0] * x[0] * x[0]); }); Assert.AreEqual(8, parser.Parse("cube(2)")); }
public void BasicArithmetic() { var parser = new MathParser(); Assert.AreEqual(7, parser.Parse("5 + 2")); Assert.AreEqual(11, parser.Parse("5 + 2 * 3")); Assert.AreEqual(17, parser.Parse("27 - 3 * 3 + 1 - 4 / 2")); Assert.AreEqual(282429536481, parser.Parse("(27 ^ 2) ^ 4")); }
public void NoLeadingZero() { var parser = new MathParser(); Assert.AreEqual(0.5, parser.Parse(".5")); Assert.AreEqual(0.5, parser.Parse(".25 + .25")); Assert.AreEqual(2.0, parser.Parse("1.5 + .5")); Assert.AreEqual(-0.25, parser.Parse(".25 + (-.5)")); Assert.AreEqual(0.25, parser.Parse(".5(.5)")); }
public void ConditionStatements() { var parser = new MathParser(); Assert.AreEqual(1, parser.Parse("2 + 3 = 1 + 4")); Assert.AreEqual(1, parser.Parse("3 + 2 > (2 - 1)")); Assert.AreEqual(0, parser.Parse("2 + 2 = 22")); Assert.AreEqual(0, parser.Parse("10 > 100")); }
private double TestCongThuc(DataRow drDiem, DataRow[] arrDrDiem, string CongThucDiem, string IDThanhPhanThi, int IDKQHT_ThanhPhanTBHS, int LanThi) { double Value = 0; int SoSauDauPhay; try { MathParser parser = new MathParser(); parser.CreateVar("TBHS", double.Parse("0" + drDiem[IDKQHT_ThanhPhanTBHS.ToString() + "_" + LanThi.ToString()]), null); parser.CreateVar("THI", double.Parse("0" + drDiem[IDThanhPhanThi + "_" + LanThi.ToString()]), null); foreach (DataRow dr in arrDrDiem) { if (!(dr["KyHieu"].ToString() == "TBHS" || dr["KyHieu"].ToString() == "THI")) { parser.CreateVar(dr["KyHieu"].ToString(), double.Parse("0" + dr["TongDiem"]), null); parser.CreateVar("Count" + dr["KyHieu"], int.Parse("0" + dr["SoDiem"]), null); } } string formula = CongThucDiem; parser.OptimizationOn = true; if (formula.IndexOf("R+(") == 0 | formula.IndexOf("R-(") == 0) { SoSauDauPhay = int.Parse(formula.Substring(3, 1)); double tmp = 0; if (formula.IndexOf("R+(") == 0) { formula = formula.Substring(5, formula.Length - 5); parser.Expression = formula; parser.Parse(); tmp = double.Parse(parser.Value.ToString()); Value = parser.Round(tmp, SoSauDauPhay, true); } else { formula = formula.Substring(5, formula.Length - 5); parser.Expression = formula; parser.Parse(); tmp = double.Parse(parser.Value.ToString()); Value = parser.Round(tmp, SoSauDauPhay, false); } } else { parser.Expression = formula; parser.Parse(); Value = double.Parse(parser.Value.ToString()); } return(Value); } catch (Exception) { return(0); } }
public void NegativeNumbers() { var parser = new MathParser(); Assert.AreEqual(0, parser.Parse("-1+1")); Assert.AreEqual(1, parser.Parse("--1")); Assert.AreEqual(-2, parser.Parse("-2")); Assert.AreEqual(-2, parser.Parse("(-2)")); // Assert.AreEqual(2, parser.Parse("-(-2)")); TODO: Fix Assert.AreEqual(4, parser.Parse("(-2)(-2)")); }
public void BuiltInFunctions() { MathParser parser = new MathParser(loadPreDefinedFunctions: true); decimal result = parser.Parse("round(21.333333333333)"); Assert.AreEqual(result, 21); decimal result2 = parser.Parse("pow(2,0)"); Assert.AreEqual(result2, 1); }
public void BasicArithmetics() { MathParser parser = new MathParser(); decimal resultA = parser.Parse("5+2"); Assert.IsTrue(resultA == 7); decimal resultB = parser.Parse("5+2*3"); Assert.IsTrue(resultB == 11); }
public void ConditionStatements() { MathParser parser = new MathParser(); decimal resultA = parser.Parse("2+3=1+4"); Assert.IsTrue(resultA == 1); decimal resultB = parser.Parse("3+2>(2-1)"); Assert.IsTrue(resultB == 1); }
public void SpeedTests() { var parser = new MathParser(); parser.LocalVariables.Add("x", 10); var list = parser.GetTokens("(3x+2)"); var time = BenchmarkUtil.Benchmark(() => parser.Parse("(3x+2)"), 25000); var time2 = BenchmarkUtil.Benchmark(() => parser.Parse(list), 25000); Assert.IsTrue(time >= time2); }
public void ProgramicallyAddVariables() { var parser = new MathParser(); parser.ProgrammaticallyParse("let a = 2pi"); Assert.AreEqual(parser.LocalVariables["pi"] * 2, parser.Parse("a"), 0.00000000000001); parser.ProgrammaticallyParse("b := 20"); Assert.AreEqual(20, parser.Parse("b")); parser.ProgrammaticallyParse("let c be 25 + 2(2+3)"); Assert.AreEqual(35, parser.Parse("c")); }
public void DecimalOperations() { //MathParser parser = new MathParser(new CultureInfo("sv-SE")); // uses "," as a decimal separator //decimal resultA = parser.Parse("0,245 + 0,3"); //decimal resultB = parser.Parse("-0,245 + 0,3"); //Assert.IsTrue(resultB == decimal.Parse("0,055", new CultureInfo("sv-SE"))); MathParser parserDefault = new MathParser(); // or new MathParser(new CultureInfo("en-US")) decimal resultC = parserDefault.Parse("0.245 + 0.3"); decimal resultD = parserDefault.Parse("-0.245 + 0.3"); Assert.IsTrue(resultD == decimal.Parse("0.055", parserDefault.CultureInfo)); }
public void ExceptionCatching() { MathParser parser = new MathParser(); try { decimal result = parser.Parse("(-1"); Assert.Fail(); // fail if the above expression hasn't thrown an exception } catch (ArithmeticException) { } decimal tr = parser.Parse("rem(20,1,,,,)"); }
public void CustomFunctions() { var parser = new MathParser(); parser.LocalFunctions.Add("timesTwo", inputs => inputs[0] * 2); Assert.AreEqual(6, parser.Parse("timesTwo(3)")); Assert.AreEqual(42, parser.Parse("timesTwo((2+3)(3+1) + 1)")); parser.LocalFunctions.Add("square", inputs => inputs[0] * inputs[0]); Assert.AreEqual(16, parser.Parse("square(4)")); parser.LocalFunctions.Add("cube", inputs => inputs[0] * inputs[0] * inputs[0]); Assert.AreEqual(8, parser.Parse("cube(2)")); }
private double TestCongThuc(double DiemTBMH, DataRow[] drDiem) { double Value = 0; int SoSauDauPhay; try { // add thanh phan diem TBTK parser.CreateVar("TBTK", DiemTBMH, null); foreach (DataRow dr in drDiem) { parser.CreateVar(dr["MaMonHoc"].ToString(), double.Parse("0" + dr["Diem"].ToString()), null); } string formula = null; formula = strCongThucDiem; parser.OptimizationOn = true; if (formula.IndexOf("R+(") == 0 | formula.IndexOf("R-(") == 0) { SoSauDauPhay = int.Parse(formula.Substring(3, 1)); double tmp = 0; if (formula.IndexOf("R+(") == 0) { formula = formula.Substring(5, formula.Length - 5); parser.Expression = formula; parser.Parse(); tmp = double.Parse(parser.Value.ToString()); Value = parser.Round(tmp, SoSauDauPhay, true); } else { formula = formula.Substring(5, formula.Length - 5); parser.Expression = formula; parser.Parse(); tmp = double.Parse(parser.Value.ToString()); Value = parser.Round(tmp, SoSauDauPhay, false); } } else { parser.Expression = formula; parser.Parse(); Value = double.Parse(parser.Value.ToString()); } return(Value); } catch (Exception) { return(0); } }
public void ExecutionTime() { Stopwatch _timer = new Stopwatch(); _timer.Start(); MathParser parser = new MathParser(); decimal result = parser.Parse("5+2"); decimal result2 = parser.Parse("5+2*3*1+2((1-2)(2-3))"); decimal result3 = parser.Parse("5+2*3*1+2((1-2)(2-3))*-1"); _timer.Stop(); Debug.WriteLine("time to parser with MathParser: " + _timer.ElapsedMilliseconds); }
private double TestCongThuc(DataRow[] drDiem) { double Value = 0; int SoSauDauPhay; try { MathParser parser = new MathParser(); foreach (DataRow dr in drDiem) { parser.CreateVar(dr["KyHieu"].ToString(), double.Parse("0" + dr["Diem"].ToString()), null); } string formula = null; formula = drDiem[0]["CongThuc"].ToString(); parser.OptimizationOn = true; if (formula.IndexOf("R+(") == 0 | formula.IndexOf("R-(") == 0) { SoSauDauPhay = int.Parse(formula.Substring(3, 1)); double tmp = 0; if (formula.IndexOf("R+(") == 0) { formula = formula.Substring(5, formula.Length - 5); parser.Expression = formula; parser.Parse(); tmp = double.Parse(parser.Value.ToString()); Value = parser.Round(tmp, SoSauDauPhay, true); } else { formula = formula.Substring(5, formula.Length - 5); parser.Expression = formula; parser.Parse(); tmp = double.Parse(parser.Value.ToString()); Value = parser.Round(tmp, SoSauDauPhay, false); } } else { parser.Expression = formula; parser.Parse(); Value = double.Parse(parser.Value.ToString()); } return(Value); } catch (Exception) { return(0); } }
public void Parse() { var node = MathParser.Parse("3+3=2*3"); node = MathParser.Parse("sqrt(x) * sqrt(x) = 7"); node = MathParser.Parse("4 * x + 3 = 19"); }
public static double Integral(string Expression, double LowerIndex, double UpperIndex, char IterationVariable, int Kind) { var parser = new MathParser(); var Var = new Variable<double>(IterationVariable.ToString()); parser.Variables.Add(Var); parser.Parse(Expression); Func<double,double> proc = x => { Var.Value = x; return parser.Evaluate(); }; switch (Kind) { case 0: return Integration.Trapezoidal(LowerIndex, UpperIndex, proc); case 1: return Integration.LeftHand(LowerIndex, UpperIndex, proc); default: return Integration.MidPoint(LowerIndex, UpperIndex, proc); } }
// Desarrolla los valores de a_k hasta el n_i máximo, permitiendo que se ingresen desde ningún valor de n_i hasta 3. private void CreateA_nValues() { var temp = 0; bool pudo = false; foreach (var i in enes.Lines) { pudo = int.TryParse(i, out temp); if (pudo) { n.Add(temp); } } int max = int.MinValue; for (int i = 0; i < n.Count; i++) { if (n[i] > max) { max = n[i]; } } for (int i = 0; i <= max; i++) { string exp = input.Text.Replace("n", "" + i); a_nValues.Add((float)parser.Parse(exp)); } }
public void CommaPiBug() { var parser = new MathParser(); var result = parser.Parse("pi"); Assert.AreEqual(result, parser.LocalVariables["pi"], 0.00000000000001); }
public static double CalcStringFormula(List <string> Formulas) { double val = 0; if (Formulas != null) { if (parser == null) { parser = new MathParser(); } foreach (string f in Formulas) { if (string.IsNullOrEmpty(f)) { continue; } string F = f.Replace("\n", "").Replace("\r", "").Replace("\t", ""); double v = parser.Parse(F, new System.Collections.Hashtable()); if (double.IsInfinity(v) || double.IsNaN(v)) { v = 0; } val += v; } } return(val); }
public static void DumpTree(string mathCode) { Expression expression; var tokenizer = new MathTokenizer(); var parser = new MathParser(); using (var reader = new StringReader(mathCode)) { var tokens = tokenizer.Tokenize(reader); expression = parser.Parse(tokens); } Console.WriteLine(expression.ToString()); }
public ConsoleMathTypeChecker() { parser = new MathParser(); parser.Factory = factory = new MathFactory(); parser.OnReduction += OnReduction; parser.OnCompletion += OnCompletion; parser.OnGroupError += OnGroupError; parser.OnInternalError += OnInternalError; parser.OnNotLoadedError += OnNotLoadedError; parser.OnLexicalError += OnLexicalError; parser.OnSyntaxError += OnSyntaxError; Assembly a = typeof(ConsoleMathTypeChecker).Assembly; parser.LoadGrammar(new BinaryReader(a.GetManifestResourceStream("QL_ExtensionTest.Grammar.QL_Grammar.egt"))); parser.Parse("form Form1 { \"Power:\" << answer1:int = 5 ^ 2; \"Modulo:\" << 10 % 5; \"Modulo2:\" << 10 % true; }"); }
public static MathValue InterpretSingle(string mathCode) { Expression expression; var tokenizer = new MathTokenizer(); var parser = new MathParser(); using (var reader = new StringReader(mathCode)) { var tokens = tokenizer.Tokenize(reader); expression = parser.Parse(tokens); } var context = CreateGlobalContext(); var result = expression.Evaluate(context); return result; }
public static double Sigma(string Expression, double LowerIndex, double UpperIndex, char IterationVariable, double Step) { double Result = 0; var parser = new MathParser(); var Var = new Variable<double>(IterationVariable.ToString()); parser.Variables.Add(Var); parser.Parse(Expression); for (var i = LowerIndex; i <= UpperIndex; i += Step) { Var.Value = i; Result += parser.Evaluate(); } return Result; }