public ViewResult Trapezoids(NumericalIntegration model) { if (!ModelState.IsValid) { ModelState.AddModelError("", Resources.MethodsController_Newton_Пожалуйста_введите_корректно_начальные_данные); return(View(model)); } NumericalMethods method = new NumericalMethods(); try { model.Result = method.MethodOfTrapezoids(model.Function, model.A, model.B, model.N); if (model.Result.Equals(Double.NaN)) { ModelState.AddModelError("", Resources.MethodsController_Chord_Решение_не_найдено__Произошло_деление_на_ноль_); return(View(model)); } } catch (Exception) { ModelState.AddModelError("", Resources.MethodsController_Chord_Метод_расходится); return(View(model)); } if (!String.IsNullOrEmpty(model.Function)) { ViewBag.Adress = "http://www.wolframalpha.com/input/?i=" + Server.UrlEncode("integrate sqrt(" + model.Function + ")dx trapezoidal rule x=" + model.A + ".." + model.B); } return(View(model)); }
// Use this for initialization void Start() { double[] A = new double[] { 4, -1 }; double[] B = new double[] { 3 }; double[] C = new double[] { 2 }; double[] D = new double[] { 2, -1 }; double[] E = new double[] { 1, -1 }; double[] F = new double[] { 1 }; Rational a = new Rational(new Polynomial(A)); Rational b = new Rational(new Polynomial(B)); Rational c = new Rational(new Polynomial(C)); Rational d = new Rational(new Polynomial(D)); Rational e = new Rational(new Polynomial(E)); Rational f = new Rational(new Polynomial(F)); Rational[][] m = new Rational[3][]; for (int i = 0; i < 3; i++) { m[i] = new Rational[3]; } m[0][0] = a; m[0][1] = f; m[0][2] = c; m[1][0] = b; m[1][1] = d; m[1][2] = b; m[2][0] = c; m[2][1] = f; m[2][2] = e; Matrix M = new Matrix(m); Polynomial p = M.GetDeterminant(); double[] roots = NumericalMethods.ExtractRoots(p); for (int i = 0; i < roots.Length; i++) { Debug.Log(roots[i]); } }
public PairAdapter(string instrument, TestResult data, string FirstName, string SecondName) { this.cFirstName = FirstName; this.cSecondName = SecondName; m_instrument = instrument; m_TradingCurrency = instrument.Substring(3, 3); m_MarginCurrency = instrument.Substring(0, 3); InitMinMax(data); int rows = (m_maxFirst - m_minFirst) / cStepFirst + 1; int columns = (m_maxSecond - m_minSecond) / cStepFirst + 1; m_table = new double[rows, columns]; foreach (var element in data.listOnePeriodresult) { Construct(element); } foreach (var element in m_param2equity) { double[] temp = element.Value.ToArray(); temp = NumericalMethods.CalculateRelativeVariation(temp); double student = Statistics.CalculateConfidenceInterval(temp, 0.95).Minimum; m_table[element.Key.Y, element.Key.X] = 1 + student; } }
double GetAlphaDt(double dt) { PCurve curve = Trajectory.Curve; double a = curve.a; // большая полуось double n = Math.Sqrt(PWorld.G * GravityBody.Mass / (a * a * a)); //среднее движение double M = n * dt; // средняя аномалия var func = curve.KeplerFunc; var Dfunc = curve.KeplerDFunc; double M0 = curve.e < 1 ? M : -M; int t; //double tEx = NumericalMethods.NewtonForKepler(curve.KeplerFunc, curve.KeplerDFunc, M0, M, out t); double tEx = NumericalMethods.StaticPointKepler(curve.e, M0, out t); double alpha = curve.AlphaFromEAnomaly(tEx); if (t > 100) { Console.Write("angle:" + alpha + " M:" + M + " E:" + tEx + " func:" + func(tEx, M) + " t:" + t); } //UnityEngine.Debug.Log("e: " + curve.e+ " sqrt((e+1)/(e-1)):" + Math.Sqrt((curve.e + 1) / (curve.e - 1)) + " tanh(H/2)" + Math.Tanh(Ex/2)); //UnityEngine.Debug.Log("dt " + dt + " Ex " + Ex + " alpha "+alpha + " M: " + M + " func "+ func(Ex,M)); return(alpha); }
public ViewResult Method38(NumericalIntegration model) { if (!ModelState.IsValid) { ModelState.AddModelError("", Resources.MethodsController_Newton_Пожалуйста_введите_корректно_начальные_данные); return(View(model)); } NumericalMethods method = new NumericalMethods(); try { model.Result = method.Method_3_8(model.Function, model.A, model.B, model.N); if (model.Result.Equals(Double.NaN)) { ModelState.AddModelError("", Resources.MethodsController_Chord_Решение_не_найдено__Произошло_деление_на_ноль_); return(View(model)); } } catch (Exception) { ModelState.AddModelError("", Resources.MethodsController_Chord_Метод_расходится); return(View(model)); } return(View(model)); }
static void Main(string[] args) { expression = Expression; var metods = new NumericalMethods(); metods.EulersMethod(Expression, 1, 2, 1, 5, 0); }
public void ValidateCalculateLinearDiscreteByEquity() { Portfolio portfolio = Portfolio.CalculateLinear(m_equity, 0.95, 2000000, 1); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Profit, 44355.3, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.When, 45.0904, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Coefficients[0], 1.00003, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Coefficients[1], 3.82186, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Coefficients[2], 28.9476, 0.001)); }
public void ValidateCalculateLinearFastDiscreteByEquityAndMargin2() { Portfolio portfolio = Portfolio.CalculateLinearFast(m_equity, m_margin, 10000000, 0.95, 3000000, 175, 1); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Profit, 66302.18930833213, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.When, 45.247374827270384, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Coefficients[0], 0, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Coefficients[1], 6.227138204537038, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Coefficients[2], 42.8705934207335, 0.001)); }
public void ValidateCalculateLinearFastDiscreteByEquityAndMargin() { Portfolio portfolio = Portfolio.CalculateLinearFast(m_equity, m_margin, 10000000, 0.95, 3000000, 175, 0.5); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Profit, 66499.84788772937, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.When, 45.11288512405088, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Coefficients[0], 0.7282109294652774, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Coefficients[1], 6.031212361462828, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Coefficients[2], 43.14954986809901, 0.001)); }
public void ValidateCalculateLinearFastDiscreteByEquity() { Portfolio portfolio = Portfolio.CalculateLinearFast(m_equity, 0.95, 1000000, 1); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Profit, 22100.7, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.When, 45.2474, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Coefficients[0], 0, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Coefficients[1], 2.07571, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Coefficients[2], 14.2902, 0.001)); }
public void ValidateCalculateLinearByEquity() { Portfolio portfolio = Portfolio.CalculateLinear(m_equity, 0.95, 2000000); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Profit, 44361.678434564674, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.When, 45.08395699716278, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Coefficients[0], 0.8343726990339021, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Coefficients[1], 3.8794446786429853, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(portfolio.Coefficients[2], 28.907356443934027, 0.001)); }
public ViewResult Rectangles(RectanglesIntegration model) { if (!ModelState.IsValid) { ModelState.AddModelError("", "Пожалуйста,введите корректно начальные данные"); return(View(model)); } NumericalMethods method = new NumericalMethods(); try { switch (model.Method) { case "Right": model.Result = method.RightRectangles(model.Function, model.A, model.B, model.N); ViewBag.Adress = "http://www.wolframalpha.com/input/?i=" + Server.UrlEncode("integrate sqrt(" + model.Function + ")dx right endpoint method x=" + model.A + ".." + model.B); break; case "Midle": model.Result = method.MidleRectangles(model.Function, model.A, model.B, model.N); ViewBag.Adress = "http://www.wolframalpha.com/input/?i=" + Server.UrlEncode("integrate sqrt(" + model.Function + ")dx midpoint method x=" + model.A + ".." + model.B); break; case "Left": model.Result = method.LeftRectangles(model.Function, model.A, model.B, model.N); ViewBag.Adress = "http://www.wolframalpha.com/input/?i=" + Server.UrlEncode("integrate sqrt(" + model.Function + ")dx left endpoint method x=" + model.A + ".." + model.B); break; } if (model.Result.Equals(Double.NaN)) { ModelState.AddModelError("", Resources.MethodsController_Chord_Решение_не_найдено__Произошло_деление_на_ноль_); return(View(model)); } } catch (Exception) { ModelState.AddModelError("", Resources.MethodsController_Chord_Метод_расходится); return(View(model)); } return(View(model)); }
public void ValidateConfidenceInterval() { /* * Needs["HypothesisTesting`"]; * MeanCI[{10, 11, 12}, ConfidenceLevel -> 0.8] * {9.911337892096364, 12.088662107903636} */ double[] data = new double[] { 10, 11, 12 }; double level = 0.8; Interval interval = Statistics.CalculateConfidenceInterval(data, level); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(9.911337892096364, interval.Minimum)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(12.088662107903636, interval.Maximum)); }
public static double[] ExtractRoots(Polynomial p) { int size = p.Order; double initialValue = 0.9; double[] roots = new double[p.Order]; Debug.Log(p.Order); for (int i = 0; i < size; i++) { Debug.Log(i); roots[i] = NumericalMethods.VonMises(p, initialValue, 0.001); Polynomial q = new Polynomial(1); q.AddValue(0, -roots[i]); q.AddValue(1, 1); Debug.Log(p); p = NumericalMethods.LongDivision(p, q); initialValue = roots[i]; } return roots; }
public override string ToString() { double average = Sum / Count; double sigmaTime = NumericalMethods.Sqrt(Sum2 / Count - average * average); double spread = Spread / Count; double sigmaSpread = NumericalMethods.Sqrt(Spread2 / Count - spread * spread); double part = Count; part /= AllCount; int spreadInPips = SymbolsManager.PipsFromValue(m_symbol, spread); int sigmaSpreadInPips = SymbolsManager.PipsFromValue(m_symbol, sigmaSpread); string result = string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}", m_tpInPips, average, sigmaTime, spreadInPips, sigmaSpreadInPips, part); return(result); }
public void CompareOneAndMultiplyAnalyses() { UnilateralTickCollection <int> bids = new UnilateralTickCollection <int>(s_bids); UnilateralTickCollection <int> asks = new UnilateralTickCollection <int>(s_asks); ResetTimeAnalyzer first = new ResetTimeAnalyzer(0.01, 1 / 60d, bids, asks, 1); ResetTimeAnalyzer second = new ResetTimeAnalyzer(0.01, 1 / 60d, bids, asks, 1); first.Process(s_buy, s_sell); second.Process(s_buy, s_sell); Assert.IsTrue(first.TakeProfit == second.TakeProfit); Assert.IsTrue(first.TimeFactor == second.TimeFactor); Assert.IsTrue(first.AverageTime == second.AverageTime); Assert.IsTrue(first.AverageLoss == second.AverageLoss); Assert.IsTrue(first.SigmaTime == second.SigmaTime); Assert.IsTrue(first.SigmaLoss == second.SigmaLoss); Assert.IsTrue(first.ResettingPercentage == second.ResettingPercentage); second.Process(s_buy, s_sell); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(first.TakeProfit, second.TakeProfit)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(first.TimeFactor, second.TimeFactor)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(first.AverageTime, second.AverageTime)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(first.AverageLoss, second.AverageLoss)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(first.SigmaTime, second.SigmaTime, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(first.SigmaLoss, second.SigmaLoss, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(first.ResettingPercentage, second.ResettingPercentage)); second.Process(s_buy, s_sell); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(first.TakeProfit, second.TakeProfit)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(first.TimeFactor, second.TimeFactor)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(first.AverageTime, second.AverageTime)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(first.AverageLoss, second.AverageLoss)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(first.SigmaTime, second.SigmaTime, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(first.SigmaLoss, second.SigmaLoss, 0.001)); Assert.IsTrue(NumericalMethods.IsApproximatelyEqual(first.ResettingPercentage, second.ResettingPercentage)); }
static void Main(string[] args) { Console.WriteLine("-------------------------- Stage_1 (1.0) --------------------------"); { Func <double, double> constantFunctionZero = Functions.Constant(0.0f); Func <double, double> constantFunctionOne = Functions.Constant(1.0f); Func <double, double> identityFunctionZero = Functions.Identity(); Func <double, double> exponentialfunctionZero = Functions.Exp(0.0f); Func <double, double> exponentialfunctionOne = Functions.Exp(0.15f); { Console.WriteLine($"Constant Function #0 : {constantFunctionZero(5.0f),2:F} (Should be 0.00)"); Console.WriteLine($"Constant Function #1 : {constantFunctionOne(5.0f),2:F} (Should be 1.00)"); Console.WriteLine($"Identity Function #0 : {identityFunctionZero(5.0f),2:F} (Should be 5.00)"); Console.WriteLine($"Exponential Function #0 : {exponentialfunctionZero(5.0f),2:F} (Should be 0.00)"); Console.WriteLine($"Exponential Function #1 : {exponentialfunctionOne(5.0f),2:F} (Should be 22.26)"); } } Console.WriteLine("-------------------------- Stage_2 (1.0) --------------------------"); { Function constantFunctionZero = Functions.Constant(1.0f); Function identityFunctionZero = Functions.Identity(); Function exponentialfunctionZero = new Function(Functions.Exp(1.0f)); { Console.WriteLine($"Constant Function #0 : {constantFunctionZero.Value(5.0f),2:F} (Should be 1.00)"); Console.WriteLine($"Identity Function #0 : {identityFunctionZero.Value(5.0f),2:F} (Should be 5.00)"); Console.Write($"Exponential Function #0 : "); foreach (double currentValue in exponentialfunctionZero.GetValues(1.0f, 2.0f, 5)) { Console.Write($"{currentValue,2:F} "); } Console.WriteLine("(Shoule be 2.72 3.32 4.06 4.95 6.05 7.39)"); } } Console.WriteLine("-------------------------- Stage_3 (1.5) --------------------------"); { Polynomial polynomialFunctionZero = new Polynomial(new double[] { 4.0f, 1.0f, 1.0f }); Polynomial polynomialFunctionOne = new Polynomial(new double[] { 0.0f, 2.0f }); Console.WriteLine($"Polynomial Function #0 : {polynomialFunctionZero.Value(2.0f),2:F} (Should be 10.00)"); Console.WriteLine($"Polynomial Function #1 : {polynomialFunctionOne.Value(3.0f),2:F} (Should be 6.00)"); Console.WriteLine($"Polynomial Derivative #0 : {polynomialFunctionOne.Derivative(2.25f),2:F} (Should be 2.00)"); } Console.WriteLine("-------------------------- Stage_4 (1.5) --------------------------"); { Function exponentialfunctionZero = Functions.Exp(1.0f); Polynomial polynomialFunctionZero = new Polynomial(new double[] { 0.0f, 2.0f }); Polynomial polynomialFunctionOne = new Polynomial(new double[] { 4.0f, 1.5f, 1.0f, 7.5f, 12345.6f }); Console.WriteLine($"Integral Function #0 : {exponentialfunctionZero.Integral(0.0f, 2.0f),2:F} (Should be 6.33)"); Console.WriteLine($"Integral Function #1 : {polynomialFunctionZero.Integral(0.0f, 2.0f),2:F} (Should be 3.96)"); Console.WriteLine($"Derivative Function #0 : {exponentialfunctionZero.Derivative(2.25f),2:F} (Should be 9.49)"); Console.WriteLine($"Polynomial Derivative #1 (formula) : {polynomialFunctionOne.Derivative(2.25f),2:F} (Should be 562616.29)"); Console.WriteLine($"Polynomial Derivative #1 (numerical) : {NumericalMethods.Derivative(polynomialFunctionOne, 2.25f),2:F} (Should be 562616.40)"); } }
public PCurve MakeCurve(double e, double p, PVector3 pos, PVector3 velocity, PVector3 GBodyPosition, double GBodyMass, int StepCount, bool TransitionCurve = false) { #region Начальный угол, построение кривой, апоцентр\перицентр var crv = new PCurve { e = e, p = p, Curve = new List <Pair <PVector3, double> >(), Lv = PVector3.Cross(pos, velocity) }; var IAngleCosValue = (p - pos.magnitude) / (e * pos.magnitude); double InitAngle = Math.Acos(IAngleCosValue); if (double.IsNaN(InitAngle)) { InitAngle = IAngleCosValue < 0 ? Math.PI : 0; } if (PVector3.Dot(pos, velocity) < 0) // проверяем направление движения (см. радиальную компоненту скорости) { InitAngle = 2 * Math.PI - InitAngle; } var Vz = pos.normalized.RotateAround(crv.Lv, -InitAngle); // выравниваем на перицентр crv.Periapsis = new Pair <PVector3, double>(Vz * crv.RFuncAlpha(0), 0); crv.Apoapsis = new Pair <PVector3, double>(crv.RFuncAlphaV3(Math.PI), Math.PI); for (double x = -Math.PI; x <= Math.PI; x += (2 * Math.PI) / StepCount) { var alpha = e < 1 ? crv.AlphaFromEAnomaly(x) : x; //var alpha = crv.AlphaFromEAnomaly(x); if (e < 1) { crv.Curve.Add(new Pair <PVector3, double>(crv.RFuncAlphaV3(alpha) + GBodyPosition, alpha)); } else if (Math.Abs(x) < Math.Acos(-1 / crv.e)) { crv.Curve.Add(new Pair <PVector3, double>(crv.RFuncAlphaV3(alpha) + GBodyPosition, alpha)); } } crv.PositionAngle = InitAngle; #endregion #region Начальное время double t; if (crv.e < 1) { double E = 2 * Math.Atan(Math.Sqrt((1 - e) / (1 + e)) * Math.Tan(InitAngle / 2)); // эксцентрическая аномалия (идем по обратному пути к уравнению кеплера) double a = crv.a; // большая полуось t = Math.Sqrt(a * a * a / (PWorld.G * GBodyMass)) * (E - e * Math.Sin(E)); } else { double H = 2 * HyperbolicFuncs.Atanh(Math.Sqrt((e - 1) / (e + 1)) * Math.Tan(InitAngle / 2)); double k = Math.Sqrt(Math.Pow(crv.a, 3) / (PWorld.G * GBodyMass)); // 1/n t = k * (e * Math.Sinh(H) - H); } crv.PositionTime = t; // для уравнения кеплера начальное время - до перицентра #endregion #region Наклонение орбиты, AN\DN double inclination = PVector3.Angle(crv.Lv, PVector3.up) * 180.0 / Math.PI; crv.inclination = inclination <= 90 ? inclination : 180 - inclination; if (Math.Abs(crv.inclination) > 0) { var DescendingNodeV = PVector3.Cross(crv.Lv, PVector3.up).normalized; double DNAngle = PVector3.Angle(DescendingNodeV, crv.Periapsis.a); double DNLength = crv.RFuncAlpha(DNAngle); double ANAngle = DNAngle - Math.PI; double ANLength = crv.RFuncAlpha(ANAngle); crv.DN = new Pair <PVector3, double>(DescendingNodeV * DNLength, DNAngle); crv.AN = new Pair <PVector3, double>(-DescendingNodeV * ANLength, -DNAngle); } #endregion #region Точка перехода var TPoint = new Pair <PVector3, double>(); var isTPoint = false; foreach (var gb in World.Gravitybodies) { foreach (var point in crv.Curve) { double distSqr1 = (point.a - GBodyPosition).magnitude; double distSqr2 = (point.a - gb.Position).magnitude; if (!(distSqr1 * distSqr1 * gb.Mass - distSqr2 * distSqr2 * GBodyMass > 0)) { // грубый метод поиска точки перехода continue; } isTPoint = true; crv.PHGBody = gb; var C = GBodyPosition - gb.Position; Func <double, double> Falpha = alpha => Math.Pow(crv.RFuncAlpha(alpha), 2) * crv.PHGBody.Mass - (C + crv.RFuncAlphaV3(alpha)).sqrMagnitude * GBodyMass; int i = crv.Curve.IndexOf(point); int it; double a = /*crv.Curve[i+1 > crv.Curve.Count ? 1 : i+1].b*/ Math.PI; double b = /*crv.Curve[i - 3 < 0 ? crv.Curve.Count - 3 : i-3].b*/ 0; double angle = NumericalMethods.Dichotomy(Falpha, a, b, out it); // уточнение координат точки TPoint = new Pair <PVector3, double>(crv.RFuncAlphaV3(angle) + GBodyPosition, angle); if (it > 100) { Debug.Write("angle: " + angle * 180 / Math.PI + " iterations:" + it + " a:" + a * 180 / Math.PI + " b:" + b * 180 / Math.PI); } break; } if (isTPoint) { break; } } if (isTPoint) { crv.isTPoint = true; crv.TransitionPoint = TPoint; } else { crv.isTPoint = false; } #endregion #region Фантомная траектория перехода if (Curve == null) { return(crv); } if (!isTPoint || TransitionCurve) { return(crv); } PCurve PHCurve; PVector3 PHVelocity = GetVelocityMagnitude(TPoint.a, TPoint.b); PVector3 PHPosition = TPoint.a - crv.PHGBody.Position; var PHCInfo = GetEllipseInfo(PHPosition, PHVelocity, Body.Mass, crv.PHGBody.Mass); PHCurve = MakeCurve(PHCInfo.a, PHCInfo.b, PHPosition, PHVelocity, crv.PHGBody.Position, crv.PHGBody.Mass, PSettings.CurveElementCount, true); crv.TransitionCurve = PHCurve; #endregion return(crv); }