Esempio n. 1
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);
     }
 }
Esempio n. 2
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);
        }
Esempio n. 3
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();
        }
        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);
            }
        }
Esempio n. 5
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));
        }
        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());
        }
Esempio n. 7
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());
        }
Esempio n. 8
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);
        }
Esempio n. 9
0
        public Surface(string expression)
        {
            if (expression == null)
            {
                throw new NullReferenceException();
            }

            _expression = Compile.compileExpression2(Infix.ParseOrThrow(expression), Symbol.NewSymbol("x"), Symbol.NewSymbol("y")).Value;
        }
        //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
        }
Esempio n. 11
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());
            }
        }
Esempio n. 12
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);
        }
Esempio n. 13
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);
        }
        internal bool IsSolution(string answerInfix)
        {
            var answerExpr = Infix.ParseOrUndefined(answerInfix);

            if (answerExpr.IsUndefined)
            {
                return(false);
            }
            else
            {
                return(answerExpr.Equals(Infix.ParseOrThrow(SolutionInfix)));
            }
        }
Esempio n. 15
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);
        }
        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);
        }
Esempio n. 17
0
        private void Button_EvaluateExpression_Click(object sender, RoutedEventArgs e)
        {
            try {
                Expr   expression = Infix.ParseOrThrow(TextBox_ExpressionInput.Text);
                string symbolstr  = TextBox_InputSymbol.Text;

                string x1 = TextBox_InputX1.Text;
                string x2 = TextBox_InputX2.Text;
                string ep = TextBox_InputEpsilon.Text;

                var result = new SecantMethodDecimal()
                {
                    Function  = expression,
                    SymbolStr = symbolstr,
                    Epsillon  = Decimal.Parse(ep)
                };

                result.ComputeSecantMethod(Decimal.Parse(x1), Decimal.Parse(x2));

                this.ListView_Solution.ItemsSource = result.Results;
                UIHelper.ResizeListViewColumnsToContent(this.ListView_Solution, null);

                var lastResult    = result.Results.Last();
                int decimalPlaces = UIHelper.CountDigitsAfterDecimal(TextBox_InputEpsilon.Text);


                this.FC_Aproximation.Formula        = result.GetAprox.ToString();
                this.FC_AproximationRounded.Formula = result.GetRoundedOff.ToString();
                this.FC_AproximationChopped.Formula = result.GetChoppedOff.ToString();

                SnackBarNotif.MessageQueue.Enqueue(
                    UIHelper.NewSnackbarMessage(
                        PackIconKind.CheckAll,
                        "Success! Check solution and results!",
                        Colors.DarkGreen,
                        0.5
                        )
                    );
            } catch {
                //show error message
                SnackBarNotif.MessageQueue.Enqueue(
                    UIHelper.NewSnackbarMessage(
                        PackIconKind.SignCaution,
                        "Error! Unable to compute aproximation!",
                        Colors.HotPink,
                        0.5
                        )
                    );
            }
        }
        private int WrongAnswer(int[] numbers)
        {
            int wrongAnswer = 0;
            int solution    = (int)((SymbolicExpression)Infix.ParseOrThrow(SolutionInfix)).RealNumberValue;
            var rng         = new Random();
            int tries       = 0;

start:
            int method = rng.Next(3);

            switch (method)
            {
            case 0:
                // take the solution and add or substract 1 or 2
                wrongAnswer = solution + rng.Next(-3, 4);
                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
                int range = Math.Abs(solution / 4) + 3;
                wrongAnswer = solution + rng.Next(solution - range, solution + range + 1);
                break;
            }
            tries++;
            // 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 smaller than the first number
            if (wrongAnswer > numbers[0] && tries < 20)
            {
                goto start;
            }
            return(wrongAnswer);
        }
Esempio n. 19
0
        private static void OnTextChanged(string raw)//or whatever moooooo
        {
            List <int> probs = new List <int>();

            Expression e = null;

            try
            {
                e = Infix.ParseOrThrow(raw);
            }
            catch { }
            foreach (var item in plugins)
            {
                probs.Add(GetProb(Activator.CreateInstance(item) as MATH2.IMathPlugin, raw, e));
            }
            MATH2.IMathPlugin pl = Activator.CreateInstance(plugins[probs.IndexOf(probs.Max())]) as MATH2.IMathPlugin;
            Console.WriteLine("Using the " + plugins[probs.IndexOf(probs.Max())].Name + " solver to solve your question:");
            List <Step> steps = null;

            try
            {
                steps = pl.Solve(raw, e);
                Console.WriteLine("Answer: " + steps.Last());
            }
            catch (Exception exc)
            {
                if (MATH2.MasterForm.Clear)
                {
                    Console.Clear();
                }
                Console.WriteLine("A " + exc.GetType().Name + " error occured whilst the solver was calculating the answer.");
                System.Threading.Thread.Sleep(2000); if (MATH2.MasterForm.Clear)
                {
                    Console.Clear();
                }
                Main();
            }
            if (steps != null)
            {
                //   Console.ReadKey();
                Console.WriteLine("Steps");
                foreach (var step in steps)
                {
                    Console.WriteLine(step);
                }
            }
            // Console.Clear();
        }
Esempio n. 20
0
        private void Button_EvaluateExpression_Click(object sender, RoutedEventArgs e)
        {
            try {
                Expr   expression = Infix.ParseOrThrow(TextBox_ExpressionInput.Text);
                Symbol symbol     = Symbol.NewSymbol(TextBox_InputSymbol.Text);

                var result = new BisectionResultRow(symbol, expression)
                {
                    A        = Double.Parse(TextBox_InputA.Text),
                    B        = Double.Parse(TextBox_InputB.Text),
                    Epsillon = Double.Parse(TextBox_InputEpsilon.Text)
                };

                var results = BisectionResultRow.ComputeList(result);
                this.ListView_Solution.ItemsSource = results;
                UIHelper.ResizeListViewColumnsToContent(this.ListView_Solution, null);

                var lastResult    = results.Last();
                int decimalPlaces = UIHelper.CountDigitsAfterDecimal(TextBox_InputEpsilon.Text);


                this.FC_Aproximation.Formula        = lastResult.B.ToString();
                this.FC_AproximationRounded.Formula = Math.Round(lastResult.B, decimalPlaces).ToString();
                this.FC_AproximationChopped.Formula = UIHelper.TruncateDecimal((decimal)lastResult.B, decimalPlaces).ToString();

                SnackBarNotif.MessageQueue.Enqueue(
                    UIHelper.NewSnackbarMessage(
                        PackIconKind.KeyboardVariant,
                        "Success! Check solution and results!",
                        Colors.DarkGreen,
                        0.5
                        )
                    );
            }
            catch {
                //show error message
                SnackBarNotif.MessageQueue.Enqueue(
                    UIHelper.NewSnackbarMessage(
                        PackIconKind.KeyboardVariant,
                        "Invalid Input! Function Input (Value to Aprox.) syntax is invalid!",
                        Colors.HotPink,
                        0.5
                        )
                    );
            }
        }
        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(2);
                switch (method)
                {
                case 0:
                    // take the solution and add or substract 1 or 2
                    wrongAnswer = solution + new Random().Next(-3, 4);
                    break;

                default:
                    // just roll something in the range of the solution
                    int range = Math.Abs(solution / 2) + 5;
                    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);
        }
Esempio n. 22
0
 public static List <Expression> ParseSequence(string raw)
 {
     try
     {
         List <Expression> ret = new List <Expression>();
         StringBuilder     sb  = new StringBuilder();
         foreach (var item in raw.Split(',').ToList())
         {
             ret.Add(Infix.ParseOrThrow(item.Replace(",", "")));
             sb.Append(LaTeX.Print(Infix.ParseOrThrow(item.Replace(",", ""))) + ",");
         }
         System.Windows.Forms.Clipboard.SetText(sb.ToString());
         // Console.WriteLine("Successfully parsed sequence: " + sb.ToString());
         return(ret);
     }
     catch
     {
         Console.WriteLine("Sequence was in the incorrect format, remember to seperate items by a comma!");
         return(null);
     }
 }
Esempio n. 23
0
        public static List <double> Coeficients(
            string strT,
            string strS,
            string strF,
            double q,
            int n)
        {
            Expression T, s, f;

            try
            {
                T = Infix.ParseOrThrow(strT);
                s = Infix.ParseOrThrow(strS);
                f = Infix.ParseOrThrow(strF);
            }
            catch (Exception ex)
            {
                throw new FunctionParseException("Failed to parse function", ex);
            }

            double h = 1 / (double)n;

            var mainDiagonal  = MainDiagonal(T, s, n);
            var subDiagonal   = SubDiagonal(T, s, n);
            var superDiagonal = new List <double>(subDiagonal);

            subDiagonal.Insert(0, 0);
            superDiagonal.Add(0);
            var constantTerms = ConstantTerms(f, q, n);

            var coefs = TridiagonalMatrixAlgorithm(
                subDiagonal,
                mainDiagonal,
                superDiagonal,
                constantTerms);

            coefs.Add(0);

            return(coefs);
        }
Esempio n. 24
0
        public static double EvaluateFunction(double t, double y, string function)
        {
            SymbolicExpression expression = Infix.ParseOrThrow(function);
            Dictionary <string, FloatingPoint> variables = new Dictionary <string, FloatingPoint>
            {
                { "t", t },
                { "y", y }
            };

            double result;

            try
            {
                result = expression.Evaluate(variables).RealValue;
            }
            catch (Exception)
            {
                result = 0;
            }

            return(result);
        }
Esempio n. 25
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);
        }
Esempio n. 26
0
 public static void initFunctions(string a, string b, string f1In, string f2In)
 {
     try
     {
         x0 = double.Parse(a);
         y0 = double.Parse(b);
         x  = Expr.Symbol("x");
         y  = Expr.Symbol("y");
         //Functions should be declared before compilation
         var parsedF1 = Infix.ParseOrThrow(f1In);
         var parsedF2 = Infix.ParseOrThrow(f2In);
         f1 = parsedF1;
         f2 = parsedF2;
     }
     catch (Exception ex)
     {
         Console.ForegroundColor = ConsoleColor.Red;
         Console.Error.WriteLine(ex.Message);
         Console.ReadKey();
         Environment.Exit(-1);
     }
     //But can be given from input
 }
Esempio n. 27
0
        internal SolveChallenge(int answerCount = 4, int minNum = STD_MIN_NUM, int maxNum = STD_MAX_NUM, bool dummy = false)
        {
            QuestionNodeHeight = 340f;
            NodeHeight         = 320f;
            CreateAnswerArrays(answerCount);
            if (dummy)
            {
                return;
            }

            // prepare the RNG
            var rng = new Random();

            // choose the variables
            string[] signs     = new string[3];
            string[] variables = new string[3];
            for (int i = 0; i < variables.Length; i++)
            {
                if (rng.NextBoolean())
                {
                    // choose a letter
                    switch (rng.Next(9))
                    {
                    case 0: variables[i] = "a"; break;

                    case 1: variables[i] = "b"; break;

                    case 2: variables[i] = "c"; break;

                    case 3: variables[i] = "y"; break;

                    case 4: variables[i] = "t"; break;

                    case 5: variables[i] = "k"; break;

                    case 6: variables[i] = "i"; break;

                    case 7: variables[i] = "s"; break;

                    case 8: variables[i] = "p"; break;

                    case 9: variables[i] = "r"; break;
                    }
                }
                else
                {
                    // choose a number
                    if (rng.NextBoolean())
                    {
                        variables[i] = rng.Next(minNum, maxNum).ToString();
                    }
                    else
                    {
                        variables[i] = 1.ToString();
                    }
                }
                if (rng.Next(4) == 0)
                {
                    signs[i] = "-";
                }
                else
                {
                    signs[i] = "";
                }
            }

            // create the challenge
            const string LA_MUL        = @"\cdot";
            var          challengeType = rng.Next(5);
            string       side1Infix    = "";
            string       side1LaTeX    = "";
            string       side2Infix    = "";
            string       side2LaTeX    = "";

            bool NegStr(string str)
            {
                return(str.StartsWith("-"));
            }

            string SignedVar(int i)
            {
                return(signs[i] + variables[i]);
            }

            string MulFromLeft(int i)
            {
                return(variables[i].Equals("1") ? signs[i] : SignedVar(i) + " " + LA_MUL + " ");
            }

            string MulStrFromLeft(string str)
            {
                return(str.Equals("1") ? "" : (str.Equals("-1") ? "-" : str + " " + LA_MUL + " "));
            }

            string AddFromRight(string str)
            {
                return((NegStr(str) ? "" : " + ") + str);
            }

            string SubFromRight(string str)
            {
                return(NegStr(str) ? " + " + str.Substring(1) : str);
            }

            switch (challengeType)
            {
            case 0:
            {
                side1Infix = SignedVar(0);
                side1LaTeX = SignedVar(0);
                side2Infix = "x * " + SignedVar(1) + " + x * " + SignedVar(2);
                side2LaTeX = MulFromLeft(1) + "x" + AddFromRight(MulFromLeft(2) + "x");
            }
            break;

            case 1:
            {
                side1Infix = SignedVar(0) + " * x";
                side1LaTeX = MulFromLeft(0) + "x";
                side2Infix = SignedVar(1) + " + " + SignedVar(2) + " * x";
                side2LaTeX = SignedVar(1) + AddFromRight(MulFromLeft(2) + "x");
            }
            break;

            case 2:
            {
                side1Infix = "(" + SignedVar(0) + " + " + SignedVar(1) + ") / x";
                side1LaTeX = @"\frac{" + SignedVar(0) + AddFromRight(SignedVar(1)) + "}{ x }";
                side2Infix = SignedVar(2);
                side2LaTeX = SignedVar(2);
            }
            break;

            case 3:
            {
                side1Infix = SignedVar(0) + " + " + SignedVar(1);
                side1LaTeX = SignedVar(0) + AddFromRight(SignedVar(1));
                side2Infix = "x / " + SignedVar(2);
                side2LaTeX = @"\frac{ x }{" + SignedVar(2) + "}";
            }
            break;

            case 4:
            {
                side1Infix = SignedVar(0) + " / " + SignedVar(1);
                side1LaTeX = @"\frac{" + SignedVar(0) + "}{" + SignedVar(1) + "}";
                side2Infix = SignedVar(2) + " / x";
                side2LaTeX = @"\frac{" + SignedVar(2) + "}{ x }";
            }
            break;
            }
            // shuffle the sides
            if (rng.NextBoolean())
            {
                ChallengeInfix = side1Infix + " = " + side2Infix;
                ChallengeLaTeX = side1LaTeX + " = " + side2LaTeX;
            }
            else
            {
                ChallengeInfix = side2Infix + " = " + side1Infix;
                ChallengeLaTeX = side2LaTeX + " = " + side1LaTeX;
            }

            // create the solution
            switch (challengeType)
            {
            case 0:
            {
                SolutionInfix = SignedVar(0) + " / (" + SignedVar(1) + " + " + SignedVar(2) + ")";
                // the following SolutionLaTeX-commands are commented out, because it's simply better (more beautiful/ easier to read) to use Latex.Format
                //SolutionLaTeX = @"x = \frac{" + SignedVar(0) + "}{" + SignedVar(1) + AddFromRight(SignedVar(2)) + "}";
            }
            break;

            case 1:
            {
                SolutionInfix = SignedVar(1) + " / (" + SignedVar(0) + " - " + SignedVar(2) + ")";
                //SolutionLaTeX = @"x = \frac{" + SignedVar(1) + "}{" + SignedVar(0) + SubFromRight(SignedVar(2)) + "}";
            }
            break;

            case 2:
            {
                SolutionInfix = "(" + SignedVar(0) + " + " + SignedVar(1) + ") / " + SignedVar(2);
                //SolutionLaTeX = @"x = \frac{" + SignedVar(0) + AddFromRight(SignedVar(1)) + "}{" + SignedVar(2) + "}";
            }
            break;

            case 3:
            {
                SolutionInfix = "(" + SignedVar(0) + " + " + SignedVar(1) + ") * " + SignedVar(2);
                //SolutionLaTeX = "x = " + MulStrFromLeft("(" + SignedVar(0) + AddFromRight(SignedVar(1)) + ")") + SignedVar(2);
            }
            break;

            case 4:
            {
                SolutionInfix = "(" + SignedVar(2) + " * " + SignedVar(1) + ") / " + SignedVar(0);
                //SolutionLaTeX = @"x = \frac{" + MulFromLeft(2) + SignedVar(1) + "}{" + SignedVar(0) + "}";
            }
            break;
            }
            SolutionLaTeX = "x = " + LaTeX.Format(Infix.ParseOrThrow(SolutionInfix));
            // map it to a random answer
            int solutionIndex = rng.Next(answerCount);

            AnswersInfix[solutionIndex] = SolutionInfix;
            AnswersLaTeX[solutionIndex] = SolutionLaTeX;

            // generate the false answers
            for (int i = 0; i < answerCount; i++)
            {
                // don't overwrite the solution
                if (i == solutionIndex)
                {
                    continue;
                }
                // choose a random algorithm to create the next answer
                bool[] alreadyTried = new bool[7];
                string infix        = Infix.ParseOrThrow(SolutionInfix).Equals(0) ? "1" : "0";
                int    method       = -1;
                bool   ok           = false;
                for (int tries = 0; tries < 30 && !ok; tries++)
                {
                    var whileTries = 0;
                    switch (challengeType)
                    {
                    case 0:
                    {
                        do
                        {
                            whileTries++;
                            if (method != -1)
                            {
                                alreadyTried[method] = true;
                            }
                            method = rng.Next(7);
                            switch (method)
                            {
                            case 0:
                            {
                                infix = "(" + SignedVar(0) + " - " + SignedVar(2) + ") / " + SignedVar(1);
                            }
                            break;

                            case 1:
                            {
                                infix = SignedVar(0) + " - " + SignedVar(1) + " - " + SignedVar(2);
                            }
                            break;

                            case 2:
                            {
                                infix = SignedVar(0) + " - (" + SignedVar(1) + " + " + SignedVar(2) + ")";
                            }
                            break;

                            case 3:
                            {
                                infix = SignedVar(0) + " / (" + SignedVar(1) + " * " + SignedVar(2) + ")";
                            }
                            break;

                            case 4:
                            {
                                infix = SignedVar(1) + " + " + SignedVar(2);
                            }
                            break;

                            case 5:
                            {
                                infix = SignedVar(1) + " / (" + SignedVar(0) + " + " + SignedVar(2) + ")";
                            }
                            break;

                            case 6:
                            {
                                infix = SignedVar(2) + " / (" + SignedVar(0) + " + " + SignedVar(1) + ")";
                            }
                            break;
                            }
                        }while (alreadyTried[method] && whileTries < 14);
                    }
                    break;

                    case 1:
                    {
                        do
                        {
                            whileTries++;
                            if (method != -1)
                            {
                                alreadyTried[method] = true;
                            }
                            method = rng.Next(6);
                            switch (method)
                            {
                            case 0:
                            {
                                infix = SignedVar(1) + " / (" + SignedVar(2) + " - " + SignedVar(0) + ")";
                            }
                            break;

                            case 1:
                            {
                                infix = SignedVar(0) + " / (" + SignedVar(1) + " + " + SignedVar(2) + ")";
                            }
                            break;

                            case 2:
                            {
                                infix = "(" + SignedVar(0) + " + " + SignedVar(1) + ") / " + SignedVar(2);
                            }
                            break;

                            case 3:
                            {
                                infix = "(" + SignedVar(2) + " * " + SignedVar(1) + ") /" + SignedVar(0);
                            }
                            break;

                            case 4:
                            {
                                infix = "(" + SignedVar(0) + " + " + SignedVar(1) + ") *" + SignedVar(2);
                            }
                            break;

                            case 5:
                            {
                                infix = "(" + SignedVar(0) + " + " + SignedVar(2) + ") /" + SignedVar(1);
                            }
                            break;
                            }
                        }while (alreadyTried[method] && whileTries < 14);
                    }
                    break;

                    case 2:
                    {
                        do
                        {
                            whileTries++;
                            if (method != -1)
                            {
                                alreadyTried[method] = true;
                            }
                            method = rng.Next(6);
                            switch (method)
                            {
                            case 0:
                            {
                                infix = SignedVar(0) + " / (" + SignedVar(1) + " + " + SignedVar(2) + ")";
                            }
                            break;

                            case 1:
                            {
                                infix = SignedVar(1) + " / (" + SignedVar(0) + " - " + SignedVar(2) + ")";
                            }
                            break;

                            case 2:
                            {
                                infix = "1 / (" + SignedVar(2) + " - " + SignedVar(0) + " - " + SignedVar(1) + ")";
                            }
                            break;

                            case 3:
                            {
                                infix = "(" + SignedVar(0) + " + " + SignedVar(2) + ") /" + SignedVar(1);
                            }
                            break;

                            case 4:
                            {
                                infix = "(" + SignedVar(1) + " + " + SignedVar(2) + ") /" + SignedVar(0);
                            }
                            break;

                            case 5:
                            {
                                infix = "(" + SignedVar(1) + " - " + SignedVar(0) + ") /" + SignedVar(2);
                            }
                            break;
                            }
                        }while (alreadyTried[method] && whileTries < 14);
                    }
                    break;

                    case 3:
                    {
                        do
                        {
                            whileTries++;
                            if (method != -1)
                            {
                                alreadyTried[method] = true;
                            }
                            method = rng.Next(6);
                            switch (method)
                            {
                            case 0:
                            {
                                infix = "(" + SignedVar(0) + " + " + SignedVar(1) + ") /" + SignedVar(2);
                            }
                            break;

                            case 1:
                            {
                                infix = SignedVar(0) + " / (" + SignedVar(1) + " + " + SignedVar(2) + ")";
                            }
                            break;

                            case 2:
                            {
                                infix = SignedVar(1) + " / (" + SignedVar(0) + " - " + SignedVar(2) + ")";
                            }
                            break;

                            case 3:
                            {
                                infix = "(" + SignedVar(0) + " + " + SignedVar(2) + ") *" + SignedVar(1);
                            }
                            break;

                            case 4:
                            {
                                infix = "(" + SignedVar(1) + " + " + SignedVar(2) + ") *" + SignedVar(0);
                            }
                            break;

                            case 5:
                            {
                                infix = "(" + SignedVar(2) + " - " + SignedVar(1) + ") *" + SignedVar(0);
                            }
                            break;
                            }
                        }while (alreadyTried[method] && whileTries < 14);
                    }
                    break;

                    case 4:
                    {
                        do
                        {
                            whileTries++;
                            if (method != -1)
                            {
                                alreadyTried[method] = true;
                            }
                            method = rng.Next(6);
                            switch (method)
                            {
                            case 0:
                            {
                                infix = SignedVar(0) + " / (" + SignedVar(1) + " + " + SignedVar(2) + ")";
                            }
                            break;

                            case 1:
                            {
                                infix = SignedVar(1) + " / (" + SignedVar(0) + " - " + SignedVar(2) + ")";
                            }
                            break;

                            case 2:
                            {
                                infix = "(" + SignedVar(0) + " * " + SignedVar(1) + ") /" + SignedVar(2);
                            }
                            break;

                            case 3:
                            {
                                infix = "(" + SignedVar(0) + " * " + SignedVar(2) + ") /" + SignedVar(1);
                            }
                            break;

                            case 4:
                            {
                                infix = SignedVar(2) + " / (" + SignedVar(0) + " * " + SignedVar(1) + ")";
                            }
                            break;

                            case 5:
                            {
                                infix = SignedVar(0) + " / (" + SignedVar(2) + " * " + SignedVar(1) + ")";
                            }
                            break;
                            }
                        }while (alreadyTried[method] && whileTries < 14);
                    }
                    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(infix))
                        {
                            ok = false;
                        }
                    }
                    // check if the answer is actually a solution
                    if (IsSolution(infix))
                    {
                        ok = false;
                        tries--;
                    }
                }
                AnswersInfix[i] = infix;
                AnswersLaTeX[i] = "x = " + LaTeX.Format(Infix.ParseOrThrow(AnswersInfix[i]));
            }
        }
Esempio n. 28
0
        private void Algorithm()
        {
            _main.Header();
            var result = "U(";
            var p_values = "";
            var xi = "";
            for (int i = 1; i <= _main.CountParams; i++)
            {
               

                if (i == _main.CountParams)
                {
                    xi += "x_" + i;
                    _alpha_ln_xi += _main.ConvertCommaToDot(_alpha[i - 1].ToString()) + "*\\ln(x_" + i + ")";

                }
                else
                {
                    xi += "x_" + i + ",";
                    _alpha_ln_xi += _main.ConvertCommaToDot(_alpha[i - 1].ToString()) + "*\\ln(x_" + i + ") + ";

                }


                p_values += "p_" + i + " = " + _main.ConvertCommaToDot(_main.PValuesParams[i - 1]);
                _pi += "p_" + i;
                if (i < _main.CountParams)
                {
                    _pi += "," + _main.SetText(" ");
                    p_values += ",";
                }
            }

            _main.ResultCollection.Add(_main.RedLine);
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(result + xi + ")=" + _alpha_ln_xi), Align = HorizontalAlignment.Center });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(p_values), Align = HorizontalAlignment.Center });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Решение:", true)) });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("1. Решим задачу оптимального поведения потребителя, если цены благ соответственно равны ", true)) });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(p_values + _main.SetText(" и доход равен ") + "M = " + _main.MParam + ".") });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Найдем функции спроса потребителя:", true)) });

            for (int i = 1; i <= _main.CountParams; i++)
            {
                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula("x_" + i + " = f_" + i + "(" + _pi + ",M);"), Align = HorizontalAlignment.Center });
            }

            result = _main.SetText("где ");
            var blag = "";
            for (int i = 1; i <= _main.CountParams; i++)
            {
                _xi += "x_" + i;
                blag += i + "-го";
                if (i < _main.CountParams)
                {
                    _xi += ", ";

                }

                if (i < _main.CountParams - 1)
                {
                    blag += ", ";
                }
                else if (i == _main.CountParams - 1)
                {
                    blag += " и ";
                }
            }

            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(result + _xi + _main.SetText(" - количество приобретаемого блага " + blag + " вида.")) });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Для этого решим следующую задачу оптимального поведения потребителя.", true)) });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Математическая модель задачи имеет вид:")) });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(@"\alpha_j > 0, x_j > 0, j = \overline{1, " + _main.CountParams +"}" + _main.SetText("           (1)")), Align = HorizontalAlignment.Center });


            for (int i = 1; i <= _main.CountParams; i++)
            {
                _pi_xi += "x_" + i + "*p_" + i;
                _minus_pi_xi += "- x_" + i + "*p_" + i;

                if (i < _main.CountParams)
                {
                    _pi_xi += " + ";
                    _minus_pi_xi += " ";
                }

            }
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_pi_xi + " = M" + _main.SetText("            (2)")), Align = HorizontalAlignment.Center });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula("U = " + _alpha_ln_xi + " \\rightarrow max" + _main.SetText("            (3)")), Align = HorizontalAlignment.Center });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Левая часть условия (2) – стоимость приобретаемых благ, а условие (3) означает, что полезность этих", true)) });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("благ должна быть максимальной.")) });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Решим задачу методом множителей Лагранжа. Функция Лагранжа:", true)) });

            result = "L(" + _xi + ",\\lambda) = U(" + _xi + ") + \\lambda(M " + _minus_pi_xi + ").";


            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + result) });
            result = "L(" + _xi + ",\\lambda) = " + _alpha_ln_xi + " + \\lambda(M " + _minus_pi_xi + ").";
            _L = _alpha_ln_xi + "+" + _lambda + "*(" + _M + _minus_pi_xi + ")";
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + result) });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Найдем частные производные функции Лагранжа и приравняем их к нулю:", true)) });

            for (int i = 0; i < _main.CountParams; i++)
            {
                _lst.Add(_main.Diff(_L.Replace("\\", ""), _variables[i]));
                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + @"\frac{\partial L}{\partial x_" + (i + 1) + "} = " + (_lst[i] as Expr).ToLaTeX().Replace(_lambda, @"\lambda") + " = 0") });
            }
            
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + @"\frac{\partial L}{\partial \lambda } = " + _M + _minus_pi_xi + " = 0") });
            _main.ResultCollection.Add(_main.RedLine);
            for (int i = 0; i < _lst.Count; i++)
            {
                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + (_lst[i] as Expr).Substitute(Expr.Parse("p_" + (i + 1)), Expr.Parse("0")).ToLaTeX() + " = " + @"\lambda*p_" + (i + 1)) });
            }
            _main.ResultCollection.Add(_main.RedLine);
            for (int i = 0; i < _lst.Count; i++)
            {

                var root = _main.FindRoot(ExprLast.Symbol("x_" + (i + 1)), Infix.ParseOrThrow((_lst[i] as Expr).ToString()));
                _lst.RemoveAt(i);
                _lst.Insert(i, root);

                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + "x_" + (i + 1) + " = " + (_lst[i] as Expr).ToLaTeX().Replace(_lambda, @"\" + _lambda)) });

            }
            _main.ResultCollection.Add(_main.RedLine);
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + _pi_xi + " = " + _M + _main.SetText("          (4)")) });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Подставим найденные значения ", true) + _xi + _main.SetText(" в (4) и выразим ") + @"\" + _lambda) });
            result = _pi_xi;
            for (int i = 0; i < _lst.Count; i++)
            {
                var expr = Expr.Parse(result).Substitute(Expr.Parse("x_" + (i + 1)), _lst[i] as Expr);
                result = _main.ConvertExprLastToExpr(Rational.Simplify(ExprLast.Symbol("x_" + (i + 1)), _main.ConvertExprToExprLast(expr))).ToString();
            }
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + Expr.Parse(result).ToLaTeX().Replace(_lambda, @"\" + _lambda) + " = " + _M) });

                
            result += "-" + _M;
            var lam_star = _main.FindRoot(ExprLast.Symbol(_lambda), Infix.ParseOrThrow(result));
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + @"\lambda^* = " + lam_star.ToLaTeX() + " = " + lam_star.Substitute("M", _main.MParam).ToLaTeX()) });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + _main.SetText(@"Найдем оптимальный набор благ потребителя.")) });
            result = @"X^* = (";

            for (int i = 0; i < _main.CountParams; i++)
            {
                result += "x_" + (i + 1) + "^*";
                if (i < _main.CountParams - 1)
                {
                    result += ",";
                }
            }
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + result + ")" + _main.SetText(@" при заданных ценах на блага и доходе:")) });
            _main.ResultCollection.Add(_main.RedLine);



            for (int i = 0; i < _main.CountParams; i++)
            {
                var res = (_lst[i] as Expr).Substitute(Expr.Parse(_lambda), lam_star);
                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + "x_" + (i + 1) + "^* = " + res.ToLaTeX()) });
                _lst[i] = res;
            }
            _main.ResultCollection.Add(_main.RedLine);
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + p_values + ", M = " + _main.ConvertCommaToDot(_main.MParam)) });
            _main.ResultCollection.Add(_main.RedLine);
            
            for (int i = 0; i < _main.CountParams; i++)
            {
                var res = (_lst[i] as Expr).Substitute(Expr.Parse(_M), Expr.Parse(_main.ConvertCommaToDot(_main.MParam))).Substitute(Expr.Parse("p_" + (i + 1)), Expr.Parse(_main.ConvertCommaToDot(_main.PValuesParams[i])));
                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + "x_" + (i + 1) + "^* = " + res.ToLaTeX()) });
                _x_star[i] = double.Parse(_main.ConvertDotToComma(res.RealNumberValue.ToString()));
            }
            result = @"X^* = (";

            for (int i = 0; i < _main.CountParams; i++)
            {
                result += "x_" + (i + 1) + "^*";
                if (i < _main.CountParams - 1)
                {
                    result += ",";
                }
            }

            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Проверим, выполняется ли для найденного оптимального решения ", true) + result + _main.SetText(") бюджетное ограничение:")) });

            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_pi_xi + " = M"), Align = HorizontalAlignment.Center });

            result = "";

            for (int i = 0; i < _main.CountParams; i++)
            {
                result += _main.ConvertCommaToDot(_main.PValuesParams[i]) + "*" + _main.ConvertCommaToDot(_x_star[i]);
                if (i < _main.CountParams - 1)
                {
                    result += "+";
                }
            }
            _main.ResultCollection.Add(_main.RedLine);
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(result + " = " + _main.ConvertCommaToDot(_main.MParam)), Align = HorizontalAlignment.Center });
            _main.ResultCollection.Add(_main.RedLine);
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(Expr.Parse(result).ToLaTeX() + " = " + _main.ConvertCommaToDot(_main.MParam)), Align = HorizontalAlignment.Center });

            result = @"\overline{ X}^ * = (" + _x_star.Aggregate("", (b, n) => b + (!string.IsNullOrEmpty(b) ? ";" : "") + Math.Truncate(n).ToString()) + ")";
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Если речь идет о неделимых благах, то оптимальный выбор потребителя составит ", true) + result + ",") });

            result = _main.SetText(" т.е. ему необходимо приобрести ");
            for (int i = 0; i < _main.CountParams; i++)
            {
                result += (i + 1) + _main.SetText("-го блага - ") + _main.ConvertCommaToDot(Math.Truncate(_x_star[i]));

                if (i < _main.CountParams - 2)
                {
                    result += ", ";
                }
                if (i < _main.CountParams - 1)
                {
                    result += _main.SetText(" и ");
                }
            }

            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(result + ".") });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Но т.к. мы условились, что речь будет идти о делимых благах, то оптимальный выбор потребителя будет:", true)) });

            result = @"\overline{ X}^ * = (" + _x_star.Aggregate("", (b, n) => b + (!string.IsNullOrEmpty(b) ? ";" : "") + _main.ConvertCommaToDot(n.ToString())) + ")";
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + result + _main.SetText(", т.е. следует приобрести: ")) });


            for (int i = 0; i < _main.CountParams; i++)
            {
                result = _main.SetText("блага ", true) + (i + 1) + _main.SetText("-го вида - ") + _main.ConvertCommaToDot(_x_star[i]);

                if (i < _main.CountParams - 1)
                {
                    result += ", ";
                }
                if (i == _main.CountParams - 1)
                {
                    result += ".";
                }
                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(result) });
            }
            _main.ResultCollection.Add(_main.RedLine);
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Решение 2:", true)) });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Функции спроса потребителя найдены в пункте 1.", true)) });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Вычислим реакции потребителя при изменении дохода М и цен ", true) + _pi + _main.SetText(" в точке оптимума ") + @"\overline{ X}^ *.") });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Реакции потребителя при изменении дохода М:", true)) });

            var minBlag = -1.0;
            var maxBlag = -1.0;
            var indMinBlag = -1;
            var indMaxBlag = -1;
            for (int i = 0; i < _main.CountParams; i++)
            {
                var res = _main.Diff((_lst[i] as Expr).ToString(), "M");
                var p = Expr.Parse(_main.ConvertCommaToDot(_main.PValuesParams[i].ToString()));
                var val = double.Parse(_main.ConvertDotToComma(res.Substitute(Expr.Parse("p_" + (i + 1)), p).RealNumberValue.ToString()));
                if (i == 0)
                {
                    minBlag = maxBlag = val;
                    indMinBlag = indMaxBlag = i;
                }
                if (val < minBlag)
                {
                    minBlag = val;
                    indMinBlag = i;
                }
                if (val > maxBlag)
                {
                    maxBlag = val;
                    indMaxBlag = i;
                }
                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + @"\frac{\partial x_" + (i + 1) + @"}{\partial M } = " + res.ToLaTeX() + @"\approx" + _main.ConvertCommaToDot(val.ToString())) });
                if (i == 0)
                {
                    _main.ResultCollection.Add(_main.RedLine);
                    _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Поскольку при увеличении дохода спрос на 1-благо возрастает, то это благо ценное.", true)) });
                    _main.ResultCollection.Add(_main.RedLine);
                }
            }

            if (_main.CountParams == 2)
            {
                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Оставшееся благо также является ценным для потребителя.  При этом наиболее ценным является " + (indMaxBlag + 1) + "-е благо, а наименее ценным – " + (indMinBlag + 1) + "-е.", true)) });
            }
            else
            {
                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Остальные блага также являются ценными для потребителя.  При этом наиболее ценным является " + (indMaxBlag + 1) + "-е благо, а наименее ценным – " + (indMinBlag + 1) + "-е.", true)) });

            }


           
            for (int i = 0; i < _main.CountParams; i++)
            {
                _main.ResultCollection.Add(_main.RedLine);
                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Определим реакции потребителя     при изменении цены на " + (i + 1) + "-е благо:", true)) });
                for (int j = 0; j < _main.CountParams; j++)
                {
                    
                    _main.ResultCollection.Add(_main.RedLine);
                    var res = _main.Diff((_lst[i] as Expr).ToString(), "p_" + (i + 1));
                    var m = Expr.Parse(_main.ConvertCommaToDot(_main.MParam.ToString()));
                    var p = Expr.Parse(_main.ConvertCommaToDot(_main.PValuesParams[j].ToString()));
                    var val = double.Parse(_main.ConvertDotToComma(res.Substitute(Expr.Parse("M"), m).Substitute(Expr.Parse("p_" + (i + 1)), p).RealNumberValue.ToString()));
                    _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + @"\frac{\partial x_" + (j + 1) + @"}{\partial p_" + (i + 1) + " } = " + res.ToLaTeX() + (val == 0 ? "=" : @"\approx") + _main.ConvertCommaToDot(val.ToString()) + (val != 0 ? " (" + (val >= 0 ? ">" : "<") + "0)" : "")) });
                    if (i == j && val < 0)
                    {
                        _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("С увеличением цены на " + (i + 1) + "-е благо спрос на него уменьшается, значит, "+ (j+1)+"-е благо нормальное.", true)) });
                    }
                    else if (i == j && val > 0)
                    {
                        _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("С увеличением цены на " + (i + 1) + "-е благо спрос на него уменьшается, значит, " + (j + 1) + "-е благо ненормальное.", true)) });
                    }
                    else if (val < 0)
                    {
                        _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("С увеличением  цены на " + (i + 1) + "-е благо спрос на " + (j + 1) + "-е благо увеличивается, эти блага взаимодополняемые.", true)) });
                    }
                    else if (val > 0)
                    {
                        _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("С увеличением  цены на " + (i + 1) + "-е благо спрос на " + (j + 1) + "-е благо увеличивается, эти блага взаимозаменяемые.", true)) });
                    }
                   
                }

            }

           
            result = @"\overline{ X}^ * = (";

            for (int i = 0; i < _main.CountParams; i++)
            {
                result += "x_" + (i + 1) + "^*";
                if (i < _main.CountParams - 1)
                {
                    result += ",";
                }
            }

            _main.ResultCollection.Add(_main.RedLine);
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Решение3:", true)) });
            _main.ResultCollection.Add(new Result()
            {
                ItemResult = _main.RenderFormula(_main.SetText("Вычислим предельные полезности благ в точке экстремума ", true) + result + ")" +
                _main.SetText(". Это значения частных производных "))
            });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("функции полезности ") + "U = (" + _xi + ")" + _main.SetText(" по соответствующим аргументам в точке ") + @"\overline{ X}^*.") });

            _main.ResultCollection.Add(_main.RedLine);
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(@"\overline{ X}^ * = (" + _x_star.Aggregate("", (b, n) => b + (!string.IsNullOrEmpty(b) ? ";" : "") + _main.ConvertCommaToDot(n.ToString())) + ")") });

            var dU_x_star = new double[_main.CountParams];
            for (int i = 0; i < _main.CountParams; i++)
            {
                _main.ResultCollection.Add(_main.RedLine);
                var res = _main.Diff(_alpha_ln_xi.Replace("\\", ""), "x_" + (i + 1));
                var x = Expr.Parse(_main.ConvertCommaToDot(_x_star[i].ToString()));
                var val = double.Parse(_main.ConvertDotToComma(res.Substitute(Expr.Parse("x_" + (i + 1)), x).RealNumberValue.ToString()));
                dU_x_star[i] = val;
                _main.ResultCollection.Add(new Result()
                {
                    ItemResult = _main.RenderFormula(_main.SetText("", true) + @"\frac{\partial U}{\partial x_" + (i + 1) + " } = " + res.ToLaTeX() + _main.SetText(";    ") +
                    @"\frac{\partial U}{\partial x_" + (i + 1) + " }(\\overline{ X})^* = " + res.ToLaTeX() + _main.SetText(" = ") + _main.ConvertCommaToDot(val.ToString()))
                    
                });
            }


            _main.ResultCollection.Add(_main.RedLine);
            for (int i = 0; i < _main.CountParams; i++)
            {
                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("На 1 дополнительную единицу " + (i + 1) + "-го блага приходится ", true) + dU_x_star[i] + _main.SetText(" единиц дополнительной полезности.")) });

            }

            _main.ResultCollection.Add(_main.RedLine);
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Решение4:", true)) });

            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Вычислим нормы замещения благ в точке оптимума ", true) + "\\overline{X}^*.") });

            for (int i = 0; i < _main.CountParams; i++)
            {

                for (int j = 0; j < _main.CountParams; j++)
                {
                    if (i == j)
                        continue;

                    var dudx = dU_x_star[i] / dU_x_star[j];

                    _main.ResultCollection.Add(_main.RedLine);
                    _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Норма замены " + (i + 1) + "-го блага " + (j + 1) + "-м:", true)) });
                    _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + @"n_{" + (j + 1) + "," + (i + 1) + @"} = -\frac{\partial U}{\partial x_" + (i + 1) + @"} : \frac{\partial U}{\partial x_" + (j + 1) + "} = " + _main.ConvertCommaToDot((-dudx).ToString())) });
                    _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Для замещения 1 единицы " + (i + 1) + "-го блага необходимо дополнительно приобрести ", true) + _main.ConvertCommaToDot((dudx).ToString())) });
                    _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText(" единиц " + (j + 1) + "-го блага, чтобы удовлетворенность осталась на прежнем уровне.")) });
                }
            }

            _main.ResultCollection.Add(_main.RedLine);
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Решение5:", true)) });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Вычислим коэффициенты эластичности по доходу и ценам при заданных ценах и доходе: ", true)) });
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(p_values + ", M = " + _main.ConvertCommaToDot(_main.MParam.ToString()) + ".") });

            var empSum = 0.0;

            for (int i = 0; i < _main.CountParams; i++)
            {
                _main.ResultCollection.Add(_main.RedLine);
                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Для блага " + (i + 1) + ":", true)) });
                var res = _main.Diff((_lst[i] as Expr).ToString(), "M").Divide("x_" + (i + 1) + "/M");
                var resReplace = res.Substitute("M", _main.ConvertCommaToDot(_main.MParam.ToString())).Substitute("x_" + (i + 1), _main.ConvertCommaToDot(_x_star[i].ToString())).Substitute("p_" + (i + 1), _main.ConvertCommaToDot(_main.PValuesParams[i].ToString())).ToString();
                empSum = double.Parse(_main.ConvertDotToComma(resReplace));
                var resRound = Math.Round(empSum);
                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + @"E_" + (i + 1) + @"^M = \frac{\partial x_" + (i + 1) + @"}{\partial M } : " + @"\frac{ x_" + (i + 1) + "}{ M } = " + res.ToLaTeX() + " = " + resRound) });

                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("При увеличении дохода на 1 % спрос на " + (i + 1) + "-e благо возрастает на 1 %.", true)) });

                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Коэффициенты эластичности по ценам:", true)) });
                result = "E_" + (i + 1) + "^M + ";
                for (int j = 0; j < _main.CountParams; j++)
                {
                    result += "E_{ " + (i + 1) + "" + (j + 1) + "}^p";
                    if (j < _main.CountParams - 1)
                    {
                        result += " + ";
                    }
                    res = _main.Diff((_lst[i] as Expr).ToString(), "p_" + (j + 1)).Divide("x_" + (i + 1) + "/p_" + (j + 1));
                    resReplace = res.Substitute("M", _main.ConvertCommaToDot(_main.MParam.ToString())).Substitute("x_" + (i + 1), _main.ConvertCommaToDot(_x_star[i].ToString())).Substitute("p_" + (j + 1), _main.ConvertCommaToDot(_main.PValuesParams[i].ToString())).ToString();
                    var epi = double.Parse(_main.ConvertDotToComma(resReplace));
                    empSum += epi;
                    _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + @"E_{" + (i + 1) + "" + (j + 1) + @"}^p = \frac{\partial x_" + (i + 1) + @"}{\partial p_" + (j + 1) + " } : " + @"\frac{ x_" + (i + 1) + "}{ p_" + (j + 1) + " } = " + resReplace) });
                    
                    var output = "При росте цены на " + (j + 1) + "-е благо на 1 %";

                    if (epi != 0)
                    {
                        if (epi < 0)
                        {
                            output += " спрос на него уменьшается на ";
                        }
                        else
                        {
                            output += "спрос на него увеличивается на ";
                        }
                        _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText(output, true) + _main.ConvertCommaToDot(Math.Abs(epi).ToString()) + _main.SetText("%.")) });

                    }
                    else
                    {
                        output += " оно является независимым.";
                        _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText(output, true)) });
                    }
                    _main.ResultCollection.Add(_main.RedLine);

                }
                
                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Проверка:", true)) });
                _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("", true) + result + " = " + _main.ConvertCommaToDot(empSum.ToString())) });
            }
            _main.ResultCollection.Add(_main.RedLine);
            _main.ResultCollection.Add(new Result() { ItemResult = _main.RenderFormula(_main.SetText("Все расчеты произведены достаточно точно и правильно.", true)) });

        }
Esempio n. 29
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="expr"></param>
 public ExpressionC(string expr)
 {
     expressions.Add(this);
     infix = Infix.ParseOrThrow(expr);
 }
Esempio n. 30
0
 /// <summary>
 /// Allows you to change this expression without creating a new one
 /// </summary>
 /// <param name="infix"></param>
 public void SetInfix(string infix)
 {
     this.infix = Infix.ParseOrThrow(infix);
 }