public void DrawRegressionLine()
        {
            var theta = Fit.Line(Data.OrderBy(d => d.Item1).Select(d => d.Item1).ToArray(), Data.OrderBy(d => d.Item1).Select(d => d.Item2).ToArray());

            var x = Expr.Variable("x");
            var a = Expr.Variable("a");
            var b = Expr.Variable("b");

            a = System.Math.Round(theta.Item2, 2);
            b = System.Math.Round(theta.Item1, 2);

            Func <double, double> fx = (a * x + b).Compile("x");

            if (_regressionPlot != null)
            {
                Series.plt.Remove(_regressionPlot);
            }

            var x1 = Data.OrderBy(d => d.Item1).First().Item1;
            var y1 = fx(Data.OrderBy(d => d.Item1).First().Item1);
            var x2 = Data.OrderBy(d => d.Item1).Last().Item1;
            var y2 = fx(Data.OrderBy(d => d.Item1).Last().Item1);

            _regressionPlot = Series.plt.PlotLine(x1, y1, x2, y2, color: System.Drawing.Color.Red);

            Series.plt.PlotText($"{System.Math.Round(fx(25), 2)}", 17, fx(25), System.Drawing.Color.Red, fontSize: 16);
            Series.Render();

            ;
        }
예제 #2
0
        private void Substitute(DeclaredSymbol localSymbol, Dictionary <string, Expr> symbolExprs, bool src)
        {
            if (!(localSymbol is DeclaredVariableSymbol localVarSymbol))
            {
                return;
            }
            foreach ((string _, DeclaredSymbol symbol) in src ? this.srcSymbols : this.dstSymbols)
            {
                Expr replacement = localSymbol.GetInitSymbolValue(symbolExprs);
                switch (symbol)
                {
                case DeclaredVariableSymbol var:
                    var.SymbolicInitializer = var.SymbolicInitializer?.Substitute(localSymbol.Identifier, replacement);
                    break;

                case DeclaredArraySymbol arr:
                    // TODO
                    break;

                case DeclaredFunctionSymbol f:
                    // TODO
                    break;
                }
            }
        }
        static double function_R0(double p, double c, double k0, double k1)
        {
            var x          = CustomExpression.Variable("x");
            var func       = CustomExpression.Parse(_userFunctionText);                                                                   //q(x)
            var derivative = func.Differentiate(x);                                                                                       //q'(x)
            var equation   = derivative - k1 / k0 * 1 / (p - c);                                                                          // - k1/k0*1/(p-c) + q'(x) = 0
            var R0         = Convert.ToDouble(Regex.Matches((-equation[0] / equation[1]).ToString(), @"(\-)?\d+(\.\d+)?")[0].ToString()); //find R from equation and then extract double

            return(R0);
        }
        //runge kutta
        static Func <double, Vector <double>, Vector <double> > DerivativeMaker(double p, double c, double a_max, double k0)
        {
            return((t, Z) =>
            {
                double[] A = Z.ToArray();
                double P = A[0];
                double x = A[1];
                var userFunction = CustomExpression.Parse(_userFunctionText.Replace("x", x.ToString()));

                return Vector <double> .Build.Dense(new[] { (p - c) * userFunction.ComplexNumberValue.Real - a_max,
                                                            k0 *a_max - k0 *x + 1 });
            });
        }
예제 #5
0
        public MainWindowViewModel(Expr s)
        {
            _s = s;

            PlotCommand      = ReactiveCommand.Create(Plot);
            ResetViewCommand = ReactiveCommand.Create(ResetView);

            MagnitudePlot = new PlotModel {
                Title = "Magnitude"
            };

            _magnitudeFrequencyAxis = CreateFrequencyAxis(AxisPosition.Bottom);

            MagnitudePlot.Axes.Add(_magnitudeFrequencyAxis);
            MagnitudePlot.Axes.Add(InitializeAxis(new LinearAxis()
            {
                Position = AxisPosition.Left, Title = "|H(s)|", Unit = "dB", AxisTitleDistance = 32
            }));

            PhasePlot = new PlotModel {
                Title = "Phase"
            };

            _phaseFrequencyAxis = CreateFrequencyAxis(AxisPosition.Bottom);

            PhasePlot.Axes.Add(_phaseFrequencyAxis);
            PhasePlot.Axes.Add(InitializeAxis(new LinearAxis()
            {
                Position = AxisPosition.Left, Title = "∡H(s)", Unit = "°", Minimum = -180, Maximum = 180, MajorStep = 45, AxisTitleDistance = 32
            }));

            BodePlot = new PlotModel {
                Title = "Bode Plot"
            };

            _frequencyAxis = CreateFrequencyAxis(AxisPosition.Bottom);

            var magnitudeAxis = InitializeAxis(new LinearAxis()
            {
                Key = MagnitudeAxisKey, Title = "|H(s)|", Unit = "dB", Position = AxisPosition.Left, StartPosition = 0.5, EndPosition = 1
            });
            var phaseAxis = InitializeAxis(new LinearAxis()
            {
                Key = PhaseAxisKey, Title = "∡H(s)", Unit = "°", Minimum = -180, Maximum = 180, MajorStep = 45, Position = AxisPosition.Left, StartPosition = 0, EndPosition = 0.5
            });

            BodePlot.Axes.Add(_frequencyAxis);
            BodePlot.Axes.Add(magnitudeAxis);
            BodePlot.Axes.Add(phaseAxis);
        }
예제 #6
0
        public void ArithmeticExpressionTests()
        {
            this.AssertParse(
                new ArithmExprNode(1,
                                   new LitExprNode(1, 3),
                                   ArithmOpNode.FromSymbol(1, "+"),
                                   new LitExprNode(1, 1)
                                   ),
                Expr.Parse("4")
                );

            this.AssertParse(
                new ArithmExprNode(1,
                                   new IdNode(1, "x"),
                                   ArithmOpNode.FromSymbol(1, "+"),
                                   new LitExprNode(1, 1)
                                   ),
                Expr.Parse("1 + x")
                );

            this.AssertParse(
                new ArithmExprNode(1,
                                   new IdNode(1, "x"),
                                   ArithmOpNode.FromSymbol(1, "+"),
                                   new ArithmExprNode(1,
                                                      new IdNode(1, "x"),
                                                      ArithmOpNode.FromSymbol(1, "-"),
                                                      new LitExprNode(1, 1)
                                                      )
                                   ),
                Expr.Parse("-1 + 2*x")
                );

            this.AssertWildcardParse(
                new ArithmExprNode(1,
                                   new IdNode(1, "x"),
                                   ArithmOpNode.FromSymbol(1, "+"),
                                   new ArithmExprNode(1,
                                                      new IdNode(1, "x"),
                                                      ArithmOpNode.FromBitwiseSymbol(1, "<<"),
                                                      new LitExprNode(1, 1)
                                                      )
                                   ),
                "? + x"
                );
        }
예제 #7
0
        static void Main(string[] args)
        {
            var x = Expr.Variable("x");
            var y = Expr.Variable("y");

            //Example 1
            Func <double, double, double> func1 = (x * x - 2 * y).Compile("x", "y");

            DifEquation equation1 = new DifEquation(func1);

            double[] section1 = new double[] { 0, 1 };

            Dictionary <string, double> initialVal1 = new Dictionary <string, double>()
            {
                { "x", 0 },
                { "y", 1 }
            };

            RungeKutta rungeKutta1 = new RungeKutta(equation1, initialVal1, section1, 10);

            Console.WriteLine($"y' = {(x * x - 2 * y).ToString()}");

            rungeKutta1.Solve();

            //Example 2
            Func <double, double, double> func2 = ((y - x * y * y) / x).Compile("x", "y");

            DifEquation equation2 = new DifEquation(func2);

            double[] section2 = new double[] { 1, 2 };

            Dictionary <string, double> initialVal2 = new Dictionary <string, double>()
            {
                { "x", 1 },
                { "y", 2 }
            };

            RungeKutta rungeKutta2 = new RungeKutta(equation2, initialVal2, section2, 10);

            Console.WriteLine($"y' = {((y - x * y * y) / x).ToString()}");

            rungeKutta2.Solve();

            Console.ReadKey();
        }
예제 #8
0
        public override void OnFrameworkInitializationCompleted()
        {
            if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
            {
                var s  = Expr.Variable("s");
                var vm = new MainWindowViewModel(s);

                vm.TransferFunctionInput = "s / (s + 2 * pi * 100)";
                vm.PlotCommand.Execute(null);

                desktop.MainWindow = new MainWindow()
                {
                    DataContext = vm
                };
            }

            base.OnFrameworkInitializationCompleted();
        }
예제 #9
0
        public static double Y(double[] coefs, double pX)
        {
            Array.Reverse(coefs);

            var x = Expr.Variable("x");

            var curve = Expr.Parse(new Polynomial(coefs).ToString().Replace(",", ".").Replace("x", "*x"));
            var tang  = curve.Differentiate(x) * x;

            Func <double, double> fx = (curve).Compile("x");

            var xResult = fx(5);

            var xx = FindRoots.OfFunction(fx, -5, 5);

            return(tang.Evaluate(new Dictionary <string, MathNet.Symbolics.FloatingPoint> {
                { "x", pX }
            }).RealValue);
        }
        static double function_Simpson(double a, double b, double N, double[] R, double p, double c,
                                       double a_max, int i_first, int i_end)
        {
            double S, S1, S2 = 0, S3 = 0, h;
            int    i = 0, j, z = 0;

            double[] Y = new double[R.Length];
            h = (b - a) / N;

            for (i = i_first + 1; i < i_end; i++)
            {
                if (i_first > 0)
                {
                    j = i - i_end + i_first;//first integral
                }
                else
                {
                    j = i - 1;//second integral
                }

                Y[z] = (p - c) * (CustomExpression.Parse(_userFunctionText.Replace("x", R[j].ToString()))).RealNumberValue;//(p - c) * q(R(t))
                z++;
            }

            S1 = Y[0] + Y[R.Length - 1];

            for (i = 0; i < R.Length; i++)
            {
                if (i % 2 != 0)
                {
                    S3 += Y[i];
                }
                else
                {
                    S2 += Y[i];
                }
            }

            S = h / 3 * (S1 + 4 * S2 + 2 * S3); //Simpson

            return(S);
        }
예제 #11
0
        private static void ParseFunction()
        {
            while (true)
            {
                InputFunction();
                try
                {
                    _parsedFunction = Expr.Parse(_function);
                    break;
                }
                catch
                {
                    Console.WriteLine("Neteisingai įvesta funkcija, bandykite įvesti iš naujo.");
                    Console.WriteLine();
                }
            }

            Console.WriteLine("Sėkmingai pasirinkta funkcija: " + _parsedFunction.ToString());
            Console.WriteLine();
        }
예제 #12
0
 public void ConstantTests()
 {
     this.AssertParse(new LitExprNode(1, 3), Expr.Parse("3"));
     this.AssertParse(new LitExprNode(1, 4.3), Expr.Parse("4.3"));
     this.AssertParse(new NullLitExprNode(1), Expr.Undefined);
 }
예제 #13
0
 private void AssertParse(ASTNode node, Expr expected)
 => this.AssertParse(node, expected.ToString());
예제 #14
0
        private void Algorithm()
        {
            _main.Header();

            var result   = "U(";
            var p_values = "";
            var xi       = "";

            _A_x_st_alpha = _main.ConvertCommaToDot(_A.ToString()) + "*";
            for (int i = 1; i <= _main.CountParams; i++)
            {
                if (i == _main.CountParams)
                {
                    xi            += "x_" + i;
                    _A_x_st_alpha += "x_" + i + "^{" + _main.ConvertCommaToDot(_alpha[i - 1].ToString()) + "}";
                }
                else
                {
                    xi            += "x_" + i + ",";
                    _A_x_st_alpha += "x_" + i + "^{" + _main.ConvertCommaToDot(_alpha[i - 1].ToString()) + "} * ";
                }


                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 + ")=" + _A_x_st_alpha), 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(@"0 < \alpha_j < 1, x_j \geq 0, j = \overline{1, " + _main.CountParams + "}, a > 0" + _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 = " + _A_x_st_alpha + " \\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 + ").";

            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) = " + _A_x_st_alpha + " + \\lambda(M" + _minus_pi_xi + ").";
            _L     = _A_x_st_alpha + "+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(ReplaceBrackets(_L), "x_" + (i + 1)));
                _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++)
            {
                if (i == _lst.Count / 2)
                {
                    _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.SetText("      (4)"))
                    });
                }
                else
                {
                    _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);

            result = _main.SetText("Умножим в (4) ", true);
            for (int i = 0; i < _lst.Count; i++)
            {
                result += _main.SetText((i + 1) + "-e выражение на ") + "x_" + (i + 1);
                if (i < _lst.Count - 1)
                {
                    result += ", ";
                }
            }
            result += _main.SetText(" и получим");
            _main.ResultCollection.Add(new Result()
            {
                ItemResult = _main.RenderFormula(result)
            });
            _main.ResultCollection.Add(_main.RedLine);


            for (int i = 0; i < _main.CountParams; 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")).Multiply("x_" + (i + 1)).ToLaTeX() + " = " + @"\lambda*p_" + (i + 1) + "*x_" + (i + 1))
                });
            }
            _main.ResultCollection.Add(_main.RedLine);

            for (int i = 0; i < _main.CountParams; 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")).Multiply("x_" + (i + 1)).Divide(_main.ConvertCommaToDot((_alpha[i] * _A).ToString())).ToLaTeX() + " = " + @"\frac{\lambda*p_" + (i + 1) + "*x_" + (i + 1) + "}{" + _main.ConvertCommaToDot((_alpha[i] * _A).ToString()) + "}")
                });
            }
            _main.ResultCollection.Add(_main.RedLine);

            result = _main.SetText("", true);
            for (int i = 0; i < _main.CountParams; i++)
            {
                result += @"\frac{" + _main.ConvertCommaToDot(_main.PValuesParams[i].ToString()) + "*x_" + (i + 1) + "}{" + _main.ConvertCommaToDot(_alpha[i].ToString()) + "}";
                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("Из последнего равенства:", true))
            });


            for (int i = 0; i < _main.CountParams - 1; i++)
            {
                var root = Expr.Parse(_main.ConvertCommaToDot(((_main.PValuesParams[i + 1] * _alpha[i]) / (_main.PValuesParams[i] * _alpha[i + 1])).ToString()) + "*x_" + (i + 2));



                _main.ResultCollection.Add(new Result()
                {
                    ItemResult = _main.RenderFormula(_main.SetText("", true) + "x_" + (i + 1) + " = " + root.ToLaTeX())
                });
            }

            _main.ResultCollection.Add(new Result()
            {
                ItemResult = _main.RenderFormula(_main.SetText("", true) + _pi_xi + " = M" + _main.SetText("        (5)"))
            });

            result = "";

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

            var sumAlpha = _alpha.Sum();

            _main.ResultCollection.Add(new Result()
            {
                ItemResult = _main.RenderFormula(_main.SetText("Подставляя ", true) + result + _main.SetText(" в уравнение (5), получаем:"))
            });
            _lst.Clear();
            for (int i = _main.CountParams - 1; i >= 0; i--)
            {
                _x_star[i] = _alpha[i] / (sumAlpha * _main.PValuesParams[i]) * _main.MParam;
                _lst.Add(Expr.Parse(_main.ConvertCommaToDot(_alpha[i].ToString()) + "/(" + _main.ConvertCommaToDot(sumAlpha).ToString() + "*p_" + (i + 1) + ")*M"));
                _main.ResultCollection.Add(new Result()
                {
                    ItemResult = _main.RenderFormula(_main.SetText("", true) + "x_" + (i + 1) + "^* = " + _main.ConvertCommaToDot(_x_star[i].ToString()))
                });
            }
            _lst.Reverse();

            _main.ResultCollection.Add(new Result()
            {
                ItemResult = _main.RenderFormula(_main.SetText("Найдем ", true) + @"\lambda" + _main.SetText(" по формуле:"))
            });
            result = "A";
            var sumAlphaStr = "";

            for (int i = 0; i < _main.CountParams; i++)
            {
                result      += @"*\left (\frac {\alpha_" + (i + 1) + "}{p_" + (i + 1) + @"} \right) ^ {\alpha_" + (i + 1) + "}";
                sumAlphaStr += @"\alpha_" + (i + 1);
                if (i < _main.CountParams - 1)
                {
                    sumAlphaStr += "+";
                }
            }
            result += @"*\left (\frac {M}{" + sumAlphaStr + @"} \right) ^ {" + sumAlphaStr + "-1}";

            _main.ResultCollection.Add(new Result()
            {
                ItemResult = _main.RenderFormula(_main.SetText("", true) + @"\lambda^* = " + result)
            });



            result += "-M";
            var lam = _A;

            for (int i = 0; i < _main.CountParams; i++)
            {
                lam *= Math.Pow(_alpha[i] / _main.PValuesParams[i], _alpha[i]);
            }
            lam *= Math.Pow(_main.MParam / sumAlpha, sumAlpha - 1);

            var lam_star = Expr.Parse(_main.ConvertCommaToDot(lam.ToString()));

            _main.ResultCollection.Add(new Result()
            {
                ItemResult = _main.RenderFormula(_main.SetText("", true) + @"\lambda^* = " + lam_star.ToLaTeX())
            });

            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("M", _main.ConvertCommaToDot(_main.MParam)).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(ReplaceBrackets(_A_x_st_alpha), "x_" + (i + 1));
                var res1 = res;

                for (int j = 0; j < _main.CountParams; j++)
                {
                    res = res.Substitute(Expr.Parse("x_" + (j + 1)), _main.ConvertCommaToDot(_x_star[j].ToString()));
                }
                var val = double.Parse(_main.ConvertDotToComma(res.ToString()));
                dU_x_star[i] = val;
                _main.ResultCollection.Add(new Result()
                {
                    ItemResult = _main.RenderFormula(_main.SetText("", true) + @"\frac{\partial U}{\partial x_" + (i + 1) + " } = " + res1.ToLaTeX() + _main.SetText(";    ") +
                                                     @"\frac{\partial U}{\partial x_" + (i + 1) + " }(\\overline{ X})^* = " + res1.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))
            });
        }
예제 #15
0
        private static void AdamsMethod()
        {
            //промежуток и шаг
            const float  a = 0;
            const float  b = 1;
            const double h = 0.1;

            //Считывание функции и её компиляция средствами библиотеки MathNet.Symbolics
            Console.WriteLine("Equation should be like: y'=f(x,y)");
            Console.WriteLine("Enter f(x,y)");
            string equation = Console.ReadLine();
            Func <double, double, double> function = Expr.Parse(equation).Compile("x", "y");

            //Ввод начальных условий
            Console.WriteLine("Enter start conditions");
            double x0, y0;

            Console.Write("x0=");
            String temp = Console.ReadLine();

            x0 = float.Parse(temp);
            Console.Write("y0=");
            temp = Console.ReadLine();
            y0   = float.Parse(temp);

            //определение колличества шагов алгоритма
            int numberOfSteps = (int)((b - a) / h);

            //массив искомых значений
            double[] values = new double[numberOfSteps];

            //алгоритм Рунге–Кутты 4–го порядка
            for (int i = 0; i < 4; i++)
            {
                double prevX = (i * h) + x0;
                double prevY;
                if (i == 0)
                {
                    prevY = y0;
                }
                else
                {
                    prevY = values[i - 1];
                }

                double k1 = function(prevX, prevY);
                double k2 = function(prevX + h / 2, prevY + h * k1 / 2);
                double k3 = function(prevX + h / 2, prevY + h * k2 / 2);
                double k4 = function(prevX + h, prevY + h * k3);

                values[i] = prevY + (h / 6 * (k1 + 2 * k2 + 2 * k3 + k4));
            }

            for (int i = 4; i < numberOfSteps; i++)
            {
                values[i] = values[i - 1] + (h / 24.0) *
                            (55 * function(((i - 1) * h) + x0, values[i - 1]) -
                             59 * function(((i - 2) * h) + x0, values[i - 2]) +
                             37 * function(((i - 3) * h) + x0, values[i - 3])
                             - 9 * function(((i - 4) * h) + x0, values[i - 4]));
            }

            //Вывод ответа
            Console.WriteLine($"x={x0}  y={y0}");
            for (int i = 0; i < numberOfSteps; i++)
            {
                Console.WriteLine($"x={(i + 1) * h + x0}  y={values[i]}");
            }
        }
예제 #16
0
        static void Main(string[] args)
        {
            //объявление переменных
            var x  = Expr.Variable("x");
            var y1 = Expr.Variable("y1");
            var y2 = Expr.Variable("y2");

            #region Zadanie 1
            //Метод последовательных приближений для решения системы

            //Объявление системы
            Expr expr_dy1 = (x + y1 * y2);
            Expr expr_dy2 = (x * x - y1 * y1);
            Func <double, double, double, double> dy1 = (expr_dy1).Compile("x", "y1", "y2");
            Func <double, double, double, double> dy2 = (expr_dy2).Compile("x", "y1", "y2");

            //Первое приближение
            Expr expr_y1_1             = (1 + x * x / 2);
            Expr expr_y2_1             = (-x + x * x * x / 3);
            Func <double, double> y1_1 = expr_y1_1.Compile("x");
            Func <double, double> y2_1 = expr_y2_1.Compile("x");
            //Второе приближение
            Expr expr_y1_2             = (1 - (x.Pow(4)) / 24 + (x.Pow(6)) / 36);
            Expr expr_y2_2             = (-x - x.Pow(5) / 20);
            Func <double, double> y1_2 = expr_y1_2.Compile("x");
            Func <double, double> y2_2 = expr_y2_2.Compile("x");

            //диапозон значений x
            double[] section_x = new double[2] {
                0, 1
            };
            //Количество делений
            int divisions = 10;
            //Определение величны шага
            double h = (section_x[1] - section_x[0]) / divisions;

            double[] x_val = new double[divisions + 1];

            x_val[0] = section_x[0];
            for (int i = 1; i <= divisions; i++)
            {
                x_val[i] = x_val[i - 1] + h;
            }

            //массивы для хранения значений y1 и y2
            double[] y1_val = new double[divisions + 1];
            double[] y2_val = new double[divisions + 1];

            y1_val[0] = 1;
            y2_val[0] = 0;

            //Печать начальных условий
            Console.WriteLine($"y1' = {expr_dy1.ToString()}");
            Console.WriteLine($"y2' = {expr_dy2.ToString()}");
            Console.WriteLine("Начальные условия: ");
            Console.WriteLine("y1(0) = 1; y2(0) = 0;");

            //Печать приближений
            Console.WriteLine("Исходя из формулы y_n = y0 + integrate (f(x, y_(n-1)))dx from 0 to x , получаем:\n");
            Console.WriteLine($"y1_1 = 1 + integrate (x + 0)dx from 0 to x = {expr_y1_1.ToString()}");
            Console.WriteLine($"y2_1 = 1 + integrate (x^2 - 1)dx from 0 to x = {expr_y2_1.ToString()}\n");
            Console.WriteLine($"y1_2 = 1 + integrate (x + (1 + x^2/2)*(-x + x^3/3))dx from 0 to x = {expr_y1_2.ToString()}");
            Console.WriteLine($"y2_2 = 1 + integrate (x^2 + (1 + x^2 + x^4/4))dx from 0 to x = {expr_y2_2.ToString()}\n");

            //Результат
            Console.WriteLine($"x\ty1_1\ty2_1\ty1_2\ty2_2");

            for (int i = 0; i <= divisions; i++)
            {
                Console.Write($"{x_val[i]:0.00}\t");
                Console.Write($"{y1_1(x_val[i]):0.0000}\t");
                Console.Write($"{y2_1(x_val[i]):0.0000}\t");
                Console.Write($"{y1_2(x_val[i]):0.0000}\t");
                Console.WriteLine($"{y2_2(x_val[i]):0.0000}\t");
            }

            Console.WriteLine();

            #endregion



            Expr expr_f1 = -2 * y1 + 4 * y2;
            Func <double, double, double, double> f1 = (expr_f1).Compile("x", "y1", "y2");
            Expr expr_f2 = -y1 + 3 * y2;
            Func <double, double, double, double> f2 = (expr_f2).Compile("x", "y1", "y2");

            Console.WriteLine($"Уравнение:\ny1' = {expr_f1.ToString()}\ny2' = {expr_f2.ToString()}\n");
            Console.WriteLine("Начальные условия: ");
            Console.WriteLine("y1(0) = 3; y2(0) = 0;\n");

            #region Zadanie 2

            Miln(f1, f2, 10, 0, 1, 3, 0);

            #endregion

            #region Zadanie 3

            Adams(f1, f2, 10, 0, 1, 3, 0);

            #endregion
        }
예제 #17
0
        static void Main(string[] args)
        {
            var _x = Expr.Variable("x");
            var _t = Expr.Variable("t");

            #region Functions

            Func <double, double, double> sigma = (3.0 * (1.1 - 0.5 * _x)).Compile("t", "x");
            Func <double, double, double> funcs = (_t.Exp() - 1.0).Compile("t", "x");

            #endregion

            double leftBorderValue  = 0;
            double rightBorderValue = 0;

            double length = 1;
            double time;
            double precision = 1.0;
            double dx;
            double dt;
            double[,] u;
            double A;

            int nX = 10;
            int nT = 30;

            double max = 0;
            double s;

            dx = length / (nX);

            for (int x = 0; x < nX; x++)
            {
                s   = sigma(0, dx * x);
                max = (max > s) ? max : s;
            }

            dt   = dx * dx * precision / (2 * max);
            A    = dt / (dx * dx);
            time = 20.0 * dt;

            nT = (int)(time / dt + 1);

            u = new double[nT, nX];

            for (int x = 0; x < nX; x++)
            {
                u[0, x] = 0.01 * (1 - dx * x) * dx * dx;
            }

            u[0, 0]      = leftBorderValue;
            u[0, nX - 1] = rightBorderValue;

            double tempS, tempF, tempT, tempX;

            for (int t = 0; t < nT - 1; t++)
            {
                for (int x = 0; x < nX; x++)
                {
                    tempT = dt * t;
                    tempX = dx * x;
                    tempS = sigma(tempT, tempX);
                    tempF = funcs(tempT, tempX);

                    if (x == 0)
                    {
                        u[t + 1, x] = leftBorderValue;
                    }
                    else if (x == nX - 1)
                    {
                        u[t + 1, x] = rightBorderValue;
                    }
                    else
                    {
                        u[t + 1, x] = A * tempS * (u[t, x - 1] + u[t, x + 1]) + (1.0 - 2.0 * A * tempS)
                                      * u[t, x] + dt * tempF;
                    }
                }
            }

            Console.WriteLine($"nX = {nX}");
            Console.WriteLine($"nT = {nT}");
            Console.WriteLine($"dt = {dt}");
            Console.WriteLine($"time = {time}");
            Console.WriteLine($"A = {A}");

            int xx = (int)(0.6 * (nX - 1) / length);

            Console.WriteLine("t\tU = U(0.6, t)");
            for (int t = 0; t < nT; t++)
            {
                Console.WriteLine($"{(dt * t):0.000000}\t{u[t, xx]:0.000000}");
            }
            Console.WriteLine();

            double tt = time / 10;
            xx = (int)(tt * (nT - 1) * 1 / time);

            Console.WriteLine($"t\tU = U(x, {tt * 2})");
            for (int x = 0; x < nX; x++)
            {
                Console.WriteLine($"{(dx * x):0.000000}\t{u[xx, x]:0.000000}");
            }
            Console.WriteLine();

            Console.WriteLine($"t\tU = (x, {tt * 4})");
            for (int x = 0; x < nX; x++)
            {
                Console.WriteLine($"{(dx * x):0.000000}\t{u[xx, x]:0.000000}");
            }
        }
예제 #18
0
 public void VariableTests()
 {
     this.AssertParse(new IdNode(1, "x"), Expr.Variable("x"));
     this.AssertParse(new IdNode(1, "xyz"), Expr.Variable("xyz"));
 }
예제 #19
0
        static void Main()
        {
            //промежуток и шаг
            const float  a = 0;
            const float  b = 1;
            const double h = 0.1;

            Console.WriteLine("Введите колличесво уравнений в системе");
            int n = int.Parse(Console.ReadLine());
            List <Func <double, double, double, double> > functions = new List <Func <double, double, double, double> >();

            for (int i = 0; i < n; i++)
            {
                //Считывание функции и её компиляция средствами библиотеки MathNet.Symbolics
                Console.WriteLine("Диффиренциальное уравнение должно иметь вид: y'=f(x,y,z)");
                Console.WriteLine("Введите f(x,y,z)");
                string equation = Console.ReadLine();
                Func <double, double, double, double> function = Expr.Parse(equation).Compile("x", "y", "z");
                functions.Add(function);
            }

            //Ввод начальных условий
            Console.WriteLine("Введите начальные условия");
            double x0, y0, z0;

            Console.Write("x0=");
            String temp = Console.ReadLine();

            x0 = float.Parse(temp);
            Console.Write("y0=");
            temp = Console.ReadLine();
            y0   = float.Parse(temp);
            Console.Write("z0=");
            temp = Console.ReadLine();
            z0   = float.Parse(temp);

            //определение колличества шагов алгоритма
            int numberOfSteps = (int)((b - a) / h);

            //массив искомых значений
            double[] valuesY = new double[numberOfSteps];
            double[] valuesZ = new double[numberOfSteps];

            //алгоритм Рунге–Кутты 4–го порядка
            for (int i = 0; i < numberOfSteps; i++)
            {
                double prevX = (i * h) + x0;
                double prevY;
                double prevZ;
                if (i == 0)
                {
                    prevY = y0;
                    prevZ = z0;
                }
                else
                {
                    prevY = valuesY[i - 1];
                    prevZ = valuesZ[i - 1];
                }

                double k1 = functions[0](prevX, prevY, prevZ);
                double k2 = functions[0](prevX + h / 2, prevY + h * k1 / 2, prevZ + h * k1 / 2);
                double k3 = functions[0](prevX + h / 2, prevY + h * k2 / 2, prevZ + h * k2 / 2);
                double k4 = functions[0](prevX + h, prevY + h * k3, prevZ + h * k3);
                valuesY[i] = prevY + (h / 6 * (k1 + 2 * k2 + 2 * k3 + k4));
                k1         = functions[1](prevX, prevY, prevZ);
                k2         = functions[1](prevX + h / 2, prevY + h * k1 / 2, prevZ + h * k1 / 2);
                k3         = functions[1](prevX + h / 2, prevY + h * k2 / 2, prevZ + h * k2 / 2);
                k4         = functions[1](prevX + h, prevY + h * k3, prevZ + h * k3);
                valuesZ[i] = prevZ + (h / 6 * (k1 + 2 * k2 + 2 * k3 + k4));
            }

            //Вывод ответа
            Console.WriteLine($"x={x0}  y={y0}");
            for (int i = 0; i < numberOfSteps; i++)
            {
                Console.WriteLine($"x={(i+1)*h+x0}  y={valuesY[i]} z={valuesZ[i]}");
            }

            Console.ReadLine();
        }
 public static void GetAllFactors(MathNet.Symbolics.SymbolicExpression sym, List <string> list)
 {
     if (sym.Factors().Count() == 1)
     {
         try { var tmp = sym.RealNumberValue; }
         catch
         {
             if (sym.Expression.IsPower)
             {
                 var hh = sym.Expression as MathNet.Symbolics.Expression.Power;
                 if (hh.Item1.IsIdentifier)
                 {
                     if (!list.Contains((hh.Item1 as MathNet.Symbolics.Expression.Identifier).Item.Item.ToString()))
                     {
                         list.Add((hh.Item1 as MathNet.Symbolics.Expression.Identifier).Item.Item.ToString());
                     }
                 }
                 else
                 {
                     var sym1 = new MathNet.Symbolics.SymbolicExpression(hh.Item1);
                     GetAllFactors(sym1, list);
                 }
                 if (hh.Item2.IsIdentifier)
                 {
                     if (!list.Contains((hh.Item2 as MathNet.Symbolics.Expression.Identifier).Item.Item.ToString()))
                     {
                         list.Add((hh.Item2 as MathNet.Symbolics.Expression.Identifier).Item.Item.ToString());
                     }
                 }
                 else
                 {
                     var sym1 = new MathNet.Symbolics.SymbolicExpression(hh.Item2);
                     GetAllFactors(sym1, list);
                 }
             }
             else if (sym.Expression.IsFunction)
             {
                 var hh = sym.Expression as MathNet.Symbolics.Expression.Function;
                 if (hh.Item2.IsIdentifier)
                 {
                     if (!list.Contains((hh.Item2 as MathNet.Symbolics.Expression.Identifier).Item.Item.ToString()))
                     {
                         list.Add((hh.Item2 as MathNet.Symbolics.Expression.Identifier).Item.Item.ToString());
                     }
                 }
                 else
                 {
                     var sym1 = new MathNet.Symbolics.SymbolicExpression(hh.Item2);
                     GetAllFactors(sym1, list);
                 }
             }
             else if (!list.Contains(sym.ToString()))
             {
                 list.Add(sym.ToString());
             }
         }
     }
     else
     {
         foreach (var item in sym.Factors())
         {
             GetAllFactors(item, list);
         }
     }
 }
예제 #21
0
        static void Main(string[] args)
        {
Start:
            ParseFunction();
Choices:
            Console.WriteLine("====================PASIRINKIMAI====================");
            Console.WriteLine("1. Apskaičiuoti liekamąjį narį");
            Console.WriteLine("2. Pasirinkti kitą funkciją");
            Console.WriteLine("3. Gauti pasirinktos funkcijos n-tos eilės išvestinę");
            Console.WriteLine("4. Gauti pasirinktos funkcijos n-tos Teiloro(Makloreno) formulę");
            Console.WriteLine("5. Baigti programą");
            Console.WriteLine("====================================================");
            Console.WriteLine();

            Console.Write("Jūsų pasirinkimas: ");
            var choice = Console.ReadLine();

            Console.WriteLine();

            if (choice == "1")
            {
                Console.Write("Įveskite išvestinės eilę: ");
                var order = int.Parse(Console.ReadLine());
                Console.WriteLine();

                Console.Write("X reiksme: ");
                var value = double.Parse(Console.ReadLine());
                Console.WriteLine();

                Console.WriteLine($"{order} eilės Teiloro(Makloreno) formulė: " + LagrangeRemainderCalculator.GetTaylorExpression(order + 1, Expr.Variable("x"), 0, _parsedFunction).ToString() + $" + r{order}(x)");
                Console.WriteLine();

                Console.WriteLine("Funkcijos liekamasis narys (Lagranzo forma): " + LagrangeRemainderCalculator.CalculateLagrangeRemainder(_parsedFunction, "x", order, 0, value));
                Console.WriteLine("Tikslus funkcijos liekamasis narys: " + LagrangeRemainderCalculator.CalculateExactRemainder(_parsedFunction, value, order));
                Console.WriteLine();
                goto Choices;
            }
            else if (choice == "2")
            {
                goto Start;
            }
            else if (choice == "3")
            {
                Console.Write("Įveskite norimos išvestinės eilę: ");
                var order = int.Parse(Console.ReadLine());
                Console.WriteLine();

                Console.WriteLine($"Funkcijos {order} eilės išvestinė: " + LagrangeRemainderCalculator.GetDerivativeOfDegree(_parsedFunction, Expr.Variable("x"), order).ToString());
                Console.WriteLine();
                goto Choices;
            }
            else if (choice == "4")
            {
                Console.Write("Įveskite norimą Teiloro(Makloreno) formulės eilę: ");
                var order = int.Parse(Console.ReadLine());
                Console.WriteLine();

                Console.WriteLine($"{order} eilės Teiloro(Makloreno) formulė: " + LagrangeRemainderCalculator.GetTaylorExpression(order + 1, Expr.Variable("x"), 0, _parsedFunction).ToString() + $" + r{order}(x)");
                Console.WriteLine();
                goto Choices;
            }
            else if (choice != "1" && choice != "2" && choice != "3" && choice != "4" && choice != "5")
            {
                Console.WriteLine("Pasirinkimas neatpažintas...");
                Console.WriteLine();
                goto Choices;
            }

            Console.WriteLine("Programa baigta...");
        }
예제 #22
0
        private void Button1_Click(object sender, EventArgs e)
        {
            trackBarCurrentLayer.Maximum = int.Parse(textBox_t_count.Text) - 1;

            double a = Math.Sqrt(double.Parse(textBoxA2.Text));
            double L = double.Parse(textBoxL.Text);
            double T = double.Parse(textBoxT.Text);

            double h = double.Parse(textBox_h.Text);
            double t = double.Parse(textBox_t.Text);

            string cos1 = "cos(pi*x/" + Convert.ToString(L) + ")";
            string cos2 = "cos(2*pi*x/" + Convert.ToString(L) + ")";
            string sin1 = "sin(pi*x/" + Convert.ToString(L) + ")";
            string sin2 = "sin(2*pi*x/" + Convert.ToString(L) + ")";

            // phi
            string phi_coeff_1 = textBox_phi_coeff_1.Text;
            string phi_coeff_2 = textBox_phi_coeff_2.Text;
            string phi_coeff_3 = textBox_phi_coeff_3.Text;

            string formula_phi = phi_coeff_1 + "+" +
                                 phi_coeff_2 + "*" + cos1 + "+" +
                                 phi_coeff_3 + "*" + cos2;

            MathNet.Symbolics.SymbolicExpression expr_phi = MathNet.Symbolics.SymbolicExpression.Parse(formula_phi);


            // psi
            string psi_coeff_1 = textBox_psi_coeff_1.Text;
            string psi_coeff_2 = textBox_psi_coeff_2.Text;
            string psi_coeff_3 = textBox_psi_coeff_3.Text;

            string formula_psi = psi_coeff_1 + "+" +
                                 psi_coeff_2 + "*" + cos1 + "+" +
                                 psi_coeff_3 + "*" + cos2;

            MathNet.Symbolics.SymbolicExpression expr_psi = MathNet.Symbolics.SymbolicExpression.Parse(formula_psi);


            // b
            string b_coeff_1 = textBox_b_coeff_1.Text;
            string b_coeff_2 = textBox_b_coeff_2.Text;
            string b_coeff_3 = textBox_b_coeff_3.Text;
            string b_coeff_4 = textBox_b_coeff_4.Text;
            string b_coeff_5 = textBox_b_coeff_5.Text;

            string formula_b = b_coeff_1 + "+" +
                               b_coeff_2 + "*" + cos1 + "+" +
                               b_coeff_3 + "*" + sin1 + "+" +
                               b_coeff_4 + "*" + cos2 + "+" +
                               b_coeff_5 + "*" + sin2;

            MathNet.Symbolics.SymbolicExpression expr_b = MathNet.Symbolics.SymbolicExpression.Parse(formula_b);


            Func <double, double> phi = expr_phi.Compile("x");
            Func <double, double> psi = expr_psi.Compile("x");
            Func <double, double> b   = expr_b.Compile("x");

            chart.Series.Clear();
            chart.Series.Add("Начальное условие \u03D5(x)");
            chart.Series["Начальное условие \u03D5(x)"].ChartType   = SeriesChartType.Spline;
            chart.Series["Начальное условие \u03D5(x)"].Color       = Color.Blue;
            chart.Series["Начальное условие \u03D5(x)"].BorderWidth = 2;

            for (double i = 0; i <= L; i += h)
            {
                chart.Series["Начальное условие \u03D5(x)"].Points.AddXY(i, phi(i));
            }

            grid2D = new Grid2D(phi, psi, b, a, L, T, h, t);
            if (radioButtonHomogeneous.Checked == true)
            {
                grid2D.SolveHomogeneous();
            }
            else if (radioButtonNongomogeneous.Checked == true)
            {
                grid2D.SolveNonhomogeneous();
            }


            trackBarCurrentLayer.Value = int.Parse(textBox_t_count.Text) - 1;
            groupBoxCurrentLayer.Text  = String.Format("Текущий слой: {0} (последний u(x, T))", trackBarCurrentLayer.Value);
            string number_layer = "Слой " + trackBarCurrentLayer.Value;

            if (trackBarCurrentLayer.Value == int.Parse(textBox_t_count.Text) - 1)
            {
                number_layer += " (последний u(x, T))";
            }
            chart.Series.Add(number_layer);
            chart.Series[number_layer].ChartType   = SeriesChartType.Spline;
            chart.Series[number_layer].Color       = Color.Black;
            chart.Series[number_layer].BorderWidth = 2;


            double[] layer = grid2D.GetLastLayer();
            for (int i = 0; i < layer.Length; i++)
            {
                chart.Series[number_layer].Points.AddXY(i * h, layer[i]);
            }
        }