public TaylorSeriesCompute(int iterations, Expr symbol, Expr value, Expr function, Expr functionInput) { //initiliaze DerivativeList = new List <TaylorSeriesIteration>(); //create the series var series = Taylor(iterations, symbol, value, function); //eval var symbols = new Dictionary <string, FloatingPoint>(); symbols.Add("x", 1); try { var eval = Evaluate.Evaluate(symbols, functionInput); //assign values this.Aprox = eval; } catch { throw new ArgumentException("Invalid function input"); } //assign to results this.SeriesExpression = series; this.InputFunction = function; //var X = Expr.Symbol("x"); //var sample = Taylor(6, X, 0, Expr.Cos(X)); //string res = Infix.Format(sample); //Console.WriteLine("taylor series: {0}", res); }
public static void Main(string[] args) { //MoreLinq Console.WriteLine(MoreEnumerable.Random().First()); //Newtonsoft Console.WriteLine(JObject.Parse(@"{""foo"":42}")); //Mathnet var x = Expr.Symbol("x"); Console.WriteLine(Infix.Format(x + x)); //DynamicExpresso Console.WriteLine(new Interpreter().Eval("2+2")); //NDesk.Options Console.WriteLine(new OptionSet { { "v", v => {} } }.Parse(new[] { "-v", "foo" })[0]); //System.Memory Console.WriteLine(new Span <int>(new[] { 42 })[0]); //System.Collections.Immutable Console.WriteLine(new[] { 12 }.ToImmutableArray()[0]); //Microsoft.Z3 try { Console.WriteLine($"Z3: {Microsoft.Z3.Version.ToString()}"); } catch (DllNotFoundException) { Console.WriteLine($"Warning, native Z3 library not detected"); } }
/// <summary> /// Initialize objects for symbolics calculations /// </summary> private void Initialize() { symbol = MathNet.Symbolics.Expression.Symbol("t"); symbols = new Dictionary <string, FloatingPoint> { { "t", 0 } }; }
//create the function Expr Taylor(int iterations, Expr symbol, Expr value, Expr function) { this.DerivativeList.Clear(); //counter for factorial int factorial = 1; //accumulates the results for each iteration (formula) Expr accumulator = Expr.Zero; //variable for holding the derivative of function for each iteration Expr derivative = function; for (int i = 0; i < iterations; i++) { //use for storing output TaylorSeriesIteration OutputItem = new TaylorSeriesIteration(); //store the current iteration OutputItem.Iteration = (i + 1).ToString(); //subs/replaces symbol with value from funct. Ex. symbol: x, func: x + 1, value: 1 result: 1 + 1 var subs = Structure.Substitute(symbol, value, derivative); //get the derivative of derivative with respect to symbol derivative = Calculus.Differentiate(symbol, derivative); //output current derivative OutputItem.Function = derivative; //evaluate derivative, f(0) var evalValue = new Dictionary <string, FloatingPoint> { { Infix.Format(symbol), 1 } }; var eval = Evaluate.Evaluate(evalValue, Structure.Substitute(symbol, 0, derivative)); OutputItem.Evaluation = eval.ToString(); //create the formula and append to accumulator accumulator = accumulator + subs / factorial * Expr.Pow(symbol - value, i); //output current formula OutputItem.Series = accumulator; //current iteration + 1 as factorial (cause 0-based loop) factorial *= (i + 1); //append to list this.DerivativeList.Add(OutputItem); } //return the formula/func in expanded form return(Algebraic.Expand(accumulator)); }
public int GetProb(string raw, MathNet.Symbolics.Expression e) { sequence = MATH2.Utils.Sequences.ParseSequence(raw); if (S.CalculateEqualizationDifNo(sequence) == 1) { return(100); } else { return(-100); } return(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 ) ); } }
public Expr FindRoot(ExprLast variable, ExprLast expr) { ExprLast simple = Algebraic.Expand(Rational.Numerator(Rational.Simplify(variable, expr))); ExprLast[] coeff = Polynomial.Coefficients(variable, simple); switch (coeff.Length) { case 1: return(ExprLast.Zero.Equals(coeff[0]) ? variable : ExprLast.Undefined); case 2: return(Rational.Simplify(variable, Algebraic.Expand(-coeff[0] / coeff[1]))); default: return(ExprLast.Undefined); } }
Expr SolveSimpleRoot(Expr variable, Expr expr) { // try to bring expression into polynomial form Expr simple = Algebraic.Expand(Rational.Numerator(Rational.Simplify(variable, expr))); // extract coefficients, solve known forms of order up to 1 Expr[] coeff = Polynomial.Coefficients(variable, simple); switch (coeff.Length) { case 1: return(Expr.Zero.Equals(coeff[0]) ? variable : Expr.Undefined); case 2: return(Rational.Simplify(variable, Algebraic.Expand(-coeff[0] / coeff[1]))); default: return(Expr.Undefined); } }
public static Func <int, int, double> ParseInput(string input) { var e = Expr.Symbol("edges"); var v = Expr.Symbol("vertices"); return((vertices, edges) => { var symbols = new Dictionary <string, FloatingPoint> { { "vertices", vertices }, { "edges", edges } }; return Evaluate.Evaluate(symbols, Infix.ParseOrUndefined(input)).RealValue; }); }
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 ) ); } }
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 }
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)) }); }
/// <summary> /// Create trajectory from given parametrization /// </summary> private void CreateTrajectory() { // Try to parse parametrizations' strings try { xExpression = Infix.ParseOrThrow(XParametrizationTextBox.Text); yExpression = Infix.ParseOrThrow(YParametrizationTextBox.Text); } catch (Exception exception) { TrajectoryLoaded = false; MessageBox.Show("Wrong format of parametrization.\n" + exception.Message); return; } // Try to parse parameters try { minParameterValue = double.Parse(MinParameterValueTextBox.Text); maxParameterValue = double.Parse(MaxParameterValueTextBox.Text); pointsCount = double.Parse(PointsCountTextBox.Text); if (minParameterValue >= maxParameterValue || pointsCount < 2) { throw new Exception(); } } catch (Exception) { TrajectoryLoaded = false; MessageBox.Show("Parameters are invalid."); return; } TrajectoryPoints = new List <Point3D>(); var flag = true; // Try to calculate curve's trajectory try { var parameterStep = (maxParameterValue - minParameterValue) / (pointsCount - 1); for (double t = minParameterValue; t < maxParameterValue + parameterStep / 2; t += parameterStep) { symbols["t"] = t; double xResult = Evaluate.Evaluate(symbols, xExpression).RealValue; double yResult = Evaluate.Evaluate(symbols, yExpression).RealValue; TrajectoryPoints.Add(new Point3D(xResult, yResult, 0.0)); if (flag) { flag = false; } } } catch (Exception exception) { TrajectoryLoaded = false; TrajectoryPoints.Clear(); if (exception.HResult == HResultWrongParam) { MessageBox.Show("Given parametrization is not based on [t] variable.\n"); } else if (exception.HResult == HResultCannotCalculate) { MessageBox.Show("Cannot calculate curve for given set.\n"); } else { MessageBox.Show("Cannot calculate curve for given set.\n" + exception.Message); } return; } TrajectoryLoaded = true; }
public BisectionResultRow(Symbol symbol, Expr functionExpression) { this.FunctionExpression = functionExpression; this.Symbol = symbol; }
public Coordinates GetXYbyCircunsferencesIntersection(Circumference circumference1, Circumference circumference2, Circumference circumference3) { var response = new Coordinates() { X = 0, Y = 0 }; var circumferenceVariables = new List <Variables>() { new Variables() { Name = "CircumferenceEquation" , V_2_X_CoordX = ((-1) * circumference1.Coordinates.X) * 2 , L_CoordX_CoordX = circumference1.Coordinates.X * circumference1.Coordinates.X , V_2_Y_CoordY = ((-1) * circumference1.Coordinates.Y) * 2 , L_CoordY_CoordY = circumference1.Coordinates.Y * circumference1.Coordinates.Y , Radio = circumference1.Radio * circumference1.Radio , ReductionFactor = 1 }, new Variables() { Name = "CircumferenceEquation" , V_2_X_CoordX = ((-1) * circumference2.Coordinates.X) * 2 , L_CoordX_CoordX = (circumference2.Coordinates.X * circumference2.Coordinates.X) , V_2_Y_CoordY = ((-1) * circumference2.Coordinates.Y) * 2 , L_CoordY_CoordY = (circumference2.Coordinates.Y * circumference2.Coordinates.Y) , Radio = (circumference2.Radio * circumference2.Radio) , ReductionFactor = -1 } }; //Get First Equation to substitution on the last step var equationForFinalSubstitution = string.Format("x^2+y^2{0}*x{1}{2}*y{3}{4}", (circumferenceVariables[0].V_2_X_CoordX > 0 ? "+" : "") + circumferenceVariables[0].V_2_X_CoordX , (circumferenceVariables[0].L_CoordX_CoordX > 0 ? "+" : "") + circumferenceVariables[0].L_CoordX_CoordX , (circumferenceVariables[0].V_2_Y_CoordY > 0 ? "+" : "") + circumferenceVariables[0].V_2_Y_CoordY , (circumferenceVariables[0].L_CoordY_CoordY > 0 ? "+" : "") + circumferenceVariables[0].L_CoordY_CoordY , ((-1) * circumferenceVariables[0].Radio) > 0 ? "+" : "") + ((-1) * circumferenceVariables[0].Radio); //Apply factor for reduction circumferenceVariables[1].V_2_X_CoordX *= circumferenceVariables[1].ReductionFactor; circumferenceVariables[1].L_CoordX_CoordX *= circumferenceVariables[1].ReductionFactor; circumferenceVariables[1].V_2_Y_CoordY *= circumferenceVariables[1].ReductionFactor; circumferenceVariables[1].L_CoordY_CoordY *= circumferenceVariables[1].ReductionFactor; circumferenceVariables[1].Radio *= circumferenceVariables[1].ReductionFactor; //Apply Reduction var reducedEquationSum = from item in circumferenceVariables group item by item.Name into reducedEquationGroup select new { Name = reducedEquationGroup.Key, V_2_X_CoordX = reducedEquationGroup.Sum(x => x.V_2_X_CoordX), L_CoordX_CoordX = reducedEquationGroup.Sum(x => x.L_CoordX_CoordX), V_2_Y_CoordY = reducedEquationGroup.Sum(x => x.V_2_Y_CoordY), L_CoordY_CoordY = reducedEquationGroup.Sum(x => x.L_CoordY_CoordY), Radio = reducedEquationGroup.Sum(x => x.Radio) }; var reducedEquation = reducedEquationSum.ToList(); var GCDInValues = new int[3] { Math.Abs((int)reducedEquation[0].V_2_X_CoordX), Math.Abs((int)reducedEquation[0].V_2_Y_CoordY), Math.Abs((int)reducedEquation[0].L_CoordX_CoordX + (int)reducedEquation[0].L_CoordY_CoordY) }; string generalExpression = string.Format("{0}*x{1}{2}*y{3}{4}", reducedEquation[0].V_2_X_CoordX , (reducedEquation[0].L_CoordX_CoordX > 0 ? "+": "") + reducedEquation[0].L_CoordX_CoordX , (reducedEquation[0].V_2_Y_CoordY > 0 ? "+" : "") + reducedEquation[0].V_2_Y_CoordY , (reducedEquation[0].L_CoordY_CoordY > 0 ? "+" : "") + reducedEquation[0].L_CoordY_CoordY , (((-1) * reducedEquation[0].Radio) > 0 ? "+" : "") + (-1) * reducedEquation[0].Radio); var x = Expr.Symbol("x"); var y = Expr.Symbol("y"); Expr aleft = Infix.ParseOrThrow(generalExpression); Expr aright = Infix.ParseOrThrow("0"); //Resolve "x" from general expression Expr xFromGeneralExpression = SolveSimpleRoot(x, aleft - aright); //TODO Substitution and final result return(response); }
public Expr ConvertExprLastToExpr(ExprLast eq) { return(eq); }