Esempio n. 1
0
        private decimal IntegrateUsingSimpsonsRule(
            string expression,
            decimal lowerLimit,
            decimal upperLimit,
            decimal numberOfIntervals = 100000)
        {
            var parser         = new MathParser();
            var sizeOfInterval = (upperLimit - lowerLimit) / numberOfIntervals;

            parser.LocalVariables["x"] = lowerLimit;

            var sum = parser.ProgrammaticallyParse(expression);

            for (var i = 1; i < numberOfIntervals; i += 2)
            {
                parser.LocalVariables["x"] = lowerLimit + sizeOfInterval * i;
                sum += 4 * parser.ProgrammaticallyParse(expression);
            }

            for (var i = 2; i < numberOfIntervals - 1; i += 2)
            {
                parser.LocalVariables["x"] = lowerLimit + sizeOfInterval * i;
                sum += 2 * parser.ProgrammaticallyParse(expression);
            }

            parser.LocalVariables["x"] = upperLimit;
            sum += parser.ProgrammaticallyParse(expression);

            var result = sum * sizeOfInterval / 3;

            return(result);
        }
Esempio n. 2
0
        private decimal IntegrateUsingTrapezoidalRule(
            string expression,
            decimal lowerLimit,
            decimal upperLimit,
            decimal numberOfIntervals = 100000)
        {
            var parser         = new MathParser();
            var sizeOfInterval = (upperLimit - lowerLimit) / numberOfIntervals;

            parser.LocalVariables["x"] = lowerLimit;
            var sum = parser.ProgrammaticallyParse(expression);

            parser.LocalVariables["x"] = upperLimit;
            sum += parser.ProgrammaticallyParse(expression);

            for (var i = 1; i < numberOfIntervals; i++)
            {
                parser.LocalVariables["x"] = lowerLimit + i * sizeOfInterval;
                sum += parser.ProgrammaticallyParse(expression) * 2;
            }

            var result = sum * sizeOfInterval / 2;

            return(result);
        }
Esempio n. 3
0
        public void BooleanVariables()
        {
            // x = 12
            mathParser.ProgrammaticallyParse("let x = (5^2 - 1) / 2");

            Assert.AreEqual(parser.ProgrammaticallyParse("let y = 0"), 0);

            Assert.AreEqual(parser.ProgrammaticallyParse("x == 12"), 1);
            Assert.AreEqual(parser.ProgrammaticallyParse("x % 2 == 0 && x % 3 == 0 && x % 4 == 0"), 1);
            Assert.AreEqual(parser.ProgrammaticallyParse("x && y"), 0);
            Assert.AreEqual(parser.ProgrammaticallyParse("x || y"), 1);
        }
Esempio n. 4
0
        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"));
        }
Esempio n. 5
0
        public void Run()
        {
            ResultsWindow.Open();

            var lineNumber = 1;
            var builder    = new StringBuilder();

            foreach (var line in _editor.Text.Split(new [] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
            {
                if (line.Trim().Length == 0)
                {
                    continue;
                }

                try
                {
                    builder.AppendLine(_parser.ProgrammaticallyParse(line).ToString(CultureInfo.InvariantCulture));
                }
                catch (Exception e)
                {
                    builder.AppendLine("ERROR (Line " + lineNumber + ") : " + e.Message);
                }

                lineNumber++;
            }

            ResultsWindow.Instance.Results.Text = builder.ToString();
        }
Esempio n. 6
0
        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            // create a variable list at the RHS
            try
            {
                switch (e.Key)
                {
                case Key.Enter:
                    ListView1.Items.Add(TextBox1.Text);
                    ListView1.Items.Add(_parser.ProgrammaticallyParse(TextBox1.Text).ToString(new CultureInfo("en-US")));
                    TextBox1.Text = "";
                    break;

                default:
                    return;
                }
            }
            catch (Exception ex)
            {
                ListView1.Items.Add(ex.Message);

                TextBox1.Text = "";
            }
            finally
            {
                if (e.Key == Key.Enter)
                {
                    ListView1.ScrollIntoView(ListView1.Items.Count);
                    DataGrid1.Items.Refresh();
                }
            }
        }
        public void ProgramicallyAddVariables()
        {
            /*
             * when parsing an expression that requires,
             * for instance, a variable name declaration
             * or change, use ProgramaticallyParse().
             */
            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");
            Assert.AreEqual(25, parser.Parse("c"));
        }
Esempio n. 8
0
        private static double EvaluateExpression(string expression, double x)
        {
            var parser = new MathParser {
                LocalVariables = { ["x"] = (decimal)x }
            };

            var result = parser.ProgrammaticallyParse(expression);

            return((double)result);
        }
Esempio n. 9
0
        public double EvaluarLambda(double x)
        {
            string s = Funcion;

            MathParser parser = new MathParser();

            parser.LocalVariables["x"] = (decimal)x;
            parser.LocalVariables["e"] = (decimal)Math.E;

            parser.LocalFunctions.Add("Cos", delegate(decimal[] n)
            {
                return((decimal)Math.Cos((double)n[0]));
            });

            parser.LocalFunctions.Add("Sen", delegate(decimal[] n)
            {
                return((decimal)Math.Sin((double)n[0]));
            });

            parser.LocalFunctions.Add("Tan", delegate(decimal[] n)
            {
                return((decimal)Math.Tan((double)n[0]));
            });

            parser.LocalFunctions.Add("Sqrt", delegate(decimal[] n)
            {
                return((decimal)Math.Sqrt((double)n[0]));
            });

            parser.LocalFunctions.Add("Ln", delegate(decimal[] n)
            {
                return((decimal)Math.Log((double)n[0]));
            });

            parser.LocalFunctions.Add("Log", delegate(decimal[] n)
            {
                return((decimal)Math.Log10((double)n[0]));
            });

            parser.LocalFunctions.Add("Atan", delegate(decimal[] n)
            {
                return((decimal)Math.Atan((double)n[0]));
            });

            try
            {
                return((double)parser.ProgrammaticallyParse(s));
            }
            catch (Exception)
            {
                return(0.0);
            }
        }
Esempio n. 10
0
        public void ProgrmaticallyAddVariables()
        {
            /*
             * when parsing an expression that requires
             * for instance a variable name declaration
             * or change, use ProgramaticallyParse().
             */
            MathParser parser = new MathParser();

            // first way, using let varname = value
            decimal resultA = parser.ProgrammaticallyParse("let a = 2pi");

            Assert.IsTrue(parser.Parse("a") == (decimal)Math.PI * 2);

            // second way, using varname :=  value
            decimal resultC = parser.ProgrammaticallyParse("b := 20");

            Assert.IsTrue(parser.Parse("b") == 20);

            // third way, using let varname be value
            decimal resultD = parser.ProgrammaticallyParse("let c be 25");

            Assert.IsTrue(resultD == 25);
        }
Esempio n. 11
0
        public void UndefinedOperatorException()
        {
            var parser = new MathParser();

            try
            {
                parser.ProgrammaticallyParse("unknownoperator(5)");
            }
            catch (Exception e)
            {
                // Tests to see if the message the exception gives is clear enough
                Assert.IsTrue(e.Message.ToLowerInvariant().Contains("operator") && e.Message.ToLowerInvariant().Contains("unknownoperator"));
                throw e;
            }
        }
Esempio n. 12
0
        public void ComparisonOfExpressions()
        {
            //var mp = new MathParser();

            var mp = new MathParser();

            // här har vi det riktiga svaret
            // x kan vara vadsomhelst.
            mp.LocalVariables["x"] = 12;
            var rightValue = mp.ProgrammaticallyParse("3x+2");
            var errorBound = 0.001M;


            var answerAlteratives = new string[] { "3x+2", "3(3x+2)/3", "(6x+4)/2" };

            // kollar igenom svar
            for (int i = 0; i < answerAlteratives.Length; i++)
            {
                if (CheckErrorBound(rightValue, mp.ProgrammaticallyParse(answerAlteratives[i])) > errorBound)
                {
                    Assert.Fail();
                }
            }
        }
Esempio n. 13
0
        public double Evaluate(string expression)
        {
            double output = 0;

            try
            {
                output = parser.ProgrammaticallyParse(expression);
                parser.LocalVariables["_"] = output;
                AddLog(expression, output.ToString());
                outputs.Add(output);
            }
            catch (Exception e)
            {
                AddLog(expression, e.ToString());
                outputs.Add(double.NaN);
            }
            inputs.Add(expression);
            cursor = -1;
            return(output);
        }
Esempio n. 14
0
        private decimal IntegrateUsingRectangleMethod(
            string expression,
            decimal lowerLimit,
            decimal upperLimit,
            decimal numberOfIntervals = 100000)
        {
            decimal sum            = 0;
            var     parser         = new MathParser();
            var     sizeOfInterval = (upperLimit - lowerLimit) / numberOfIntervals;

            for (var i = 0; i < numberOfIntervals; i++)
            {
                parser.LocalVariables["x"] = lowerLimit + sizeOfInterval * i;
                sum += parser.ProgrammaticallyParse(expression) * sizeOfInterval;
            }

            var result = sum;

            return(result);
        }
Esempio n. 15
0
    //this parses mathematical operations and variable value uses
    bool ParseNumbers(string _expression, out double results)
    {
        Dictionary <string, dynamic> vars = new Dictionary <string, dynamic>();
        string _toParse = Regex.Replace(_expression, "(|)", string.Empty);

        string[] _Args = _toParse.Split(new[] { '+', '-', '/', '*' });
        foreach (var item in _Args)
        {
            if (variables.TryGetValue(item, out dynamic value))
            {
                if (vars.ContainsKey(item))
                {
                    break;
                }
                else if (variables[item] is double)
                {
                    vars[item] = variables[item];
                }
                else
                {
                    ThrowError();
                    results = 0;
                    return(false);
                }
            }
        }
        string preParsed = _expression;

        foreach (var item in vars)
        {
            preParsed = Regex.Replace(preParsed, item.Key, item.Value.ToString());
        }
        preParsed = Regex.Replace(preParsed, ",", ".");
        double parsed = Math.ProgrammaticallyParse(preParsed);

        results = parsed;
        return(true);
    }
Esempio n. 16
0
        public decimal Func(decimal x)
        {
            _parser.LocalVariables["x"] = x;

            return(_parser.ProgrammaticallyParse(functionInput.Text));
        }
Esempio n. 17
0
 public string Exec(string expr = "")
 {
     return(_parser.ProgrammaticallyParse(expr).ToString(CultureInfo.InvariantCulture));
 }
Esempio n. 18
0
        /// <summary>
        /// Executes a list of strings as a script, line by line, and returns the last calculated number
        /// </summary>
        /// <param name="linesEnumerable"></param>
        /// <returns></returns>
        public double ExecuteLines(IEnumerable <string> linesEnumerable)
        {
            var lines = linesEnumerable.ToArray();

            double lastOutput = 0;
            Stack <IfChainState> chainStates = new Stack <IfChainState>();
            int lineNumber = 0;

            try
            {
                while (lineNumber < lines.Length)
                {
                    var line = lines[lineNumber].Trim().ToLowerInvariant();
                    if (string.IsNullOrWhiteSpace(line))
                    {
                        lineNumber++;
                        continue;
                    }
                    IfChainState currentState = IfChainState.Executing;
                    if (chainStates.Count > 0)
                    {
                        currentState = chainStates.Peek();
                    }
                    if (line.StartsWith("if"))
                    {
                        if (currentState == IfChainState.Executing)
                        {
                            string condition = line.Substring(line.IndexOf("if") + 2).Trim();
                            var    result    = booleanParser.ProgrammaticallyParse(condition);
                            bool   executeIf = booleanParser.ToBoolean(result);
                            chainStates.Push(executeIf ? IfChainState.Executing : IfChainState.NotExecuted);
                        }
                        else
                        {
                            // The if statement this if statement is in is not executing, so we push executed on the stack to make sure the contents of this don't get executed, and any following if else/else statements don't get executed either
                            chainStates.Push(IfChainState.Executed);
                        }
                    }
                    else if (line.StartsWith("else if") || line.StartsWith("elif"))
                    {
                        var oldState = chainStates.Pop();
                        if (oldState == IfChainState.NotExecuted)
                        {
                            string condition = line.Substring(line.IndexOf("if") + 2).Trim();
                            var    result    = booleanParser.ProgrammaticallyParse(condition);
                            bool   executeIf = booleanParser.ToBoolean(result);
                            chainStates.Push(executeIf ? IfChainState.Executing : IfChainState.NotExecuted);
                        }
                        else
                        {
                            chainStates.Push(IfChainState.Executed);
                        }
                    }
                    else if (line.StartsWith("else"))
                    {
                        var oldState = chainStates.Pop();
                        chainStates.Push(oldState == IfChainState.NotExecuted ? IfChainState.Executing : IfChainState.Executed);
                    }
                    else if (line == "end if" || line == "endif")
                    {
                        chainStates.Pop();
                    }
                    else
                    {
                        if (currentState == IfChainState.Executing)
                        {
                            if (line.StartsWith(LogFunctionName + " ") || line.StartsWith(LogFunctionName + "(") || line.StartsWith(LogFunctionName + "\""))
                            {
                                string logExpression = line.Substring(LogFunctionName.Length).Trim();
                                LogString(logExpression);
                            }
                            else
                            {
                                lastOutput = mathParser.ProgrammaticallyParse(line);
                            }
                        }
                    }
                    lineNumber++;
                }
            }
            catch (Exception e)
            {
                throw new ScriptParserException(lineNumber + 1, e);
            }
            return(lastOutput);
        }