public static Expression ChooseWithDiff(Expression h, int k, int times, int sign) { if (k < 1) { return(0); } var u = Expression.Symbol("u"); var d = (u.Factorial(k - 1, sign)); for (var i = 0; i < times; i++) { d = Calculus.Differentiate(u, d); } var result = d / k.Factorial(); var floatingPoint = Evaluate.Evaluate( new Dictionary <string, FloatingPoint> { { "u", FloatingPoint.NewReal(h.ToReal()) } }, result); var frac = (Expression)floatingPoint.RealValue.ToFraction(); // k.Factorial(); return(frac); }
public static float[] Calculate(int[] hand, int handLength, int sdRound) { VerifyParameters(handLength, sdRound); float[] hssd = new float[2]; hssd[0] = HandStrength.CalculateFast(hand, handLength); if (handLength == 7) { // Nothing more to do on the river. return(hssd); } int sdHandLength = HeHelper.RoundToHandSize[sdRound]; CardSet cs = StdDeck.Descriptor.GetCardSet(hand, 0, handLength); Params p = new Params { Hand = new int[sdHandLength] }; for (int i = 0; i < handLength; ++i) { p.Hand[i] = hand[i]; } p.Hs = hssd[0]; CardEnum.Combin <Params>(StdDeck.Descriptor, sdHandLength - handLength, p.Hand, handLength, p.Hand, handLength, OnDeal, p); Debug.Assert(FloatingPoint.AreEqual(p.Hs, p.SumHs / p.Count, 0.00001)); hssd[1] = (float)Math.Sqrt(p.SumDiff / p.Count); return(hssd); }
private List <Point> GetPointsBetween(Point p1, Point p2) { double step_size = 0.01; //todo adjust List <Point> points = new List <Point>(); FloatingPoint pointer = new FloatingPoint(p1); int CompareX(Point start, Point end) { return(end.X.CompareTo(start.X)); } int CompareY(Point start, Point end) { return(end.Y.CompareTo(start.Y)); } int x_comp = CompareX(p1, p2); int y_comp = CompareY(p1, p2); FloatingPoint delta = new FloatingPoint(p1, p2).Multiply(step_size); while (x_comp != CompareX(p2, pointer.Floored()) || y_comp != CompareY(p2, pointer.Floored())) { pointer = pointer.Add(delta); Point current = pointer.Floored(); if (!points.Contains(current)) { points.Add(current); } } return(points); }
static void Verify(int oppCount, double[] cardProbabs, double[,] pm) { if (oppCount <= 0) { throw new ApplicationException("Player count must be > 0"); } int n = cardProbabs.GetLength(0); if (n != pm.GetLength(0) || n != pm.GetLength(1)) { throw new ApplicationException("Array size mismatch"); } double sum = 0; for (int i = 0; i < n; ++i) { sum += cardProbabs[i]; } if (!FloatingPoint.AreEqual(1, sum, 1e-5)) { throw new ApplicationException(String.Format("Wrong sum of card probabilities: {0}, expected 1.", sum)); } for (int i = 0; i < n; ++i) { for (int j = 0; j <= i; ++j) { if (pm[i, j] < 0 || pm[i, j] > 1 || pm[j, i] < 0 || pm[j, i] > 1 || !FloatingPoint.AreEqual(pm[i, j] + pm[j, i], 1, 1e-5)) { throw new ApplicationException(String.Format("Prefernce matrix wrong at ({0}, {1}).", i, j)); } } } }
public virtual void OnGameBegin(string gameString) { _gameRecord = new GameRecord(gameString); _pos = _gameRecord.FindPositionByName(_name); if (_checkBlinds) { for (int p = 0; p < _gameRecord.Players.Count; ++p) { _curStrNodeIdx = p + 1; StrategyTreeNode stNode = new StrategyTreeNode(); _strategies[_pos].GetNode(p + 1, &stNode); double strBlind = stNode.Amount; double grBlind = _gameRecord.Players[p].Blind; if (!FloatingPoint.AreEqual(grBlind, strBlind, AMOUNT_EPSILON)) { throw new ApplicationException( String.Format("{0}: blind size mismatch: game: {1}, strategy: {2}", GetBotStateDiagText(), grBlind, strBlind)); } } } if (_gameRecord.Actions.Count != 0) { throw new ApplicationException( String.Format("{0}: action count must be zero in OnGameBegin, game string '{1}'", GetBotStateDiagText(), gameString)); } _curStrNodeIdx = _gameRecord.Players.Count; _processedActionsCount = 0; _lastAbsStrProbab = 1.0; _gameState = new GameState(_gameRecord, null); log.InfoFormat("{0} OnGameBegin() pos {1}", _name, _pos); }
public static bool Verify(ActionTree at, ChanceTree ct, StrategyTree[] strategies, double epsilon, out string message) { message = ""; // No need to check preconditions, GameValue does it GameValue gv = new GameValue { ActionTree = at, ChanceTree = ct, Strategies = strategies }; gv.Solve(); for (int p = 0; p < at.PlayersCount; ++p) { StrategyTree[] strategiesCopy = (StrategyTree[])strategies.Clone(); Br br = new Br { ActionTree = at, ChanceTree = ct, Strategies = strategiesCopy, HeroPosition = p }; br.Solve(); if (!FloatingPoint.AreEqual(gv.Values[p], br.Value, epsilon)) { message = String.Format("Unequal values for pos {0}: eq: {1}, br: {2}, eps: {3}", p, gv.Values[p], br.Value, epsilon); return(false); } } return(true); }
public static void Main() { Number <Byte> byt = new Number <Byte>(12); Console.WriteLine(byt.Add(12)); Number <SByte> sbyt = new Number <SByte>(-3); Console.WriteLine(sbyt.Subtract(12)); Number <ushort> ush = new Number <ushort>(16); Console.WriteLine(ush.Add((ushort)3)); Number <double> dbl = new Number <double>(Math.PI); Console.WriteLine(dbl.Add(1.0)); FloatingPoint <Single> sng = new FloatingPoint <float>(12.3f); Console.WriteLine(sng.Add(3.0f)); // FloatingPoint<int> f2 = new FloatingPoint<int>(16); // Console.WriteLine(f2.Add(6)); }
public void CheckWeights(double[] weights, Random underlyingRng) { int[] counts = new int[weights.Length]; DiscreteProbabilityRng rng = new DiscreteProbabilityRng(underlyingRng); rng.SetWeights(weights); for (int i = 0; i < 200000; ++i) { int r = rng.Next(); counts[r]++; } double[] resultWeights = new double[weights.Length]; int sum = 0; double sumWeights = 0; for (int i = 0; i < counts.Length; ++i) { Console.Write("{0} ", counts[i]); sum += counts[i]; sumWeights += weights[i]; } Console.WriteLine(); for (int i = 0; i < counts.Length; ++i) { resultWeights[i] = (double)counts[i] / sum * sumWeights; Console.Write("{0:0.000} ", resultWeights[i]); Assert.IsTrue(FloatingPoint.AreEqualRel(weights[i], resultWeights[i], 0.05)); if (weights[i] == 0) { Assert.AreEqual(0, counts[i], "0-weigths must not occur"); } } Console.WriteLine(); }
public static void Main() { // tests for digits with spaces string digitsSeparatedTrue = "1 4 2 1 6"; string digitsSeparatedFalse = "1 22 "; Lexer digitsTrue = new DigitsWithSpaces(digitsSeparatedTrue); Lexer digitsFalse = new DigitsWithSpaces(digitsSeparatedFalse); // tests for alternate groups string alternateTrue = "aa42aa5bb1"; string alternateFalse = "b22aaa"; string alternateFalse2 = "4ds2212d4"; Lexer altTrue = new AlternateGroups(alternateTrue); Lexer altFalse = new AlternateGroups(alternateFalse); Lexer altFalse2 = new AlternateGroups(alternateFalse2); // tests for floating points string floatingTrue = "321321.3123123"; string floatingFalse = ".412"; Lexer floatTrue = new FloatingPoint(floatingTrue); Lexer FloatFalse = new FloatingPoint(floatingFalse); // tests for single string; string stringTrue = "'dasdasd'"; string stringFalse = "'dasda'dasd'"; Lexer strTrue = new SingleString(stringTrue); Lexer strFalse = new SingleString(stringFalse); // tests for multiline comment string commentTrue = "/* sadsadsa */"; string commentFalse = "/*gfdgf*/agfdgdfgs*/"; string commentFalse2 = "/*dsadas"; Lexer commTrue = new MultilineComment(commentTrue); Lexer commFalse = new MultilineComment(commentFalse); Lexer commFalse2 = new MultilineComment(commentFalse2); try { // расскоментировать строчку для проверки // то, что помечено True - должно работать // то, что помечено False - должно выдавать ошибку //digitsTrue.Parse(); //digitsFalse.Parse(); //altTrue.Parse(); //altFalse.Parse(); //altFalse2.Parse(); //floatTrue.Parse(); //FloatFalse.Parse(); //strTrue.Parse(); //strFalse.Parse(); //commTrue.Parse(); commFalse.Parse(); //commFalse2.Parse(); } catch (LexerException e) { System.Console.WriteLine(e.Message); } }
public static float ValueToFloat(Value val) { return(val switch { FloatingPoint point => (float)point.Value, Integer integer => integer.Value, _ => throw new System.ArgumentException("List element was not a number"), });
public static double CalculateExactRemainder(Expr func, FloatingPoint point, int order) { var pointVar = new Dictionary <string, FloatingPoint> { { "x", point } }; var taylorExpr1 = GetTaylorExpression(order + 1, Expr.Variable("x"), 0, func); var trueValue = func.Evaluate(pointVar); var taylorValue = taylorExpr1.Evaluate(pointVar); return(trueValue.RealValue - taylorValue.RealValue); }
protected bool Step3_OnNodeBegin(TreeNode tree, TreeNode node, List <Context> stack, int depth) { Context context = stack[depth]; SyncPlayerTreeWithGameTree(stack, depth, _step3CurPos); TreeNode playerNode = context.PlayerTreeNode; // Correct and validate strategy of the opponent. if (depth == 0) { playerNode.StrategicProbab = 1; } else if (!node.State.IsGameOver) { if (node.State.IsPlayerActing(_step3CurPos)) { // Sum of strategic probability of children must be equal to the str. prob. of the parent. double StrategicProbabOfChildren = 0; for (int c = 0; c < playerNode.Children.Count; ++c) { StrategicProbabOfChildren += playerNode.Children[c].StrategicProbab; } if ( !FloatingPoint.AreEqualRel(playerNode.StrategicProbab, StrategicProbabOfChildren, 0.000001)) { throw new ApplicationException( string.Format( "Player {0}, node id {1} : strategic probab. {2} != sum of strategic probab. of children {3}", _step3CurPos, playerNode.Id, playerNode.StrategicProbab, StrategicProbabOfChildren)); } } else { // Strategic probability of each child must be the same as of the parent. for (int c = 0; c < playerNode.Children.Count; ++c) { playerNode.Children[c].StrategicProbab = playerNode.StrategicProbab; } } } node.StrategicProbab *= playerNode.StrategicProbab; return(true); }
public void SetPotShare(ushort activePlayers, double[] potShare) { int bitCount = CountBits.Count(activePlayers); // Now implement for heads-up only. if (bitCount < 1 || bitCount > 3) { throw new ApplicationException(String.Format("Wrong active player mask {0}, players count must be in range [1..2]", activePlayers)); } if (bitCount == 1) { return; } _potShare0 = potShare[0]; Debug.Assert(FloatingPoint.AreEqual(1.0, _potShare0 + potShare[1], 1e-12)); }
void OnNodeEnd(ChanceTree tree, Context[] stack, int depth) { Context context = stack[depth]; Int64 n = context.NodeIdx; if (!context.IsLeaf) { if (!FloatingPoint.AreEqual(tree.Nodes[context.NodeIdx].Probab, context.SumProbabsOfChildren, Epsilon)) { throw new ApplicationException(String.Format( "Node {0}: sum of chance probability of children {1} != chance probability of the paren {2}", context.NodeIdx, context.SumProbabsOfChildren, tree.Nodes[context.NodeIdx].Probab)); ; } } }
public JsonResult Post(FloatingPoint floatingPoint) { string sqlDataSource = _configuration.GetConnectionString("DevConnection"); SqlConnection conn = new SqlConnection(sqlDataSource); cmd = new SqlCommand("InsertFloatingPoint", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("Id", floatingPoint.Id); cmd.Parameters.AddWithValue("FloatingPointId", Guid.NewGuid()); cmd.Parameters.AddWithValue("Name ", floatingPoint.Name); cmd.Parameters.AddWithValue("District ", floatingPoint.District); cmd.Parameters.AddWithValue("City", floatingPoint.City); cmd.Parameters.AddWithValue("Lat", floatingPoint.Lat); cmd.Parameters.AddWithValue("Lng", floatingPoint.Lng); cmd.Parameters.AddWithValue("IsDealer", floatingPoint.IsDealer); cmd.Parameters.AddWithValue("CreatedBy", Guid.NewGuid()); cmd.Parameters.AddWithValue("CreatedDate", DateTime.UtcNow); cmd.Parameters.AddWithValue("RouteDay", ""); cmd.Parameters.AddWithValue("ShopName", ""); cmd.Parameters.AddWithValue("OwnerName", ""); cmd.Parameters.AddWithValue("OwnerPhone", ""); cmd.Parameters.AddWithValue("Competitor1TvWalton", 0); cmd.Parameters.AddWithValue("Competitor1RfWalton", 0); cmd.Parameters.AddWithValue("Competitor2TvVision", 0); cmd.Parameters.AddWithValue("Competitor2RfVision", 0); cmd.Parameters.AddWithValue("Competitor3TvMarcel", 0); cmd.Parameters.AddWithValue("Competitor3RfMinister", 0); cmd.Parameters.AddWithValue("MonthlySaleTv", 0); cmd.Parameters.AddWithValue("MonthlySaleRf", 0); cmd.Parameters.AddWithValue("MonthlySaleAc", 0); cmd.Parameters.AddWithValue("ShowroomSize", 0); cmd.Parameters.AddWithValue("DisplayOut", 0); cmd.Parameters.AddWithValue("DisplayIn", 0); conn.Open(); int a = cmd.ExecuteNonQuery(); conn.Close(); if (a > 0) { return(new JsonResult("Saved")); } return(new JsonResult(0)); }
protected override void OnNodeEndFunc(StrategyTree tree, Context[] stack, int depth) { if (stack[depth].IsVerificationNeeded) { Context context = stack[depth]; if (!NonZeroSumsOnly || context.SumProbabilityOfChildren != 0) { if (!FloatingPoint.AreEqual(context.SumProbabilityOfChildren, context.Probability, Epsilon)) { throw new VerificationException { Text = string.Format("Node {0}, depth {1}: sum of childen {2} differs from expected {3} (epsilon {4}).", context.NodeIdx, depth, context.SumProbabilityOfChildren, context.Probability, Epsilon) }; } } } }
public void Visit(FloatingPoint f) { Debug.Assert(this.Size == 32 || this.Size == 64); if (this.Size == 32) { this.CppType = "float"; this.CaptureType = "float"; } else { this.CppType = "double"; this.CaptureType = "double"; } // Floating point types are captured as uints if we need to perofrm bit manipulation on them (e.g. masking, shifting) if (this.NeedsMasking) { this.CaptureType = String.Format("std::uint{0}_t", this.CaptureSize); } }
public static double CalculateLagrangeRemainder(Expr function, string variableName, int n, FloatingPoint x, FloatingPoint x0) { var results = new List <double>(); var length = GetLength(Math.Min(x.RealValue, x0.RealValue), Math.Max(x.RealValue, x0.RealValue)); var increment = length / 10; double currentIncrement = Math.Min(x.RealValue, x0.RealValue); var factorial = (FloatingPoint)SpecialFunctions.Factorial(n + 1); while (currentIncrement < Math.Max(x.RealValue, x0.RealValue)) { var variable = new Dictionary <string, FloatingPoint> { { variableName, currentIncrement } }; var derivativeResult = function.CalculateFunctionAtDerivative(variable, Expr.Variable(variableName), n + 1); var result = derivativeResult.RealValue / factorial.RealValue * Math.Pow(Math.Abs(x.RealValue - x0.RealValue), n + 1); results.Add(Math.Abs(result)); currentIncrement += increment; } var variableMax = new Dictionary <string, FloatingPoint> { { variableName, Math.Max(x.RealValue, x0.RealValue) } }; var derivativeResultMax = function.CalculateFunctionAtDerivative(variableMax, Expr.Variable(variableName), n + 1); var resultMax = derivativeResultMax.RealValue / factorial.RealValue * Math.Pow(Math.Abs(x.RealValue - x0.RealValue), n + 1); results.Add(Math.Abs(resultMax)); return(results.Max(x => x)); }
private static FloatingPoint GetRandomNumberInRange(FloatingPoint min, FloatingPoint max) => new Random().NextDouble() * (max.RealValue - min.RealValue) + min.RealValue;
/// <summary> /// Processes each poker action received from the server. /// Updates the game state and moves to the next node in our strategy. /// </summary> /// <param name="pa"></param> void ProcessAction(PokerAction pa) { int chBegin, chCount; _strIndexes[_pos].GetChildrenBeginIdxAndCount(_curStrNodeIdx, out chBegin, out chCount); int nextStrNodeIdx = -1; if (pa.IsDealerAction()) { _gameState.UpdateByAction(pa, null); if (pa.Position >= 0 && pa.Position != _pos) { // This is a deal to an opponent // We can skip it for games without public cards (and it is very unlikely we will have some // in the future). return; } int[] hand = _deckDescr.GetIndexes(_gameState.Players[_pos].Hand); int abstrCard = _chanceAbsrtractions[_pos].GetAbstractCard(hand, hand.Length); for (int c = 0; c < chCount; ++c) { int stNodeIdx = _strIndexes[_pos].GetChildIdx(chBegin + c); StrategyTreeNode stNode = new StrategyTreeNode(); _strategies[_pos].GetNode(stNodeIdx, &stNode); if (!stNode.IsDealerAction) { throw new ApplicationException( String.Format("{0} : expected strategy child: dealer action but was: '{1}'", GetBotStateDiagText(), stNode.ToStrategicString(null))); } if (stNode.Card == abstrCard) { nextStrNodeIdx = stNodeIdx; goto searchFinished; } } } else // Player action { double inPotBefore = _gameState.Players[pa.Position].InPot; _gameState.UpdateByAction(pa, null); double inPotAfter = _gameState.Players[pa.Position].InPot; double actualAmount = inPotAfter - inPotBefore; double bestAmount = double.MinValue; for (int c = 0; c < chCount; ++c) { int stNodeIdx = _strIndexes[_pos].GetChildIdx(chBegin + c); StrategyTreeNode stNode = new StrategyTreeNode(); _strategies[_pos].GetNode(stNodeIdx, &stNode); if (!stNode.IsPlayerAction(pa.Position)) { throw new ApplicationException( String.Format("{0} : expected strategy child: player action pos {1} but was: '{2}'", GetBotStateDiagText(), pa.Position, stNode.ToStrategicString(null))); } double amount = stNode.Amount; switch (_amountSearchMethod) { case AmountSearchMethod.Equal: if (FloatingPoint.AreEqual(amount, actualAmount, AMOUNT_EPSILON)) { nextStrNodeIdx = stNodeIdx; goto searchFinished; } break; case AmountSearchMethod.Closest: if (Math.Abs(amount - actualAmount) < Math.Abs(bestAmount - actualAmount)) { bestAmount = amount; nextStrNodeIdx = stNodeIdx; } break; } } } searchFinished: if (nextStrNodeIdx == -1) { throw new ApplicationException( String.Format("{0} : cannot find strategy action for poker action '{1}'", GetBotStateDiagText(), pa.ToGameString())); } _curStrNodeIdx = nextStrNodeIdx; }
public FloatingPoint Add(FloatingPoint p) { X += p.X; Y += p.Y; return(this); }
/// <summary> /// 去读配置项重新计算结果,更新数据 /// </summary> public static void ReCalculation(string projectId) { var list = DAL.CommonDAL.GetProjectItemList(projectId); var tongjiList = new List <Model.Tongji>(); #region 加载配置 Model.SysConfig config = ReadConfig(); if (config == null || string.IsNullOrEmpty(config.HanLiang)) { return; } #endregion #region 计算含量 Action <Model.DrugProjectItem> countHL = (Model.DrugProjectItem s) => { try { var dic = new Dictionary <string, FloatingPoint>() { { "供试峰面积", float.Parse(s.PJSFMJ) }, { "供试称样量", float.Parse(s.GSCYL) }, { "稀释倍数", float.Parse(s.XSBS) }, { "对照浓度", float.Parse(s.DZLD) }, { "对照峰面积", float.Parse(s.DZFMJ) } }; FloatingPoint value = Evaluate.Evaluate(dic, Infix.ParseOrUndefined(config.HanLiang)); s.HL = Math.Round(value.RealValue, config.HanLiangPoint, MidpointRounding.AwayFromZero).ToString(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }; #endregion #region 计算平均含量和方差 list.ForEach(s => countHL(s)); var yplist = list.Where(s => s.type.Trim() == Model.DrugType.饮片.ToString()); var tjlist = list.Where(s => s.type.Trim() == Model.DrugType.汤剂.ToString()); Action <string, double, bool> addTongji = (string key, double PJHL, bool isYp) => { if (isYp) { if (tongjiList.Any(s => s.GroupName == key)) { tongjiList.Where(s => s.GroupName == key).FirstOrDefault().YPHL = PJHL; } else { tongjiList.Add(new Model.Tongji() { GroupName = key, YPHL = PJHL }); } } else { if (tongjiList.Any(s => s.GroupName == key)) { tongjiList.Where(s => s.GroupName == key).FirstOrDefault().TJHL = PJHL; } else { tongjiList.Add(new Model.Tongji() { GroupName = key, TJHL = PJHL }); } } }; Action <List <Model.DrugProjectItem>, bool> countPJHL = (List <Model.DrugProjectItem> models, bool fc) => { foreach (var item in models.GroupBy(s => s.CodeNum1)) { double PJHL = 0; int lastId = 0; List <FcEntity> fclist = new List <Win.FcEntity>(); int index = 0; foreach (var sitem in item) { PJHL += Convert.ToDouble(sitem.HL); lastId = sitem.ID; if (index > 1) { index = 0; } fclist.Add(new Win.FcEntity() { HL = Convert.ToDouble(sitem.HL), ID = sitem.ID }); } if (lastId != 0 && item.Count() > 1) { PJHL = Math.Round(PJHL / item.Count(), config.PingJunHLPoint, MidpointRounding.AwayFromZero); list.Where(s => s.ID == lastId).FirstOrDefault().PJHL = PJHL.ToString(); addTongji(item.Key, PJHL, fc); if (fc) { if (fclist.Count >= 2) { double fac = 0; fclist = fclist.OrderBy(s => s.ID).ToList(); for (int i = 1; i < fclist.Count; i++) { fac = fclist[i - 1].HL - fclist[i].HL; } list.Where(s => s.ID == lastId).FirstOrDefault().FC = Math.Round(fac, config.FangChaPoint, MidpointRounding.AwayFromZero).ToString(); } } } } }; countPJHL(yplist.Where(s => s.IsFuCe == "False").ToList(), true); countPJHL(yplist.Where(s => s.IsFuCe != "False").ToList(), true); countPJHL(tjlist.Where(s => s.IsFuCe == "False").ToList(), false); countPJHL(tjlist.Where(s => s.IsFuCe != "False").ToList(), false); #endregion #region 统计数据 foreach (var item in tongjiList) { item.ZYLv = Math.Round((item.TJHL / item.YPHL) * 100, 2, MidpointRounding.AwayFromZero); } DAL.CommonDAL.AddProjectTongji(tongjiList, projectId); #endregion #region 计算完毕更新数据库 foreach (var item in list) { DAL.CommonDAL.UpdateProjectItem(item); } #endregion }
//Раcчет значения правой части ОДУ f(x, y1, y2 ... yn) public double F(Dictionary <string, FloatingPoint> vars) { FloatingPoint res = function.Evaluate(vars); return(res.RealValue); }
static void Main(string[] args) { //Используемые переменныые var x1 = Expr.Variable("x1"); var x2 = Expr.Variable("x2"); var x3 = Expr.Variable("x3"); var x4 = Expr.Variable("x4"); var x5 = Expr.Variable("x5"); var x6 = Expr.Variable("x6"); var x7 = Expr.Variable("x7"); var x8 = Expr.Variable("x8"); var x9 = Expr.Variable("x9"); var x10 = Expr.Variable("x10"); //Пример 1 var values1 = new Dictionary <string, FloatingPoint> { { "x1", 0.9 }, { "x2", 0.5 } }; var f1 = (x1 * x1); var f2 = (x2 * x2 - 1); var f3 = (x1 * x1 * x1); var f4 = (-x2); Expr[,] functions1 = new Expr[, ] { { f1, f2 }, { f3, f4 } }; var system1 = new EquationsSystem(functions1); system1.Print(); var newton1 = new NewtonMethodSystem(system1, values1, 0.0001); newton1.Solve(); //Пример 2 var values2 = new Dictionary <string, FloatingPoint> { { "x1", 0.5 }, { "x2", 0.5 }, { "x3", 0.5 } }; f1 = (x1 * x1); f2 = (x2 * x2); f3 = (x3 * x3 - 1); f4 = (2 * x1 * x1); var f5 = f2; var f6 = (-4 * x3); var f7 = (3 * x1 * x1); var f8 = (-4 * x2); var f9 = (x3 * x3); Expr[,] functions2 = new Expr[, ] { { f1, f2, f3 }, { f4, f5, f6 }, { f7, f8, f9 } }; var system2 = new EquationsSystem(functions2); system2.Print(); var newton2 = new NewtonMethodSystem(system2, values2, 0.0001); newton2.Solve(); Console.WriteLine("Введите уравнения системы, =0 в конце вводить не нужно"); Console.WriteLine("По окончанию ввода введите 0"); List <string> equations = new List <string>(); while (true) { string temp = Console.ReadLine(); if (temp == "0") { break; } equations.Add(temp); } Expr[,] functions3 = new Expr[equations.Count, equations.Count]; int i = 0; foreach (string equation in equations) { Expr temp = Expr.Parse(equation); List <Expr> expression = new List <Expr>(); for (int j = 0; j < temp.NumberOfOperands; j++) { expression.Add(temp[j]); } if (temp.NumberOfOperands > equations.Count) { expression[0] = temp[0] + temp[1]; expression.RemoveAt(1); } for (int j = 0; j < equations.Count; j++) { functions3[i, j] = expression[j]; } i++; } var system3 = new EquationsSystem(functions3); Console.WriteLine("Введите изначальное приближение"); var values3 = new Dictionary <string, FloatingPoint>(equations.Count); for (int j = 0; j < equations.Count; j++) { Console.Write($"x{j+1}="); String[] temp = Console.ReadLine().Split('='); FloatingPoint floatingPoint = float.Parse(temp[0]); values3.Add($"x{j + 1}", floatingPoint); } var newton3 = new NewtonMethodSystem(system3, values3, 0.0001); newton3.Solve(); Console.ReadLine(); }
public double Solve(double a, double b, double epsilon, bool verifyFunctionShape) { if (a > b) { ShortSequence.Swap(ref a, ref b); } double x1 = b - (b - a) / GR; double x2 = a + (b - a) / GR; double f1 = F(x1); double f2 = F(x2); double fStart = 0, fEnd = 0; if (verifyFunctionShape) { fStart = F(a); fEnd = F(b); if (!IsShapeCorrect(fStart, fEnd, f1) || !IsShapeCorrect(fStart, fEnd, f2)) { throw new ApplicationException("Wrong function shape"); } } for (;;) { if (b - a <= epsilon) { return((b + a) * 0.5); } if (f1 > f2) { // Replace a a = x1; x1 = x2; f1 = f2; x2 = a + (b - a) / GR; f2 = F(x2); if (verifyFunctionShape) { if (!IsShapeCorrect(fStart, fEnd, f2)) { throw new ApplicationException("Wrong function shape"); } } } else { // Replace b b = x2; x2 = x1; f2 = f1; x1 = b - (b - a) / GR; f1 = F(x1); if (verifyFunctionShape) { if (!IsShapeCorrect(fStart, fEnd, f1)) { throw new ApplicationException("Wrong function shape"); } } } Debug.Assert(FloatingPoint.AreEqual((b - a) / (x2 - a), GR, 1e-10)); Debug.Assert(FloatingPoint.AreEqual((b - a) / (b - x1), GR, 1e-10)); } }
public void Visit(FloatingPoint f) { CreateDeclaration(); CreateBody(); }