static void Main(string[] args) { // Quadratic var quadratic_evaluator = new PrefixEvaluatorBuilder(); var quadratic = new Quadratic(quadratic_evaluator); quadratic.Construct(); for (int i = 1; i <= 10; i++) Console.WriteLine("{0} squared is {1}", i, quadratic_evaluator.Evaluate(new Dictionary<string, decimal> { { "x", i } })); // 1/x var hyperbolic_evaluator = new PrefixEvaluatorBuilder(); var hyperbolic = new Hyperbola(hyperbolic_evaluator); hyperbolic.Construct(); for (int i = 1; i <= 10; i++) Console.WriteLine("1 / {0} is {1}", i, hyperbolic_evaluator.Evaluate(new Dictionary<string, decimal> { { "x", i } })); // (1 -x)/x var another_hyperbolic_evaluator = new PrefixEvaluatorBuilder(); var another_hyperbolic = new AnotherHyperbola(another_hyperbolic_evaluator); another_hyperbolic.Construct(); for (int i = 1; i <= 10; i++) Console.WriteLine("(1 - {0}) / {0} is {1}", i, another_hyperbolic_evaluator.Evaluate(new Dictionary<string, decimal> { { "x", i } })); Console.ReadLine(); //Could add a graphing builder that returns a Visual... }
public IQuadraticEquation Add(IQuadraticEquation subtractQuadraticEquation) { var output = new Quadratic(); output.Result = Result + subtractQuadraticEquation.Result; output.A = A + subtractQuadraticEquation.A; output.B = B + subtractQuadraticEquation.B; output.C = C + subtractQuadraticEquation.C; return(output); }
public void InInverse_InputAboveRange_ReturnsDestination() { Ease ease = new Quadratic(); float y = 1.6f; float expected = ease.Scale.X; float actual = ease.InInverse(y); Assert.AreEqual(expected, actual, 0.001f); }
public void InInverse_InputInRange_ReturnsExpectedValue() { Ease ease = new Quadratic(); float y = 0.6f; float expected = 0.7746f; float actual = ease.InInverse(y); Assert.AreEqual(expected, actual, 0.001f); }
public void Out_InputInRange_ReturnsExpectedValue() { Ease ease = new Quadratic(); float x = 0.6f; float expected = 0.84f; float actual = ease.Out(x); Assert.AreEqual(expected, actual, 0.001f); }
public void OutInverse_InputBelowRange_ReturnsOrigin() { Ease ease = new Quadratic(); float y = -0.6f; float expected = 0; float actual = ease.OutInverse(y); Assert.AreEqual(expected, actual, 0.001f); }
public void Out_InputAboveRange_ReturnsDestination() { Ease ease = new Quadratic(); float x = 1.5f; float expected = ease.Scale.Y; float actual = ease.Out(x); Assert.AreEqual(expected, actual, 0.001f); }
public IQuadraticEquation Subtract(IQuadraticEquation subtractQuadraticEquation) { var output = new Quadratic(); output.Result = Result - subtractQuadraticEquation.Result; output.A = A - subtractQuadraticEquation.A; output.B = B - subtractQuadraticEquation.B; output.C = C - subtractQuadraticEquation.C; return(output); }
///// <summary>Called when new data is received</summary> //public override void Step() //{ // var current_price = Instrument.CurrentPrice(0); // var sym = Instrument.Symbol; // // Find the stats for the recent price history // PriceStats.Add((double)current_price); // // Synchronise the Positions with our list // SynchroniseLivePositions(); // // Measure the current net position // var net = NetPosition; // // If the sum of all trades is greater than the threshold, cash in // // If the sum of all trades exceeds 90% of the balance to risk, bail out // var profit_threshold = Misc.Max(1.0, Broker.Balance * TakeProfitPC); // if (net > profit_threshold) // { // CloseOut(); // return; // Return so that closed positions get output while debugging // } // if (net < -BalanceRisked) // { // CloseOut(); // return; // Return so that closed positions get output while debugging // } // // Attempt to compress the positions // for (;Positions.Count > 2;) // { // var pos0 = Positions.Back(0); // var pos1 = Positions.Back(1); // if (pos0.NetProfit + pos1.NetProfit > 1.0) // { // Broker.ClosePosition(pos0); // Broker.ClosePosition(pos1); // continue; // } // break; // } // // If we have no position, make a trade // if (Positions.Count == 0) // { // // Get the current price direction // var q = Quadratic.FromPoints( // new v2(-2f, (float)Instrument[-2].Median), // new v2(-1f, (float)Instrument[-1].Median), // new v2(-0f, (float)Instrument[-0].Median)); // var next_price =(QuoteCurrency)q.F(1.0); // var tt = next_price > current_price ? TradeType.Buy : TradeType.Sell; // var sign = tt.Sign(); // // Create the initial trade // var volume = sym.VolumeMin; // var risk = Broker.MaxSL(Instrument, volume); // var ep = Instrument.CurrentPrice(sign); // var tp = ep + sign * risk; // var sl = ep - sign * risk; // var trade = new Trade(Instrument, tt, Label, ep, sl, tp, volume); // // Record how much we're risking on this set of trades // BalanceRisked = sym.QuoteToAcct(risk * volume); // // Open the position // var pos = Broker.CreateOrder(trade); // if (pos != null) // Positions.Add(pos); // } // else // { // // Get the loss threshold given the current number of trades // var loss_per_level = BalanceRisked / ReversesCount; // var loss_threshold = Positions.Count * loss_per_level; // // If the net profit has dropped below the threshold, open a reverse trade // if (net < -loss_threshold) // { // // The reverse trade is created such that the total risk remains the same. // var prev = Positions.Back(); // var volume = sym.NormalizeVolume(prev.Volume * (Positions.Count + 1) / Positions.Count); // var tt = prev.TradeType.Opposite(); // var ep = Instrument.CurrentPrice(tt.Sign()); // var tp = prev.StopLossAbs(); // var sl = prev.TakeProfitAbs(); // var trade = new Trade(Instrument, tt, Label, ep, sl, tp, volume); // // Open the reverse position // var pos = Broker.CreateOrder(trade); // if (pos != null) // Positions.Add(pos); // } // } // int break_point; // if (Instrument.NewCandle) // break_point = 1; //} ///// <summary>Update the collection 'Positions' with any live positions created by this strategy</summary> //private void SynchroniseLivePositions() //{ // var live_positions = Bot.Positions.ToHashSet(x => x.Id); // Positions.RemoveIf(x => !live_positions.Contains(x.Id)); //} /// <summary>Returns a trade when a likely good trade is identified. Or null</summary> private Trade FindEntry() { // Get the current price direction var q = Quadratic.FromPoints( new v2(-2f, (float)Instrument[-2].Close), new v2(-1f, (float)Instrument[-1].Close), new v2(-0f, (float)Instrument[-0].Close)); // Choose the trade type var curr_price = (double)Instrument.CurrentPrice(0); var next_price = q.F(1.0); var tt = next_price > curr_price ? TradeType.Buy : TradeType.Sell; var sign = tt.Sign(); { // Look for some confirming signals // Does it match the long period EMA? const double ema100_threshold_gradient = 0.1; // pips per index var ema100 = Bot.Indicators.ExponentialMovingAverage(Instrument.Data.Close, 100); var grad100 = ema100.Result.FirstDerivative() / Instrument.MCS; if (Math.Abs(grad100) < ema100_threshold_gradient || Math.Sign(grad100) != sign) { return(null); } // Does it match the short period EMA? const double ema14_threshold_gradient = 0.1f; // pips per index var ema14 = Bot.Indicators.ExponentialMovingAverage(Instrument.Data.Close, 14); var grad14 = ema14.Result.FirstDerivative() / Instrument.MCS; if (Math.Abs(grad14) < ema14_threshold_gradient || Math.Sign(grad14) != sign) { return(null); } // Is the price within the MCS of the long period EMA? if (Math.Abs(curr_price - ema100.Result.LastValue) > Instrument.MCS) { return(null); } // Is the instrument over-bought or over-sold var rsi = Bot.Indicators.RelativeStrengthIndex(Instrument.Data.Close, 14); if (tt == TradeType.Buy && rsi.Result.LastValue > 70.0) { return(null); // Over bought } if (tt == TradeType.Sell && rsi.Result.LastValue < 30.0) { return(null); // Over sold } // Has the current price just left a strong SnR level? // Is there a candle pattern that agrees with the trade } return(new Trade(Instrument, tt, Label)); }
public static float CalculateLerpValue(float lerpValue, Type easingType, bool isZeroToOne) { switch (easingType) { case Type.Linear: lerpValue = Linear.InOut(lerpValue); break; case Type.Quadratic: lerpValue = Quadratic.InOut(lerpValue); break; case Type.Cubic: lerpValue = Cubic.InOut(lerpValue); break; case Type.Quartic: lerpValue = Quartic.InOut(lerpValue); break; case Type.Quintic: lerpValue = Quintic.InOut(lerpValue); break; case Type.Sinusoidal: lerpValue = Sinusoidal.InOut(lerpValue); break; case Type.Exponential: lerpValue = Exponential.InOut(lerpValue); break; case Type.Circular: lerpValue = Circular.InOut(lerpValue); break; case Type.Elastic: lerpValue = Elastic.InOut(lerpValue); break; case Type.Back: lerpValue = Back.InOut(lerpValue); break; case Type.Bounce: lerpValue = Bounce.InOut(lerpValue); break; default: return(-1f); } return(lerpValue); }
public void InInverse_ChangedScaleInputBelowRange_ReturnsOrigin() { Vector scale = new Vector(4, 6); Ease ease = new Quadratic(scale); float y = -1.1f; float expected = 0; float actual = ease.InInverse(y); Assert.AreEqual(expected, actual, 0.001f); }
public static void SolutionReal(Quadratic eq) { if (eq.Discriminant < 0) { return; } Console.WriteLine(eq.ToString() + " дискриминант = " + eq.Discriminant); Console.WriteLine("\tКорни: Х1={0,3:g3} \tX2={1,3:g3}", eq.X1, eq.X2); }
public void Out_ChangedScaleInputAboveRange_ReturnsDestination() { Vector scale = new Vector(4, 6); Ease ease = new Quadratic(scale); float x = 11.1f; float expected = ease.Scale.Y; float actual = ease.Out(x); Assert.AreEqual(expected, actual, 0.001f); }
public IQuadraticEquation MakeSubject(double value) { Quadratic output = new Quadratic(this); //No adjustment for X, this is intrinsic output.Result /= value; output.A /= value; output.B /= value; output.C /= value; return(output); }
public void InOut_ChangedScaleInputInRange2_ReturnsExpectedValue() { Vector scale = new Vector(4, 6); Ease ease = new Quadratic(scale); float x = 1.5f; float expected = 1.688f; float actual = ease.InOut(x); Assert.AreEqual(expected, actual, 0.001f); }
public void InInverse_ChangedScaleInputInRange_ReturnsExpectedValue() { Vector scale = new Vector(4, 6); Ease ease = new Quadratic(scale); float y = 2.5f; float expected = 2.582f; float actual = ease.InInverse(y); Assert.AreEqual(expected, actual, 0.001f); }
public void InOutInverse_ChangedScaleInputAboveRange_ReturnsDestination() { Vector scale = new Vector(4, 6); Ease ease = new Quadratic(scale); float y = 6.1f; float expected = ease.Scale.X; float actual = ease.InOutInverse(y); Assert.AreEqual(expected, actual, 0.001f); }
void Test(double a, double b, double c, double[] expectedResult) { var result = Quadratic.Solve(a, b, c); // Assert Assert.AreEqual(expectedResult.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.AreEqual(expectedResult[i], result[i]); } }
[Test] public void FromPoints() { var a = new v2(0.5f, 0.3f); var b = new v2(0.7f, -0.2f); var c = new v2(1.0f, 0.6f); var q = Quadratic.FromPoints(a, b, c); Assert.Equal(q.F(a.x), a.y, Math_.TinyF); Assert.Equal(q.F(b.x), b.y, Math_.TinyF); Assert.Equal(q.F(c.x), c.y, Math_.TinyF); }
internal long XPRequired(int level, int tier) { if (level >= 10) { tier++; } else { level++; } return(Quadratic.F_longQuad(level * (tier + 1), 13, 0, 0)); }
static void Main(string[] args) { MyLog.Instance().Log("Начало программы."); float a = 0; float b = 0; float c = 0; while (true) { Console.WriteLine("Введите коэффициенты:"); try { a = float.Parse(Console.ReadLine()); b = float.Parse(Console.ReadLine()); c = float.Parse(Console.ReadLine()); break; } catch (Exception ex) { Console.WriteLine("Коэффициент введен неверно. Попробуйте еще раз\n"); MyLog.Instance().Log("Введен неверный коэффициент. Исключение: " + ex.Message); } } MyLog.Instance().Log("Введены коэффициенты: a = " + a.ToString() + ", b = " + b.ToString() + ", c = " + c.ToString()); Quadratic solver = new Quadratic(); try { List <float> roots = solver.Solve(a, b, c); string resultString = ""; foreach (float root in roots) { resultString += root.ToString() + " "; } MyLog.Instance().Log("Корни найдены. Результат: " + resultString); } catch (CerberException ex) { MyLog.Instance().Log("Ошибка: " + ex.Message); } MyLog.Instance().Write(); Console.ReadKey(); }
public void Negative() { // Arrange var a = 1; var b = 1; var c = 1; // Act var result = Quadratic.Solve(a, b, c); // Assert Assert.AreEqual(0, result.Length); }
public void TestMethod1() { // Arrange var a = 1; var b = -3; var c = 2; // Act var result = Quadratic.Solve(a, b, c); // Assert Assert.AreEqual(2, result.Length); Assert.AreEqual(2, result[0]); Assert.AreEqual(1, result[1]); }
public void ExpandReverseDistanceTest() { Quadratic kernel = new Quadratic(0); var x = new double[] { 0.5, 2.0 }; var y = new double[] { 1.3, -0.2 }; var phi_x = kernel.Transform(x); var phi_y = kernel.Transform(y); double d = Distance.SquareEuclidean(x, y); double phi_d = kernel.ReverseDistance(phi_x, phi_y); Assert.AreEqual(phi_d, d); }
static void Main(string[] args) { Console.WriteLine("Choose, what you want to do:"); Console.WriteLine("Multiply matrixes (type 1) or solve equation (type 2)"); string matrixOrEquation; do { Console.WriteLine("Make correct choice"); matrixOrEquation = Console.ReadLine(); } while (matrixOrEquation != "1" && matrixOrEquation != "2"); if (matrixOrEquation == "2") { Console.WriteLine("Choose, what equation you want to solve."); Console.WriteLine("For linear type 1, for quadratic type 2."); string type; string path = ResourceData.path; do { Console.WriteLine("Make correct choice"); type = Console.ReadLine(); } while (type != "1" && type != "2"); if (type == "1") { Linear linear = CreateLinear(path); linear.FindSolution(); Logger logger = new Logger(path); logger.Log(linear); } if (type == "2") { Quadratic quadratic = CreateQuadratic(path); quadratic.FindSolution(); Logger logger = new Logger(path); logger.Log(quadratic); } Console.WriteLine("Check log file. Press any key to exit."); } if (matrixOrEquation == "1") { string path = ConfigurationManager.AppSettings["pathToMatrix"]; Matrix matrix = readMatrix(path); matrix.MultiplyMatrix(); matrix.PrintMatrix(); Console.WriteLine("Press any key to exit."); } Console.ReadKey(); }
/// <summary>Trade entry signal based on MACD</summary> protected TradeType?SignalMACD() { // Look for minima or maxima in the short period average var macd = Bot.Indicators.MacdCrossOver(26, 12, 9); // Fit a quadratic to the MACD line (blue one) var poly = Quadratic.FromPoints( -2.0, macd.MACD.Last(2), -1.0, macd.MACD.Last(1), -0.0, macd.MACD.Last(0)); // If the quadratic predicts a peak it might be time to buy/sell. var peak_x = poly.StationaryPoints[0]; if (peak_x < -1.0 || peak_x > 0.0) { return(null); } var blue = macd.MACD.LastValue; var red = macd.Signal.LastValue; for (;;) { var minima = poly.ddF(peak_x) > 0; if (minima) // buy? { // MACD must be below the signal line if (blue > red) { break; } return(TradeType.Buy); } else // sell? { // MACD must be above the signal line if (blue < red) { break; } return(TradeType.Sell); } } return(null); }
internal void GainXP(long amount) { if (amount < 0 || essence.tier < Tier) { return; } long req = Quadratic.F_longQuad(level + 1, ReferenceData.xpToLvlAbility * (Tier + 1), 0, 0); while (xp >= req) { level++; xp -= req; req = Quadratic.F_longQuad(level + 1, ReferenceData.xpToLvlAbility * (Tier + 1), 0, 0); } }
private static MonotonicFunction SumQuadraticQuadratic(Quadratic a, Quadratic b) { if (a.QuadraticCoefficient + b.QuadraticCoefficient == 0f) { return(new Linear( a.LinearCoefficient + b.LinearCoefficient, a.ConstantCoefficient + b.ConstantCoefficient)); } else { return(new Quadratic( a.QuadraticCoefficient + b.QuadraticCoefficient, a.LinearCoefficient + b.LinearCoefficient, a.ConstantCoefficient + b.ConstantCoefficient)); } }
private void ChangeBackgroundColor() { if (widgetToHighlight != null) { double time = GetFadeInOutPulseRatio(timeSinceStart.Elapsed.TotalSeconds, pulseTime); double lightnessMultiplier = Quadratic.InOut(time); widgetToHighlight.BackgroundColor = startColor.AdjustLightness(1 + lightnessChange * lightnessMultiplier).ToColor(); if (widgetToHighlight.HasBeenClosed || timeSinceStart.Elapsed.TotalSeconds > cycles * pulseTime) { widgetToHighlight.BackgroundColor = startColor; widgetToHighlight.AfterDraw -= ConnectToWidget; RunningAttentions.Remove(widgetToHighlight); widgetToHighlight = null; return; } } }
private void setKernalType(KernelType k) { switch (k) { case KernelType.Linear: kernel = new Linear(); break; case KernelType.Quadratic: kernel = new Quadratic(); break; case KernelType.Sigmoid: kernel = new Sigmoid(); break; case KernelType.Spline: kernel = new Spline(); break; case KernelType.ChiSquared: kernel = new ChiSquare(); break; case KernelType.Gaussian: kernel = new Gaussian(); break; case KernelType.Multiquadric: kernel = new Multiquadric(); break; case KernelType.InverseMultquadric: kernel = new InverseMultiquadric(); break; case KernelType.Laplacian: kernel = new Laplacian(); break; default: break; } }
public static Quadratic CreateQuadratic(string path) { Quadratic q; Console.WriteLine("You chose quadratic equation (ax^2 + bx + c = 0)."); double tempA; string a; Console.WriteLine("Enter a"); a = Console.ReadLine(); while (!double.TryParse(a, out tempA)) { Console.WriteLine("Please enter valid a."); Logger logger = new Logger(path); logger.LogWrong(a, "-", "-"); a = Console.ReadLine(); } double tempB; string b; Console.WriteLine("Enter b"); b = Console.ReadLine(); while (!double.TryParse(b, out tempB)) { Console.WriteLine("Please enter valid b."); Logger logger = new Logger(path); logger.LogWrong(a, b, "-"); b = Console.ReadLine(); } double tempC; string c; Console.WriteLine("Enter c"); c = Console.ReadLine(); while (!double.TryParse(c, out tempC)) { Console.WriteLine("Please enter valid c."); Logger logger = new Logger(path); logger.LogWrong(a, b, c); c = Console.ReadLine(); } q = new Quadratic(tempA, tempB, tempC); return(q); }
public SolvedQuadratic(Quadratic quadratic, QuadraticSolutions solutions) { _quadratic = quadratic; _solutions = solutions; }
private static QuadraticSolutions Solve(Quadratic quadratic) { var a = quadratic.A; var b = quadratic.B; var c = quadratic.C; var imaginary = false; var discriminant = ((b * b) - (4 * a * c)); if (discriminant < 0) { discriminant = -discriminant; imaginary = true; } var tmp = Math.Sqrt(discriminant); var solutionOne = (-b + tmp) / (2 * a); var solutionTwo = (-b - tmp) / (2 * a); return new QuadraticSolutions(solutionOne, solutionTwo, imaginary); }
// Use this for initialization public virtual void Start() { Time.timeScale = 1; parabolaXYCoef = new Quadratic(); parabolaZYCoef = new Quadratic(); velocity = Vector3.zero; dest = transform.position; }
private void ProcessReceivedQuadratic(Quadratic quadratic) { var solutions = Solve(quadratic); var solvedQuadratic = new SolvedQuadratic(quadratic, solutions); _solvedChannel.Publish(solvedQuadratic); }