Пример #1
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());
        }
        public string mostraNovaEquacao()
        {
            /*var s = Expr.Variable("s");
            *  var t = Expr.Variable("t");*/


            //MessageBox.Show("Equação geral: " + aL + "s² + " + cL + "t² - " + aL * cL + " = 0");
            double[] num =
            {
                getAL(), getBL(), getCL(), getDL(), getEL(), getF()
            };

            double max = 0;

            for (int i = 0; i < 6; i++)
            {
                if (num[i] > max)
                {
                    max = num[i];
                }
            }

            long[] num2 =
            {
                (long)max, (long)max, (long)max, (long)max, (long)max, (long)max
            };
            int j = 0;

            for (int i = 0; i < 6; i++)
            {
                if (num[i] != 0)
                {
                    num2[j] = (long)num[i];
                    j++;
                }
            }
            double div = (double)Euclid.GreatestCommonDivisor(num2);

            MessageBox.Show("MMC: " + div);
            if (div != null && div != 0)
            {
                setAL(getAL() / div);
                setBL(getBL() / div);
                setCL(getCL() / div);
                setDL(getDL() / div);
                setEL(getEL() / div);
                setF(getF() / div);
            } // Simplifica a equação com o maior divisor entre eles


            var eq       = Infix.ParseOrThrow(getAL().ToString() + "*u*u+" + getBL().ToString() + "*u*v+" + getCL().ToString() + "*v*v+" + getDL().ToString() + "*u+" + getEL().ToString() + "*v+" + getF().ToString());
            var expanded = Algebraic.Expand(eq);

            MessageBox.Show("Equação Geral: " + Infix.FormatStrict(expanded), "Equação", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            // Agora falta simplificar a equação


            return(Infix.FormatStrict(expanded).ToString());
        }
        public void calculaH_K(double[] coeficientes)
        {
            double a = coeficientes[0];
            double b = coeficientes[1];
            double c = coeficientes[2];
            double d = coeficientes[3];
            double e = coeficientes[4];
            double f = coeficientes[5];

            var A = Matrix <double> .Build.DenseOfArray(new double[, ]
            {
                { Convert.ToInt32(a), Convert.ToInt32(b / 2) },
                { Convert.ToInt32(b / 2), Convert.ToInt32(c) },
            });

            MessageBox.Show("Matriz para calcular H e K: " + A.ToString());
            var B = Vector <double> .Build.Dense(new double[] { -(d / 2), -(e / 2) });

            var x = A.Solve(B);

            MessageBox.Show("H e K: " + x.ToString());
            h = x[0];
            k = x[1];

            if (!Double.IsInfinity(getH())) // Se o determinante deu diferente de zero foi possível realizar a translação
            {
                // Achar o novo termo independente da equação: (p.96)
                setF((getD() / 2) * getH() + (getE() / 2) * getK() + getF());

                var eq       = Infix.ParseOrThrow(getA().ToString() + "*u*u+" + getB().ToString() + "*u*v+" + getC().ToString() + "*v*v+" + getF().ToString());
                var expanded = Algebraic.Expand(eq);
                MessageBox.Show("Translação realizada!\nNova equação da cônica:\n" + Infix.FormatStrict(expanded) + " ", "Translação Concluida", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                MessageBox.Show("Iniciando Rotação para elimianar o termo quadrático misto", "Iniciando Rotação", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        //mostraNovaEquacao2 retorna a equação após fazer a rotação e a translação conforme o caso na pag 99 das notas de aula
        public string mostraNovaEquacao2()
        {
            // O termo independente continua o mesmo pois não foi realizada a translação
            double[] num =
            {
                getAL(), getBL(), getCL(), getDL(), getEL(), getF()
            };

            double max = 0;

            for (int i = 0; i < 6; i++)
            {
                if (num[i] > max)
                {
                    max = num[i];
                }
            }

            long[] num2 =
            {
                (long)max, (long)max, (long)max, (long)max, (long)max, (long)max
            };
            int j = 0;

            for (int i = 0; i < 6; i++)
            {
                if (num[i] != 0)
                {
                    num2[j] = (long)num[i];
                    j++;
                }
            }
            double div = (double)Euclid.GreatestCommonDivisor(num2);

            MessageBox.Show("MMC: " + div);
            if (div != null && div != 0)
            {
                setAL(getAL() / div);
                setBL(getBL() / div);
                setCL(getCL() / div);
                setDL(getDL() / div);
                setEL(getEL() / div);
                setF(getF() / div);
            } // Simplifica a equação com o maior divisor entre eles

            var eq       = Infix.ParseOrThrow(getAL().ToString() + "*u*u+" + getBL().ToString() + "*u*v+" + getCL().ToString() + "*v*v+" + getDL().ToString() + "*u+" + getEL().ToString() + "*v+" + getF().ToString());
            var expanded = Algebraic.Expand(eq);

            MessageBox.Show("Equação Geral: " + Infix.FormatStrict(expanded), "Equação", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);


            return(Infix.FormatStrict(expanded).ToString());
            // B = 0
            // Agora simplificar a equação
        }
Пример #5
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());
            }
        }
Пример #6
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));
        }
Пример #7
0
        public Expr FindRoot(ExprLast variable, ExprLast expr)
        {
            ExprLast simple = Algebraic.Expand(Rational.Numerator(Rational.Simplify(variable, expr)));


            ExprLast[] coeff = Polynomial.Coefficients(variable, simple);
            switch (coeff.Length)
            {
            case 1: return(ExprLast.Zero.Equals(coeff[0]) ? variable : ExprLast.Undefined);

            case 2: return(Rational.Simplify(variable, Algebraic.Expand(-coeff[0] / coeff[1])));

            default: return(ExprLast.Undefined);
            }
        }
Пример #8
0
        Expr SolveSimpleRoot(Expr variable, Expr expr)
        {
            // try to bring expression into polynomial form
            Expr simple = Algebraic.Expand(Rational.Numerator(Rational.Simplify(variable, expr)));

            // extract coefficients, solve known forms of order up to 1
            Expr[] coeff = Polynomial.Coefficients(variable, simple);
            switch (coeff.Length)
            {
            case 1: return(Expr.Zero.Equals(coeff[0]) ? variable : Expr.Undefined);

            case 2: return(Rational.Simplify(variable, Algebraic.Expand(-coeff[0] / coeff[1])));

            default: return(Expr.Undefined);
            }
        }
Пример #9
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);
        }
Пример #10
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);
     }
 }