Ejemplo n.º 1
0
        }//end property

        //METHODS
        public string[] FixInfixLayout(string infix)
        {
            char[] infix_char_array = new char[infix.Length];
            infix_char_array = infix.ToCharArray();
            string final_infix = "";
            int    count       = 0;

            foreach (char item in infix_char_array) //CYCLE THROUGH THE CHARS TO ADD SPACES WHERE NEEDED
            {
                if (item == '-' && infix_char_array[count + 1] >= 0 || item == '-' && infix_char_array[count + 1] <= 9)
                {
                    final_infix += $" {item}";
                }
                else if (item == '+' || item == '-' || item == '/' || item == '*' || item == '^' || item == '(' || item == ')')
                {
                    final_infix += $" {item} ";
                }
                else
                {
                    final_infix += $"{item}";
                } //end if
                count++;
            }     //end foreach

            //SET INFIX
            Infix = final_infix;
            //SPLIT AND REMOVE UNNECESSARY SPACES, TABS, OR RETURNS
            char[]   seperators  = { ' ', '\t', '\n', };
            string[] infix_array = Infix.Split(seperators, StringSplitOptions.RemoveEmptyEntries);

            return(infix_array);
        }//end method
Ejemplo n.º 2
0
        //  private void PUpdated(Arg a)
        //  {
        ////      a.parent.UpdateArgs(flowLayoutPanel2.Controls);
        //  }
        //private void LoadArgs(MATH2.IMathPlugin plugin)
        //{
        //    List<Arg> args = plugin.GetArgs();
        //    foreach (Arg arg in args)
        //    {
        //        arg.parent = plugin;
        //        arg.r = new Arg.Return(PUpdated);
        //        //flowLayoutPanel2.Controls.Add(arg.GetControl());
        //        Console.WriteLine("added arg " + arg.displayname);
        //    }

        //}
        private void OnTextChanged(string raw)//or whatever moooooo
        {
            List <int> probs = new List <int>();

            Expression ex = null;

            try
            {
                ex = Infix.ParseOrThrow(fastColoredTextBox1.Text);
            }
            catch { }
            try
            {
                foreach (var item in plugins)
                {
                    probs.Add(GetProb(Activator.CreateInstance(item) as MATH2.IMathPlugin, raw, ex));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            foreach (var plugin in plugins)
            {
                comboBox1.Items.Add(plugin.Name);
            }

            comboBox1.SelectedIndex = probs.IndexOf(probs.Max());
            comboBox1_SelectedIndexChanged(null, null);

            // Console.Clear();
        }
Ejemplo n.º 3
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 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);
            }
        }
Ejemplo n.º 5
0
        public static int CalculateEqualizationDifNo(List <Expression> seq)
        {
            //Console.WriteLine("calculating: ================================");
            int  no    = 0;
            bool found = false;

            List <Expression> last = seq;

            while (!found)
            {
                //   Console.Write("last = ");
                //foreach (var item in last)
                {
                    //      Console.Write(Infix.Print(item)+",");
                }
                //Console.WriteLine();
                //*
                if (last.TrueForAll(x => Infix.PrintStrict(last.Last()) == Infix.PrintStrict(x)))
                {
                    // Console.Write("  Last - x =" + Infix.Print(last.Last() - x));
                    found = true;
                    continue;
                }//*/
                last = GetDifference(last);
                no++;
            }
            return(no);
        }
Ejemplo n.º 6
0
        private void trackBar1_ValueChanged(object sender, EventArgs e)
        {
            string url = "";

            laTeXDisplay1.size = trackBar1.Value;
            try
            {
                // url = @"http://www.texrendr.com/cgi-bin/mathtex.cgi?\dpi{" + trackBar1.Value.ToString() + @"}" + LaTeX.Print(Infix.ParseOrThrow(fastColoredTextBox1.Text));
                //Console.WriteLine(url);
                laTeXDisplay1.LoadLatex(LaTeX.Print(Infix.ParseOrThrow(fastColoredTextBox1.Text)));
            }
            catch
            {
                //url = @"http://www.texrendr.com/cgi-bin/mathtex.cgi?\dpi{" + trackBar1.Value.ToString() + @"}" + fastColoredTextBox1.Text;
                laTeXDisplay1.LoadLatex(fastColoredTextBox1.Text);
                // Console.WriteLine(char.MinValue);
                //  int no = (int)char.MinValue;
                // while (no != char.MaxValue)
                //{
                //  char c = (char)no;
                //System.Console.WriteLine("CharID: " + no + " | Bin: "
                //  + string.Join(" ", System.Text.Encoding.UTF8.GetBytes(c.ToString()).Select(byt =>
                //    System.Convert.ToString(byt, 2).PadLeft(8, '0')))
                //+ " | Display: " + c);
                //no++;
                //}
            }
            //   laTeXDisplay1.LoadLatex(new Uri(url));
        }
Ejemplo n.º 7
0
 private void fastColoredTextBox1_TextChanged(object sender, FastColoredTextBoxNS.TextChangedEventArgs e)
 {
     //  lasttext = fastColoredTextBox1.Text;
     if (MATH2.MasterForm.Clear)
     {
         Console.Clear();
     }
     comboBox1.Items.Clear();
     try
     {
         OnTextChanged(fastColoredTextBox1.Text);
     }
     catch { }
     try
     {
         // url = @"http://www.texrendr.com/cgi-bin/mathtex.cgi?\dpi{" + trackBar1.Value.ToString() + @"}" + LaTeX.Print(Infix.ParseOrThrow(fastColoredTextBox1.Text));
         //Console.WriteLine(url);
         laTeXDisplay1.LoadLatex(LaTeX.Print(Infix.ParseOrThrow(fastColoredTextBox1.Text)));
     }
     catch
     {
         //url = @"http://www.texrendr.com/cgi-bin/mathtex.cgi?\dpi{" + trackBar1.Value.ToString() + @"}" + fastColoredTextBox1.Text;
         laTeXDisplay1.LoadLatex(fastColoredTextBox1.Text);
     }
 }
Ejemplo n.º 8
0
        private static OperatorTable <T> BuildOperatorsTable <T>(TokenParser <T> lexer)
            where T : Token
        {
            Func <T, T, ReservedOpToken, T> fn = (lhs, rhs, op) =>
            {
                return(new BinaryOp(lhs, rhs, op) as T);
            };

            Func <ReservedOpToken, Func <T, T, T> > binop = op => new Func <T, T, T>((T lhs, T rhs) =>
            {
                return(fn(lhs, rhs, op));
            });

            Func <string, Parser <Func <T, T, T> > > resOp = name => from op in lexer.ReservedOp(name) select binop(op);

            var equals   = new Infix <T>("=", resOp("="), Assoc.Left);
            var mult     = new Infix <T>("*", resOp("*"), Assoc.Left);
            var divide   = new Infix <T>("/", resOp("/"), Assoc.Left);
            var plus     = new Infix <T>("+", resOp("+"), Assoc.Left);
            var minus    = new Infix <T>("-", resOp("-"), Assoc.Left);
            var lessThan = new Infix <T>("<", resOp("<"), Assoc.Left);

            var binops = new OperatorTable <T>();

            binops.AddRow().Add(equals)
            .AddRow().Add(mult).Add(divide)
            .AddRow().Add(plus).Add(minus)
            .AddRow().Add(lessThan);

            return(binops);
        }
Ejemplo n.º 9
0
        public List <Step> Solve(string raw, Expression e)
        {
            sequence = Utils.Sequences.ParseSequence(raw);
            Expression seconddifference        = Utils.Sequences.GetDifference(Utils.Sequences.GetDifference(sequence)).Last();
            List <List <Expression> > branches = new List <List <Expression> >();

            branches.Add(sequence);
            branches.Add(Utils.Sequences.GetDifference(sequence));
            branches.Add(Utils.Sequences.GetDifference(Utils.Sequences.GetDifference(sequence)));
            StepData.BranchData bd = new StepData.BranchData(branches);
            steps.Add(new Step(seconddifference, "get the second difference (" + Infix.Print(seconddifference) + ")", new StepData.BranchData(branches)));
            t_n = t_n * t_n;
            steps.Add(new Step(t_n, "must be n^2 in quadratic sequence", t_n));
            t_n = t_n * ((seconddifference / 2));
            steps.Add(new Step(t_n, "Half the second difference and multiply n^2 with it", t_n));
            //  Console.WriteLine(Infix.Print(FindOffset(1)));
            t_n += FindOffset(1);
            steps.Add(new Step(FindOffset(1), "work out the offset with our current expression and the given sequence", FindOffset(1)));
            steps.Add(new Step(t_n, "add the offset to our expression", t_n));
            int           na = 1;
            StringBuilder sb = new StringBuilder();

            while (na != 10)
            {
                sb.Append(Infix.Print(Utils.Sequences.GetValueInSequence(t_n, t_n, na)) + ", ");
                na++;
            }
            steps.Add(new Step(null, "Double check: " + sb.ToString()));
            steps.Add(new Step(t_n, "final answer", t_n));
            return(steps);
        }
        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());
        }
Ejemplo n.º 11
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");
            }
        }
Ejemplo n.º 12
0
        private int WrongAnswer(int[] numbers)
        {
            int  wrongAnswer = 0;
            int  solution    = (int)((SymbolicExpression)Infix.ParseOrThrow(SolutionInfix)).RealNumberValue;
            var  rng         = new Random();
            bool ok          = false;

            for (int tries = 0; tries < 30 && !ok; tries++)
            {
                int method = rng.Next(3);
                switch (method)
                {
                case 0:
                    // multiply with slightly changed numbers
                    wrongAnswer = numbers[1];
                    for (int i = 0; i < numbers.Length; i++)
                    {
                        if (i == 1)
                        {
                            continue;
                        }
                        wrongAnswer *= (numbers[i] + (rng.NextBoolean() ? 1 : -1));
                    }
                    break;

                case 1:
                    // multiply with slightly changed numbers
                    wrongAnswer = numbers[0];
                    for (int i = 1; i < numbers.Length; i++)
                    {
                        wrongAnswer *= (numbers[i] + (rng.NextBoolean() ? 1 : -1));
                    }
                    break;

                default:
                    // just roll something in the range of the solution
                    int range = Math.Abs(solution / 4) + 3;
                    wrongAnswer = solution + rng.Next(solution - range, solution + range + 1);
                    break;
                }
                // check if the answer is ok
                ok = true;
                // check if the answer is identical to another
                foreach (string answer in AnswersInfix)
                {
                    // if it is, begin anew
                    if (answer != null && answer.Equals(wrongAnswer.ToString()))
                    {
                        ok = false;
                    }
                }
                // check if the answer is actually a solution
                if (IsSolution(wrongAnswer.ToString()))
                {
                    ok = false;
                    tries--;
                }
            }
            return(wrongAnswer);
        }
Ejemplo n.º 13
0
        public void ToRealTest()
        {
            var x = Infix.ParseOrUndefined("1/3");

            var d = x.ToReal().Round(2);

            Assert.AreEqual(0.33, d);
        }
Ejemplo n.º 14
0
        public bool isValidFunction(string sFunction)
        {
            if (string.IsNullOrEmpty(sFunction))
            {
                throw new ArgumentNullException("sFunction");
            }

            return(Infix.ParseOrUndefined(sFunction) != Expression.Undefined);
        }
Ejemplo n.º 15
0
        private void calculateFuncAi(string sFunction, double x)
        {
            var e      = Infix.ParseOrUndefined(sFunction);
            var result = Evaluate.Evaluate(new Dictionary <string, FloatingPoint> {
                { "x", x }
            }, e);

            _model.funcAi = result.RealValue;
        }
Ejemplo n.º 16
0
        public Surface(string expression)
        {
            if (expression == null)
            {
                throw new NullReferenceException();
            }

            _expression = Compile.compileExpression2(Infix.ParseOrThrow(expression), Symbol.NewSymbol("x"), Symbol.NewSymbol("y")).Value;
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            Console.Write("Expression: ");
            var expr   = Console.ReadLine();
            var parsed = Infix.ParseOrThrow(expr);
            var res    = Evaluate.Evaluate(new Dictionary <String, FloatingPoint>(), parsed);

            Console.WriteLine(res);
        }
Ejemplo n.º 18
0
        public double GetValue(IPoint p)
        {
            Dictionary <string, FloatingPoint> values = new Dictionary <string, FloatingPoint>();

            for (int i = 0; i < dimentions; ++i)
            {
                values.Add("X" + (i + 1).ToString(), p.GetPointOnAxis(i));
            }
            return(Evaluate.Evaluate(values, Infix.ParseOrUndefined(function_string)).RealValue);
        }
        //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
        }
Ejemplo n.º 20
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());
            }
        }
Ejemplo n.º 21
0
        public List <Step> Solve(string raw, Expression exp)
        {
            try
            {
                // Expression e = new Expression();
                //   e += exp;
                sequence = MATH2.Utils.Sequences.ParseSequence(raw);
                // steps.Add(new Step(null, raw + " - start off with the sequence",new StepData.LaTeXData(raw),StepData.DataType.LaTeX));
                //  Console.WriteLine("First difference:");
                Expression firstdif = S.GetDifference(sequence)[S.GetDifference(sequence).Count - 1];

                List <List <Expression> > branches = new List <List <Expression> >();
                branches.Add(sequence);
                branches.Add(S.GetDifference(sequence));
                // (80*x)-((19*x*y)-((-80+(81*x*y)))+((1/2)*(n*n)))*(13*y*y)+(4*x)
                steps.Add(new Step(firstdif, "find the first difference", new StepData.BranchData(branches)));
                //Console.WriteLine(Infix.Print(firstdif));
                t_n = t_n * firstdif;
                steps.Add(new Step(t_n, "n must be multiple of first difference", t_n));
                //substitute(thing,thingwith,raw);
                // Console.WriteLine("Equation so far: " + Infix.Print(t_n));
                // Console.WriteLine("offset: " + Infix.Print(FindOffset()));
                steps.Add(new Step(FindOffset(), "subtract and calculate offset", FindOffset()));
                t_n = t_n + FindOffset();
                steps.Add(new Step(t_n, "add that offset to the t_n expression", t_n));
                //steps.Add(new Step(t_n, "boom, we now have a full expression for n in a linear sequence"));
                //   Console.WriteLine("Answer: " + Infix.Print(t_n));
                //     Console.Write("Sequence as calculated: ");
                int           na = 1;
                StringBuilder sb = new StringBuilder();
                while (na != 10)
                {
                    sb.Append(Infix.Print(S.GetValueInSequence(t_n, t_n, na)) + ", ");
                    na++;
                }
                steps.Add(new Step(null, "Double check: " + sb.ToString()));
                steps.Add(new Step(t_n, ""));
                //       Console.Write(Environment.NewLine);
                //     Console.ReadKey();
                //   Console.WriteLine("Steps");
                //foreach (var item in steps)
                {
                    //     Console.WriteLine(item);
                }

                return(steps);
            }
            catch (Exception e)
            {
                Console.WriteLine("BANANA Error " + e.Message + ":");
                Console.WriteLine(e);
                Console.WriteLine(e.InnerException);
                return(null);
            }
        }
Ejemplo n.º 22
0
        public static double Evaluate(double x, string expr)
        {
            var parsed = Infix.ParseOrThrow(expr);
            var values = new Dictionary <String, FloatingPoint>();

            values.Add("x", x);

            var res = MathNet.Symbolics.Evaluate.Evaluate(values, parsed);

            return(res.RealValue);
        }
Ejemplo n.º 23
0
        private List <MathNet.Symbolics.Expression> GetListEquations(string[] strEquations)
        {
            List <MathNet.Symbolics.Expression> equations = new List <MathNet.Symbolics.Expression>();

            for (int i = 0; i < strEquations.Length; i++)
            {
                equations.Add(Infix.ParseOrThrow(strEquations[i].Replace('=', '-').Replace(",", ".")));
            }

            return(equations);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Please insert a function with x as dependant variable: ");
            string     fstring = Console.ReadLine();
            Expression f       = Infix.ParseOrUndefined(fstring);

            Newton(f, 4f, (float)(10 * Math.Pow(10, -10)), 20);
            Secant(f, 1f, 4f, (float)(10 * Math.Pow(10, -10)), 20);
            Multiple_Roots(f, 4f, (float)(10 * Math.Pow(10, -10)), 20);
            Console.Read();
        }
Ejemplo n.º 25
0
 public string String(object o)
 {
     if (o as Expression == null)
     {
         return(o.ToString());
     }
     else
     {
         return(Infix.Print(o as Expression));
     }
 }
Ejemplo n.º 26
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));
        }
 //O1 -> +,-,*,/
 bool O1()
 {
     if (now.word == "+" || now.word == "-" || now.word == "*" || now.word == "/")
     {
         Infix.Add(now);
         now = (token)tokenlist[count++]; return(true);
     }
     else
     {
         return(false);
     }
 }
Ejemplo n.º 28
0
        internal bool IsSolution(string answerInfix)
        {
            var answerExpr = Infix.ParseOrUndefined(answerInfix);

            if (answerExpr.IsUndefined)
            {
                return(false);
            }
            else
            {
                return(answerExpr.Equals(Infix.ParseOrThrow(SolutionInfix)));
            }
        }
Ejemplo n.º 29
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);
        }
Ejemplo n.º 30
0
        private int WrongAnswer(Random rng, int[] summands)
        {
            int wrongAnswer = 0;
            int solution    = (int)((SymbolicExpression)Infix.ParseOrThrow(SolutionInfix)).RealNumberValue;
            int tries       = 0;

start:
            tries++;
            int algorithm = rng.Next(0, 3);

            switch (algorithm)
            {
            case 0:
                // take the solution and add or substract 1 or 2
                wrongAnswer = solution + rng.Next(-2, 3);
                break;

            case 1:
                // take the solution and add or substract 10 or 20
                wrongAnswer = solution + rng.Next(-2, 3) * 10;
                break;

            default:
                // just roll something in the range of the solution
                wrongAnswer = solution + rng.Next(solution - (solution / 4) - 3, solution + (solution / 4) + 4);
                break;
            }
            // check if the answer is identical to another
            foreach (string answer in AnswersInfix)
            {
                // if it is, begin anew
                if (answer != null && answer.Equals(wrongAnswer.ToString()) && tries < 20)
                {
                    goto start;
                }
            }
            // check if the answer is actually a solution
            if (IsSolution(wrongAnswer.ToString()))
            {
                goto start;
            }
            // check if the answer is larger than each summand (it would be too simple if else)
            for (int i = 0; i < summands.Length; i++)
            {
                if (wrongAnswer <= summands[i] && tries < 20)
                {
                    goto start;
                }
            }
            return(wrongAnswer);
        }
Ejemplo n.º 31
0
 public static string GetOperatorSymbol(Infix infix)
 {
     switch (infix)
     {
         case Infix.Add:
             return "+";
         case Infix.Assign:
             return "=";
         case Infix.BitwiseAnd:
             return "&";
         case Infix.BitwiseOr:
             return "|";
         case Infix.BitwiseXor:
             return "^";
         case Infix.BitwiseAndAssign:
             return "&=";
         case Infix.BitwiseSignedRightShiftAssign:
             return ">>=";
         case Infix.BitwiseLeftShift:
             return "<<";
         case Infix.BitwiseLeftShiftAssign:
             return "<<=";
         case Infix.BitwiseUnsignedRightShiftAssign:
             return ">>>=";
         case Infix.BitwiseOrAssign:
             return "|=";
         case Infix.BitwiseSignedRightShift:
             return ">>";
         case Infix.BitwiseUnsignedRightShift:
             return ">>>";
         case Infix.BitwiseXorAssign:
             return "^=";
         case Infix.Divide:
             return "/";
         case Infix.DivideAssign:
             return "/=";
         case Infix.In:
             return "in";
         case Infix.InstanceOf:
             return "instanceof";
         case Infix.IsEqualTo:
             return "===";
         case Infix.IsGreaterThan:
             return ">";
         case Infix.IsGreaterThanOrEqualTo:
             return ">=";
         case Infix.IsKindaEqualTo:
             return "==";
         case Infix.IsLessThan:
             return "<";
         case Infix.IsLessThanOrEqualTo:
             return "<=";
         case Infix.IsNotEqualTo:
             return "!==";
         case Infix.IsKindaNotEqualTo:
             return "!=";
         case Infix.LogicalAnd:
             return "&&";
         case Infix.LogicalOr:
             return "||";
         case Infix.Modulus:
             return "%";
         case Infix.ModulusAssign:
             return "%=";
         case Infix.Multiply:
             return "*";
         case Infix.MultiplyAssign:
             return "*=";
         case Infix.AddAssign:
             return "+=";
         case Infix.Subtract:
             return "-";
         case Infix.SubtractAssign:
             return "-=";
         default:
             throw new Exception("Unknown operator: " + infix);
     }
 }
Ejemplo n.º 32
0
 public static bool OperatorIsRightToLeft(Infix infix)
 {
     switch (infix)
     {
         case Infix.Assign:
         case Infix.AddAssign:
         case Infix.SubtractAssign:
         case Infix.MultiplyAssign:
         case Infix.ModulusAssign:
         case Infix.BitwiseAndAssign:
         case Infix.BitwiseLeftShiftAssign:
         case Infix.BitwiseSignedRightShiftAssign:
         case Infix.BitwiseOrAssign:
         case Infix.BitwiseUnsignedRightShiftAssign:
         case Infix.BitwiseXorAssign:
         case Infix.DivideAssign:
             return true;
         default:
             return false;
     }
 }
Ejemplo n.º 33
0
        public static int GetOperatorPrecedence(Infix infix)
        {
            switch (infix)
            {
                case Infix.Multiply:
                case Infix.Divide:
                case Infix.Modulus:
                    return Util.PRECEDENCE_MULTIPLY_DIVIDE_MODULUS;

                case Infix.Add:
                case Infix.Subtract:
                    return Util.PRECEDENCE_ADD_SUBTRACT;

                case Infix.BitwiseLeftShift:
                case Infix.BitwiseSignedRightShift:
                case Infix.BitwiseUnsignedRightShift:
                    return Util.PRECEDENCE_BITWISE_SHIFT;

                case Infix.IsLessThan:
                case Infix.IsLessThanOrEqualTo:
                case Infix.IsGreaterThan:
                case Infix.IsGreaterThanOrEqualTo:
                    return Util.PRECEDENCE_LESS_GREATER;

                case Infix.IsEqualTo:
                case Infix.IsKindaEqualTo:
                case Infix.IsNotEqualTo:
                case Infix.IsKindaNotEqualTo:
                    return Util.PRECEDENCE_EQUAL_NOT_EQUAL;

                case Infix.BitwiseAnd:
                    return Util.PRECEDENCE_BITWISE_AND;

                case Infix.BitwiseXor:
                    return Util.PRECEDENCE_BITWISE_XOR;

                case Infix.BitwiseOr:
                    return Util.PRECEDENCE_BITWISE_OR;

                case Infix.LogicalAnd:
                    return Util.PRECEDENCE_LOGICAL_AND;

                case Infix.LogicalOr:
                    return Util.PRECEDENCE_LOGICAL_OR;

                case Infix.Assign:
                case Infix.AddAssign:
                case Infix.SubtractAssign:
                case Infix.MultiplyAssign:
                case Infix.DivideAssign:
                case Infix.ModulusAssign:
                case Infix.BitwiseXorAssign:
                case Infix.BitwiseAndAssign:
                case Infix.BitwiseOrAssign:
                case Infix.BitwiseSignedRightShiftAssign:
                case Infix.BitwiseUnsignedRightShiftAssign:
                case Infix.BitwiseLeftShiftAssign:
                    return Util.PRECEDENCE_ASSIGN_MUTATE;

                default:
                    throw new Exception("Unknown binop: " + infix);
            }
        }