예제 #1
0
        public static void Main(string[] args)
        {
            //MoreLinq
            Console.WriteLine(MoreEnumerable.Random().First());
            //Newtonsoft
            Console.WriteLine(JObject.Parse(@"{""foo"":42}"));
            //Mathnet
            var x = Expr.Symbol("x");

            Console.WriteLine(Infix.Format(x + x));
            //DynamicExpresso
            Console.WriteLine(new Interpreter().Eval("2+2"));
            //NDesk.Options
            Console.WriteLine(new OptionSet {
                { "v", v => {} }
            }.Parse(new[] { "-v", "foo" })[0]);
            //System.Memory
            Console.WriteLine(new Span <int>(new[] { 42 })[0]);
            //System.Collections.Immutable
            Console.WriteLine(new[] { 12 }.ToImmutableArray()[0]);
            //Microsoft.Z3
            try {
                Console.WriteLine($"Z3: {Microsoft.Z3.Version.ToString()}");
            } catch (DllNotFoundException) {
                Console.WriteLine($"Warning, native Z3 library not detected");
            }
        }
예제 #2
0
        public int[][] ConvertLogicToConditional(string Logic)
        {
            string NewLogic = Logic.Replace("&&", "*").Replace("||", "+").Replace("&", "*").Replace("|", "+");
            Dictionary <string, int> LetterToNum = new Dictionary <string, int>();

            foreach (var i in ExtractNumbers(Logic))
            {
                var Letter = IndexToColumn(i + 1);
                LetterToNum.Add(Letter, i);
            }
            LetterToNum = LetterToNum.OrderBy(x => x.Value).Reverse().ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            foreach (var i in LetterToNum)
            {
                //Debugging.Log(i.ToString());
                NewLogic = NewLogic.Replace(i.Value.ToString(), i.Key);
            }
            //Debugging.Log(NewLogic);
            Expression LogicSet      = Infix.ParseOrThrow(NewLogic);
            var        Output        = Algebraic.Expand(LogicSet);
            string     ExpandedLogic = Infix.Format(Output).Replace(" ", "");

            //Debugging.Log(ExpandedLogic);

            foreach (var i in LetterToNum)
            {
                ExpandedLogic = ExpandedLogic.Replace(i.Key, i.Value.ToString());
            }
            ExpandedLogic = HandlePowers(ExpandedLogic.Replace(" ", ""));

            return(ExpandedLogic.Split('+').Select(x => x.Split('*').Select(y => int.Parse(y)).ToArray()).ToArray());
        }
예제 #3
0
        public static string GetFullFormulaOptions([ExcelArgument(AllowReference = true)] object arg, bool replaceRef = false, bool resolveName = false, int decimalPlaces = 5)
        {
            try
            {
                //this removes the volatile flag
                XlCall.Excel(XlCall.xlfVolatile, false);

                ExcelReference theRef = (ExcelReference)arg;
                Excel.Range    rng    = ReferenceToRange(theRef);

                Debug.Print("Get formula for {0}", rng.Address);

                ws = rng.Parent as Excel.Worksheet;

                var parser = GetParser(rng);
                var root   = parser.Root;

                var newFormula = GetFormulaForFunc(root, replaceRef, resolveName, -1);

                Debug.Print(newFormula);

                //remove the SUMs
                var noSumVersion = GetFormulaWithoutSum(new XLParser.FormulaAnalyzer(newFormula).Root);
                var cleanFormula = Infix.Format(Infix.ParseOrThrow(noSumVersion));

                Debug.Print(cleanFormula);

                var finalFormula = cleanFormula;

                if (decimalPlaces > -1)
                {
                    Debug.Print("Going back through a 2nd time");
                    cleanFormula = CleanUpSqrtAbs(cleanFormula);
                    parser       = GetParser(cleanFormula);
                    var secondParserResult = GetFormulaForFunc(parser.Root, replaceRef, resolveName, decimalPlaces);
                    finalFormula = Infix.Format(Infix.ParseOrThrow(secondParserResult));
                }

                //see if a short version of the formula is available
                var algFormula = Infix.Format(Algebraic.Expand(Infix.ParseOrThrow(finalFormula)));
                var ratFormula = Infix.Format(Rational.Expand(Infix.ParseOrThrow(finalFormula)));

                var shortFormula = new[] { algFormula, ratFormula, finalFormula }.OrderBy(c => c.Length).First();

                //go through formula and search for |..| to replace with ABS(..)
                shortFormula = CleanUpSqrtAbs(shortFormula);

                return(shortFormula);
            }
            catch (Exception e)
            {
                Debug.Print(e.ToString());
                return(e.ToString());
            }
        }
예제 #4
0
        //create the function
        Expr Taylor(int iterations, Expr symbol, Expr value, Expr function)
        {
            this.DerivativeList.Clear();

            //counter for factorial
            int factorial = 1;

            //accumulates the results for each iteration (formula)
            Expr accumulator = Expr.Zero;

            //variable for holding the derivative of function for each iteration
            Expr derivative = function;

            for (int i = 0; i < iterations; i++)
            {
                //use for storing output
                TaylorSeriesIteration OutputItem = new TaylorSeriesIteration();

                //store the current iteration
                OutputItem.Iteration = (i + 1).ToString();

                //subs/replaces symbol with value from funct. Ex. symbol: x, func: x + 1, value: 1 result: 1 + 1
                var subs = Structure.Substitute(symbol, value, derivative);

                //get the derivative of derivative with respect to symbol
                derivative = Calculus.Differentiate(symbol, derivative);

                //output current derivative
                OutputItem.Function = derivative;

                //evaluate derivative, f(0)
                var evalValue = new Dictionary <string, FloatingPoint> {
                    { Infix.Format(symbol), 1 }
                };
                var eval = Evaluate.Evaluate(evalValue, Structure.Substitute(symbol, 0, derivative));
                OutputItem.Evaluation = eval.ToString();

                //create the formula and append to accumulator
                accumulator = accumulator + subs / factorial * Expr.Pow(symbol - value, i);

                //output current formula
                OutputItem.Series = accumulator;

                //current iteration + 1 as factorial (cause 0-based loop)
                factorial *= (i + 1);

                //append to list
                this.DerivativeList.Add(OutputItem);
            }

            //return the formula/func in expanded form
            return(Algebraic.Expand(accumulator));
        }
예제 #5
0
        public async Task <SearchResultCollection> SearchAsync(SearchQuery query, CancellationToken ct)
        {
            string latex;
            string infix;
            double?evaluated;

            try
            {
                // simplify
                var expression = Infix.ParseOrThrow(query.QueryString);
                latex = LaTeX.Format(expression);
                infix = Infix.Format(expression);

                // try to calculate
                var symbols = new Dictionary <string, FloatingPoint>();
                try
                {
                    evaluated = Evaluate.Evaluate(symbols, expression).RealValue;
                }
                catch (Exception ex)
                {
                    // expression valid, but can't be calculated
                    return(null);
                }
            }
            catch (Exception ex)
            {
                // expression error
                return(null);
            }

            var results = new SearchResultCollection
            {
                Title           = "Math evaluation",
                Relevance       = evaluated != null ? SearchResultRelevance.ONTOP : SearchResultRelevance.DEFAULT,
                FontAwesomeIcon = "Calculator"
            };

            results.Results = new ObservableCollection <SearchResult>
            {
                new MathSearchResult
                {
                    Title            = infix,
                    LaTeXExpression  = latex,
                    LaTeXEvaluated   = evaluated != null ? "= " + evaluated : "",
                    ParentCollection = results
                }
            };

            return(results);
        }
예제 #6
0
        public static void CalculateEquation(ref Dictionary <string, FloatingPoint> initialVector, int i)
        {
            var df1x = Calculus.Differentiate(x, f1);
            var df1y = Calculus.Differentiate(y, f1);
            var df2x = Calculus.Differentiate(x, f2);
            var df2y = Calculus.Differentiate(y, f2);


            double j11 = Eval.Evaluate(initialVector, df1x).RealValue;
            double j12 = Eval.Evaluate(initialVector, df1y).RealValue;
            double j21 = Eval.Evaluate(initialVector, df2x).RealValue;
            double j22 = Eval.Evaluate(initialVector, df2y).RealValue;

            if (i == 1)
            {
                Console.WriteLine("Jacobian matrix symbolic:");
                Console.WriteLine(Infix.FormatStrict(df1x) + "      " + Infix.Format(df1y) + "\n" + Infix.Format(df2x) + "     " + Infix.Format(df2y));
            }
            double[]        m        = { j11, j21, j12, j22 };
            Matrix <double> jacobian = new DenseMatrix(2, 2, m);

            Console.WriteLine("Jacobian matrix numeric:\n");
            Console.WriteLine(jacobian.ToString());
            Matrix <double> initial = new DenseMatrix(2, 1, new double[] { Eval.Evaluate(initialVector, f1).RealValue, Eval.Evaluate(initialVector, f2).RealValue });

            jacobian = jacobian.Inverse();

            var solution = jacobian * (-initial);

            var xn = x0 + solution[0, 0];
            var yn = y0 + solution[1, 0];

            var outVal = new Dictionary <string, FloatingPoint> {
                { "x", xn }, { "y", yn }
            };

            Console.WriteLine("Iteration " + i + ":\n");
            Console.WriteLine("x" + i.ToString() + " = " + xn + Environment.NewLine + "y" + i.ToString() + " = " + yn);
            Console.WriteLine("f1(x" + i + ",y" + i + ")=" + Math.Round(Eval.Evaluate(initialVector, f1).RealValue, 3));
            Console.WriteLine("f2(x" + i + ",y" + i + ")=" + Eval.Evaluate(initialVector, f2).RealValue);
            Console.WriteLine("\n");

            initialVector = outVal;
            x0            = xn;
            y0            = yn;
        }
예제 #7
0
        public static void ParseFormula()
        {
            var _app = ExcelDnaUtil.Application;

            app = (Excel.Application)_app;

            ws = (Excel.Worksheet)app.ActiveSheet;

            Excel.Range rng = (Excel.Range)app.ActiveCell;

            Debug.Print(rng.Formula.ToString());

            var parser = GetParser(rng);
            var root   = parser.Root;

            var newFormula = GetFormulaForFunc(root, true, true, -1);

            Debug.Print("processed formula: " + newFormula);

            MessageBox.Show(newFormula);

            var newParser    = new XLParser.FormulaAnalyzer(newFormula);
            var noSumVersion = GetFormulaWithoutSum(newParser.Root);

            Debug.Print("no sum version: " + noSumVersion);

            useSympyToCleanUpFormula(noSumVersion);

            //take that formula and process as math

            var exp = Infix.ParseOrThrow(noSumVersion);

            Debug.Print("mathdotnet verison: " + Infix.Format(exp));
            Debug.Print("expanded verison: " + Infix.Format(Algebraic.Expand(exp)));
            Debug.Print("variables: " + string.Join(",", Structure.CollectIdentifierSymbols(exp).Select(c => c.Item)));

            //GenerateFullTreeWithReferences(root);
        }
예제 #8
0
 private void enter_btn_Click(object sender, EventArgs e)
 {
     if (CalcInput.Text.Length > 0)
     {
         if (CalcInput.Text.Contains("Expand"))
         {
             try
             {
                 CalcInput.Text = CalcInput.Text.Replace("Expand", "");
                 var convert          = Infix.ParseOrThrow(CalcInput.Text);
                 var parsedExpression = Algebraic.Expand(convert);
                 MetroMessageBox.Show(this, Infix.Format(parsedExpression), "Answer");
                 CalcInput.Text = CalcInput.Text.Insert(0, "Expand");
             }
             catch (Exception ex)
             {
                 MessageBox.Show("Error" + ex);
             }
         }
         else if (CalcInput.Text.Contains("d/dx"))
         {
             try
             {
                 CalcInput.Text = CalcInput.Text.Replace("d/dx", "");
                 var convert          = Infix.ParseOrThrow(CalcInput.Text);
                 var parsedExpression = Algebraic.Expand(convert);
                 var differentiated   = Calculus.Differentiate(Infix.ParseOrThrow("x"), parsedExpression);
                 CalcInput.Text = CalcInput.Text.Insert(0, "d/dx");
                 MetroMessageBox.Show(this, "Using the formula nx^n-1, or pre-determined values \r\n" + "d/dx = " + Infix.Format(differentiated), "Answer");
             }
             catch (Exception ex)
             {
                 MetroMessageBox.Show(this, "Error, ensure you have brackets for each term, and a * between a number and a symbol " + ex, "Error",
                                      MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
             }
         }
         else if (CalcInput.Text.Contains("TrigIden"))
         {
             try
             {
                 CalcInput.Text = CalcInput.Text.Replace("TrigIden", "");
                 var convert          = Infix.ParseOrThrow(CalcInput.Text);
                 var parsedExpression = Trigonometric.Expand(convert);
                 CalcInput.Text = CalcInput.Text.Insert(0, "TrigIden");
                 MetroMessageBox.Show(this, "Answer \r\n " + Infix.Format(parsedExpression), "Answer", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
             }
             catch (Exception ex)
             {
                 MetroMessageBox.Show(this, "Error " + ex, "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
             }
         }
         else if (CalcInput.Text.Contains("TrigContract"))
         {
             try
             {
                 CalcInput.Text = CalcInput.Text.Replace("TrigContract", "");
                 var convert          = Infix.ParseOrThrow(CalcInput.Text);
                 var parsedExpression = Trigonometric.Contract(convert);
                 CalcInput.Text = CalcInput.Text.Insert(0, "TrigContract");
                 MetroMessageBox.Show(this, "Answer \r\n " + Infix.Format(parsedExpression), "Answer", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
             }
             catch (Exception ex)
             {
                 MetroMessageBox.Show(this, "Error " + ex, "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
             }
         }
         else
         {
             try
             {
                 var parsedExpression = Infix.ParseOrThrow(CalcInput.Text);
                 MessageBox.Show(Infix.Format(parsedExpression));
             }
             catch (Exception ex)
             {
                 MetroFramework.MetroMessageBox.Show(this, "Error" + ex, "Error");
             }
         }
     }
     else
     {
         MetroMessageBox.Show(this, "Please enter text before clicking enter...", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
     }
 }
예제 #9
0
        public string GetSqrt(string espression)
        {
            string result      = String.Empty;
            string AddToResult = "";

            espression = espression.Replace('.', ',');
            double num;

            if (Double.TryParse(espression, out num))
            {
                if (num < 0 && num % 1 != 0)
                {
                    espression  = espression.Substring(1);
                    AddToResult = "*i";
                }
            }
            espression = espression.Replace(',', '.');


            var expression = Infix.ParseOrUndefined("sqrt(" + espression + ")");


            if (expression == Expression.Undefined)
            {
                throw new SqrtException("Unable to parse expression");
            }

            try
            {
                var sub_result = Evaluate.Evaluate(null, expression);

                if (sub_result.IsReal)
                {
                    if (sub_result.RealValue != 0)
                    {
                        result = "+/- " + sub_result.RealValue.ToString();
                    }
                    else
                    {
                        result = "0";
                    }
                }
                else if (sub_result.IsComplex)
                {
                    result = sub_result.ComplexValue.Real.ToString() + " + i*" + sub_result.ComplexValue.Imaginary.ToString();
                }
                else
                {
                    result = sub_result.ToString();
                }
            }
            catch (NullReferenceException ex)
            {
                result = Infix.Format(Calculus.Taylor(5, Infix.ParseOrThrow(espression), Infix.ParseOrThrow("1"), expression)) + " + ...";
            }
            int i = 0;

            while (i < result.Length)
            {
                if (result[i] == ',')
                {
                    int j = i + 1;
                    for (; j - i < _accuracy && j < result.Length && Char.IsNumber(result[j]); j++)
                    {
                    }
                    i = j + 1;
                    for (; j < result.Length && Char.IsNumber(result[j]); j++)
                    {
                    }
                    if (_accuracy == 0)
                    {
                        i = i - 2;
                    }
                    result = result.Remove(i, j - i);
                }
                else
                {
                    i++;
                }
            }
            return(result + AddToResult);
        }