// TODO: Add ITorqueProvider and thrust effect on torque
 public override float GetPitchInput(Conditions conditions, float AoA, bool dryTorque = false, float guess = float.NaN)
 {
     BrentSearch solver = new BrentSearch((input) => this.GetAeroTorque(conditions, AoA, (float)input, dryTorque).x, -0.3, 0.3, 0.0001);
     if (solver.FindRoot())
         return (float)solver.Solution;
     solver.LowerBound = -1;
     solver.UpperBound = 1;
     if (solver.FindRoot())
         return (float)solver.Solution;
     if (this.GetAeroTorque(conditions, AoA, 0, dryTorque).x > 0)
         return -1;
     else
         return 1;
 }
Esempio n. 2
0
        /// <summary>
        ///   Computes recommended sample size for the test to attain
        ///   the power indicated in <see cref="Power"/> considering
        ///   values of <see cref="Effect"/> and <see cref="Size"/>.
        /// </summary>
        ///
        /// <returns>Recommended sample size for attaining the given
        /// <see cref="Power"/> for size effect <see cref="Effect"/>
        /// under the given <see cref="Size"/>.</returns>
        ///
        public virtual void ComputeSamples()
        {
            double requiredPower = Power;

            // Attempt to locate the optimal sample size
            // to attain the required power by locating
            // a zero in the difference function:

            double sol = BrentSearch.FindRoot(n =>
            {
                Samples = n;
                ComputePower();

                return(requiredPower - Power);
            },

                                              lowerBound: 2,
                                              upperBound: 1e+4);


            // Check it
            Samples = sol;
            ComputePower();

            double newPower = Power;

            Power = requiredPower;

            if (Math.Abs(requiredPower - newPower) > 1e-5)
            {
                Samples = Double.NaN;
            }
        }
Esempio n. 3
0
        public void ConstructorTest()
        {
            #region doc_example
            // Suppose we were given the function x³ + 2x² - 10x and
            // we have to find its root, maximum and minimum inside
            // the interval [-4,3]. First, we express this function
            // as a lambda expression:
            Func <double, double> function = x => x * x * x + 2 * x * x - 10 * x;

            // And now we can create the search algorithm:
            BrentSearch search = new BrentSearch(function, -4, 3);

            // Finally, we can query the information we need
            bool   success1 = search.Maximize(); // should be true
            double max      = search.Solution;   // occurs at -2.61

            bool   success2 = search.Minimize(); // should be true
            double min      = search.Solution;   // occurs at  1.27

            bool   success3 = search.FindRoot(); // should be true
            double root     = search.Solution;   // occurs at  0.50
            #endregion

            Assert.IsTrue(success1);
            Assert.IsTrue(success2);
            Assert.IsTrue(success3);
            Assert.AreEqual(-2.6103173042172645, max);
            Assert.AreEqual(1.2769840667540548, min);
            Assert.AreEqual(-0.5, root);
        }
Esempio n. 4
0
        public void ConstructorTest()
        {
            #region doc_example
            // Suppose we were given the function x³ + 2x² - 10x + 1 and
            // we have to find its root, maximum and minimum inside
            // the interval [-4, 2]. First, we express this function
            // as a lambda expression:
            Func <double, double> function = x => x * x * x + 2 * x * x - 10 * x + 1;

            // And now we can create the search algorithm:
            BrentSearch search = new BrentSearch(function, -4, 2);

            // Finally, we can query the information we need
            bool   success1 = search.Maximize(); // should be true
            double max      = search.Solution;   // occurs at -2.61

            bool   success2 = search.Minimize(); // should be true
            double min      = search.Solution;   // occurs at  1.28

            bool   success3 = search.FindRoot(); // should be true
            double root     = search.Solution;   // occurs at  0.10
            double value    = search.Value;      // should be zero
            #endregion

            Assert.IsTrue(success1);
            Assert.IsTrue(success2);
            Assert.IsTrue(success3);
            Assert.AreEqual(-2.6103173073566239, max);
            Assert.AreEqual(1.2769839857480398, min);
            Assert.AreEqual(0.10219566016872624, root);
            Assert.AreEqual(0, value, 1e-5);
        }
        public void OnData(Futures data1)
        {
            if (Time.Year == 2006)
            {
                System.Diagnostics.Debugger.Break();
            }

            if (data1.Symbol == symbols[0])
            {
                prices.Push1(data1.Open);
            }

            if (data1.Symbol == symbols[1])
            {
                prices.Push2(data1.Open);
            }

            if (prices.QLength1 == numBars && prices.QLength2 == numBars)
            {
                mult  = BrentSearch.FindRoot(prices.multFunc, -2, 2, 1e-8);
                resid = prices.Open1 - (mult * prices.Open2);

                if (Portfolio[symbols[0]].IsLong && resid > 0)
                {
                    Order(symbols[0], -1);
                    Order(symbols[1], 1);
                    //Debug(data1.Time.ToString()+" Resid: "+resid.ToString()+" Close BuySell-Open1: "+prices.Open1.ToString()+" Open2: "+prices.Open2.ToString());
                }

                if (Portfolio[symbols[0]].IsShort && resid < 0)
                {
                    Order(symbols[0], 1);
                    Order(symbols[1], -1);
                    //Debug(data1.Time.ToString()+" Resid: "+resid.ToString()+" Close SellBuy-Open1: "+prices.Open1.ToString()+" Open2: "+prices.Open2.ToString());
                }

                if (!Portfolio[symbols[0]].HoldStock && !Portfolio[symbols[1]].HoldStock)
                {
                    if (resid > cLevel)
                    {
                        //int tradeSize = (int)(Portfolio.Cash / balRisk);
                        Order(symbols[0], -1);
                        Order(symbols[1], 1);
                        //Debug(data1.Time.ToString()+" Resid: "+resid.ToString()+" SellBuy-Open1: "+prices.Open1.ToString()+" Open2: "+prices.Open2.ToString());
                    }

                    if (resid < -cLevel)
                    {
                        //int tradeSize = (int)(Portfolio.Cash / balRisk);
                        Order(symbols[0], 1);
                        Order(symbols[1], -1);
                        //Debug(data1.Time.ToString()+" Resid: "+resid.ToString()+" BuySell-Open1: "+prices.Open1.ToString()+" Open2: "+prices.Open2.ToString());
                    }
                }
            }
        }
Esempio n. 6
0
        public void FindRootWithLowMaxIterationsThrowsConvergenceException()
        {
            Func <double, double> f = x => (x + 2) * (x - 2);
            double a = -1;
            double b = +3000;

            Assert.ThrowsException <ConvergenceException>(() =>
            {
                double actual = BrentSearch.FindRoot(f, a, b, maxIterations: 5);
            });
        }
Esempio n. 7
0
        public void FindRootBoundedTwiceThrowsConvergenceException()
        {
            Func <double, double> f = x => (x + 2) * (x - 2);
            double a = -3;
            double b = +3;

            Assert.ThrowsException <ConvergenceException>(() =>
            {
                double actual = BrentSearch.FindRoot(f, a, b);
            });
        }
Esempio n. 8
0
        public void FindRootBoundedTwiceFailsToSolve()
        {
            Func <double, double> f = x => (x + 2) * (x - 2);
            double a = -3;
            double b = +3;

            var search    = new BrentSearch(f, a, b);
            var isSuccess = search.FindRoot();

            Assert.AreEqual(false, isSuccess);
            Assert.AreEqual(BrentSearchStatus.RootNotBracketed, search.Status);
        }
Esempio n. 9
0
        /// <summary>
        /// Get the minimum value that we can add to hit the target
        /// </summary>
        /// <param name="targetValue">
        /// The target we would like to hit
        /// </param>
        /// <returns>
        /// The difference between the initial value and what we need to add/remove to hit the target
        /// </returns>
        public decimal GetGoalSeekValue(decimal targetValue)
        {
            this.iterations = 0;
            var startTime = DateTime.Now;

            this.target = targetValue;
            var startValue = this.GetStartValue();
            var result     = (decimal)BrentSearch.FindRoot(this.TestTree, (double)startValue, (double)targetValue, 1);

            this.timeSpan = DateTime.Now - startTime;

            return(result);
        }
Esempio n. 10
0
        public void FindRootTest()
        {
            //  Example from http://en.wikipedia.org/wiki/Brent%27s_method

            Func <double, double> f = x => (x + 3) * Math.Pow((x - 1), 2);
            double a = -4;
            double b = 4 / 3.0;

            double expected = -3;
            double actual   = BrentSearch.FindRoot(f, a, b);

            Assert.AreEqual(expected, actual, 1e-6);
            Assert.IsFalse(Double.IsNaN(actual));
        }
Esempio n. 11
0
        public void FindRootWithLowMaxIterationsFailsToSolveButGivesLastKnownSolution()
        {
            Func <double, double> f = x => (x + 2) * (x - 2);
            double a = -1;
            double b = +3000;

            var search    = new BrentSearch(f, a, b, maxIterations: 5);
            var isSuccess = search.FindRoot();

            Assert.AreEqual(false, isSuccess);
            Assert.AreEqual(BrentSearchStatus.MaxIterationsReached, search.Status);

            Assert.IsTrue(search.Solution > a && search.Solution < b);
        }
Esempio n. 12
0
        /// <summary>
        /// Should solve
        /// </summary>
        /// <param name="c"></param>
        /// <param name="t0"></param>
        /// <param name="distance"></param>
        /// <returns></returns>
        public static double PointAtDistanceFrom(this ICurve c, double t0, double distance)
        {
            Func <double, double> objFunc = t1 =>
            {
                var length3 = t0 < t1?c.GetLength3(t0, t1) : c.GetLength3(t1, t0);

                return(length3 - Math.Abs(distance));
            };
            var domain = c.Domain();
            var min    = distance < 0.0 ? 0.8 * domain[0] : t0;
            var max    = distance < 0.0 ? t0 : 1.2 * domain[1];
            var solver = new BrentSearch(objFunc, min, max);

            solver.FindRoot();
            var sol = solver.Solution;

            return(sol);
        }
Esempio n. 13
0
        public void FindRootTest()
        {
            //  Example from http://en.wikipedia.org/wiki/Brent%27s_method

            Func <double, double> f = x => (x + 3) * Math.Pow((x - 1), 2);
            double a = -4;
            double b = 4 / 3.0;

            double expected = -3;
            double actual   = BrentSearch.FindRoot(f, a, b);

            Assert.AreEqual(expected, actual, 1e-6);
            Assert.IsFalse(Double.IsNaN(actual));

            var  search    = new BrentSearch(f, a, b);
            bool isSuccess = search.FindRoot();

            Assert.IsTrue(isSuccess);
            Assert.AreEqual(BrentSearchStatus.Success, search.Status);
            Assert.AreEqual(expected, search.Solution, 1e-6);
            Assert.IsTrue(Math.Abs(search.Value) < 1e-5);
        }
Esempio n. 14
0
 public FuncionLogLogistica(double[] eventos) : base(eventos)
 {
     try
     {
         double[] eventosOrdenados = eventos.OrderBy(x => x).ToArray();
         double   alfa             = eventos.Count() % 2 == 0 ? (eventosOrdenados.ElementAt(eventos.Count() / 2) + eventosOrdenados.ElementAt((eventos.Count() / 2) + 1)) / 2 : eventos.OrderBy(x => x).ElementAt((eventos.Count() / 2) + 1);
         this.A = alfa.ToString("0.0000");
         double media = eventos.Average();
         int    n     = eventos.Count();
         double sigma = eventos.Sum(x => Math.Pow(x - media, 2)) / n;
         double k     = Math.Sqrt(Math.Pow(sigma, 2) / (Math.Pow(sigma, 2) + Math.Pow(media, 2)));
         Func <double, double> function = x => Math.Sqrt(1 - (x / Math.Tan(x))) - k;
         BrentSearch           search   = new BrentSearch(function, (Math.PI / 2) * k, Math.Sqrt(3) * k);
         search.FindRoot();
         double beta = Math.PI / search.Solution;
         this.B = beta.ToString("0.0000");
         DistribucionContinua = new LogLogisticDistribution(alfa, beta);
         Resultado            = new ResultadoAjuste(StringFDP, StringInversa, DistribucionContinua.StandardDeviation, DistribucionContinua.Mean, DistribucionContinua.Variance, this);
     }
     catch (Exception)
     {
         Resultado = null;
     }
 }
Esempio n. 15
0
 public LogLogistics(double[] events)
 {
     try
     {
         double[] eventosOrdenados = events.OrderBy(x => x).ToArray();
         double   alfa             = events.Count() % 2 == 0 ? (eventosOrdenados.ElementAt(events.Count() / 2) + eventosOrdenados.ElementAt((events.Count() / 2) + 1)) / 2 : events.OrderBy(x => x).ElementAt((events.Count() / 2) + 1);
         this.A = alfa.ToString("0.0000");
         double media = events.Average();
         int    n     = events.Count();
         double sigma = events.Sum(x => Math.Pow(x - media, 2)) / n;
         double k     = Math.Sqrt(Math.Pow(sigma, 2) / (Math.Pow(sigma, 2) + Math.Pow(media, 2)));
         Func <double, double> function = x => Math.Sqrt(1 - (x / Math.Tan(x))) - k;
         BrentSearch           search   = new BrentSearch(function, (Math.PI / 2) * k, Math.Sqrt(3) * k);
         search.FindRoot();
         double beta = Math.PI / search.Solution;
         this.B = beta.ToString("0.0000");
         this.continuousDistribution = new LogLogisticDistribution(alfa, beta);
         this.result = this.result = new DistributionResult(this.FDP, this.Inverse, this.continuousDistribution.StandardDeviation, this.continuousDistribution.Mean, this.continuousDistribution.Variance, this);
     }
     catch (Exception e)
     {
         Console.WriteLine("Excepcion en clase " + this.GetType().ToString() + e.Message);
     }
 }