コード例 #1
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);
        }
コード例 #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;
            }
        }
コード例 #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);
        }
コード例 #4
0
        public virtual float GetMinAoA(Conditions conditions, float guess = float.NaN)
        {
            BrentSearch minimizer = new BrentSearch((aoa) => GetLiftForceMagnitude(conditions, (float)aoa, 1), -60 * Mathf.Deg2Rad, -10 * Mathf.Deg2Rad, 0.0001);

            if (float.IsNaN(guess) || float.IsInfinity(guess))
            {
                minimizer.Maximize();
            }
            else
            {
                minimizer.LowerBound = guess - 2 * Mathf.Deg2Rad;
                minimizer.UpperBound = guess + 2 * Mathf.Deg2Rad;
                if (!minimizer.Maximize())
                {
                    minimizer.LowerBound = guess - 5 * Mathf.Deg2Rad;
                    minimizer.UpperBound = guess + 5 * Mathf.Deg2Rad;
                    if (!minimizer.Maximize())
                    {
                        minimizer.LowerBound = Mathf.Clamp(guess - 10 * Mathf.Deg2Rad, -90 * Mathf.Deg2Rad, -60 * Mathf.Deg2Rad);
                        minimizer.UpperBound = Mathf.Max(-10 * Mathf.Deg2Rad, guess + 10 * Mathf.Deg2Rad);
                        minimizer.Maximize();
                    }
                }
            }
            return((float)minimizer.Solution);
        }
コード例 #5
0
        public virtual float GetMaxAoA(Conditions conditions, out float lift, float guess = float.NaN)
        {
            BrentSearch maximizer = new BrentSearch((aoa) => GetLiftForceMagnitude(conditions, (float)aoa, 1), 10 * Mathf.Deg2Rad, 60 * Mathf.Deg2Rad, 0.0001);

            if (float.IsNaN(guess) || float.IsInfinity(guess))
            {
                maximizer.Maximize();
            }
            else
            {
                maximizer.LowerBound = guess - 2 * Mathf.Deg2Rad;
                maximizer.UpperBound = guess + 2 * Mathf.Deg2Rad;
                if (!maximizer.Maximize())
                {
                    maximizer.LowerBound = guess - 5 * Mathf.Deg2Rad;
                    maximizer.UpperBound = guess + 5 * Mathf.Deg2Rad;
                    if (!maximizer.Maximize())
                    {
                        maximizer.LowerBound = Mathf.Min(10 * Mathf.Deg2Rad, guess - 10 * Mathf.Deg2Rad);
                        maximizer.UpperBound = Mathf.Clamp(guess + 10 * Mathf.Deg2Rad, 60 * Mathf.Deg2Rad, 90 * Mathf.Deg2Rad);
                        maximizer.Maximize();
                    }
                }
            }
            lift = (float)maximizer.Value;
            return((float)maximizer.Solution);
        }
コード例 #6
0
        public void MinimizeTest()
        {
            Func <double, double> f = x => 2 * x * x - 3 * x + 5;

            double expected = 3 / 4.0;
            double actual   = BrentSearch.Minimize(f, -200, +200);

            Assert.AreEqual(expected, actual, 1e-10);
        }
コード例 #7
0
        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());
                    }
                }
            }
        }
コード例 #8
0
        /// <summary>
        ///   Gets the inverse of the cumulative distribution function (icdf) for
        ///   this distribution evaluated at probability <c>p</c>. This function
        ///   is also known as the Quantile function.
        /// </summary>
        ///
        /// <param name="p">A probability value between 0 and 1.</param>
        ///
        /// <returns>
        ///   A sample which could original the given probability
        ///   value when applied in the <see cref="UnivariateContinuousDistribution.DistributionFunction(double)"/>.
        /// </returns>
        ///
        protected internal override double InnerInverseDistributionFunction(double p)
        {
            if (this.exact)
            {
                if (n1 > n2)
                {
                    Trace.TraceWarning("Warning: Using a MannWhitneyDistribution where the first sample is larger than the second.");
                    double lower = 0;
                    double upper = 0;

                    double f = DistributionFunction(0);

                    if (f > p)
                    {
                        while (f > p && !double.IsInfinity(lower))
                        {
                            lower = upper;
                            upper = 2 * upper + 1;
                            f     = DistributionFunction(upper);
                        }
                    }
                    else if (f < p)
                    {
                        while (f < p && !double.IsInfinity(upper))
                        {
                            upper = lower;
                            lower = 2 * lower - 1;
                            f     = DistributionFunction(lower);
                        }
                    }
                    else
                    {
                        return(0);
                    }

                    if (double.IsNegativeInfinity(lower))
                    {
                        lower = double.MinValue;
                    }

                    if (double.IsPositiveInfinity(upper))
                    {
                        upper = double.MaxValue;
                    }

                    double value = BrentSearch.Find(DistributionFunction, p, lower, upper);

                    return(value);
                }

                return(base.InnerInverseDistributionFunction(p));
            }

            return(approximation.InverseDistributionFunction(p));
        }
コード例 #9
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);
            });
        }
コード例 #10
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);
            });
        }
コード例 #11
0
        public void MaximizeWithLowMaxIterationsThrowsConvergenceException()
        {
            Func <double, double> f = x => - 2 * x * x - 3 * x + 5;
            double a = -200;
            double b = +200;

            Assert.ThrowsException <ConvergenceException>(() =>
            {
                double actual = BrentSearch.Maximize(f, a, b, maxIterations: 10);
            });
        }
コード例 #12
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);
        }
コード例 #13
0
        /// <summary>
        ///   Gets the cumulative distribution function (cdf) for
        ///   this distribution evaluated at point <c>x</c>.
        /// </summary>
        ///
        /// <param name="x">A single point in the distribution range.</param>
        ///
        public override double DistributionFunction(double x)
        {
            if (x < Support.Min)
            {
                return(0);
            }
            if (x > Support.Max)
            {
                return(1);
            }

            return(BrentSearch.Find(InverseDistributionFunction, x, 0, 1, 1e-10));
        }
コード例 #14
0
ファイル: GoalSeek.cs プロジェクト: ICodeGorilla/CalcFlow
        /// <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);
        }
コード例 #15
0
        public void MaximizeWithLowMaxIterationsFailsToSolveButGivesLastKnownSolution()
        {
            Func <double, double> f = x => - 2 * x * x - 3 * x + 5;
            double a = -200;
            double b = +200;

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

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

            Assert.IsTrue(search.Solution > a && search.Solution < b);
        }
コード例 #16
0
 // 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;
 }
コード例 #17
0
ファイル: SimplePerceptron.cs プロジェクト: 2021SIA/TP3
        private double optimizing(
            Vector <double> w,
            Vector <double>[] input,
            double[] desiredTrainingOutput,
            int batch,
            int[] rand)
        {
            Func <double, double> function = x => loop(w, input, desiredTrainingOutput, batch, x, rand);
            BrentSearch           search   = new BrentSearch(function, 0, 1);
            bool   success = search.Minimize();
            double min     = search.Solution;

            return(min);
        }
コード例 #18
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));
        }
コード例 #19
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);
        }
コード例 #20
0
        public static PointParamWithRayProjection ClosestPointToRay(this ICurve curve, PointDirection3 ray, double tol = 1e-9)
        {
            var bound       = curve.Domain();
            int numOfRadius = 0;

            double[]  radius   = null;
            MathPoint location = null;

            var radiusResult       = curve.FindMinimumRadius();
            var domain             = new RangeDouble(curve.Domain());
            var tessTol            = radiusResult.Radius / 10;
            var closestPointOnEdge = Vector3.Zero;

            for (var i = 0; i < 1; i++)
            {
                var tessPoints = Sequences
                                 .LinSpace(domain.Min, domain.Max, 100)
                                 .Select(curve.PointParamAt).ToList();
                var edges = tessPoints.Buffer(2, 1).Where(buf => buf.Count == 2)
                            .ToList();

                var closestEdge
                    = edges
                      .Select(edge => new { edge, connection = MakeEdge(edge).ShortestEdgeJoining(ray, tol) })
                      .MinBy(o => o.connection.LengthSquared)[0];

                var a = closestEdge.edge[0].T;
                var b = closestEdge.edge[1].T;
                domain  = new RangeDouble(a, b);
                tessTol = tessTol / 10;
            }

            Func <Vector3, Vector3> projectOnRay = p => (p - ray.Point).ProjectOn(ray.Direction) + ray.Point;

            var solver = new BrentSearch(t =>
            {
                var p    = curve.PointAt(t);
                var proj = projectOnRay(p);
                return((p - proj).LengthSquared());
            }, domain.Min, domain.Max);

            solver.Minimize();
            var minT = solver.Solution;

            var pointParam = curve.PointParamAt(minT);

            return(new PointParamWithRayProjection(pointParam, projectOnRay(pointParam.Point)));
        }
コード例 #21
0
        public void CreateSearchWithParametersSetPropertiesSetsCorrectly()
        {
            Func <double, double> f = x => 2 * x + 4;

            double lowerBound    = -3;
            double upperBound    = +5;
            double tolerance     = 1e-9;
            int    maxIterations = 20;

            BrentSearch sut = new BrentSearch(f, lowerBound, upperBound, tolerance, maxIterations);

            Assert.AreSame(f, sut.Function);
            Assert.AreEqual(lowerBound, sut.LowerBound);
            Assert.AreEqual(upperBound, sut.UpperBound);
            Assert.AreEqual(tolerance, sut.Tolerance);
            Assert.AreEqual(maxIterations, sut.MaxIterations);
        }
コード例 #22
0
        public void MinimizeTest()
        {
            Func <double, double> f = x => 2 * x * x - 3 * x + 5;

            double expected = 3 / 4d;
            double actual   = BrentSearch.Minimize(f, -200, +200);

            Assert.AreEqual(expected, actual, 1e-10);


            var  search    = new BrentSearch(f, -200, 200);
            bool isSuccess = search.Minimize();

            Assert.IsTrue(isSuccess);
            Assert.AreEqual(BrentSearchStatus.Success, search.Status);
            Assert.AreEqual(expected, search.Solution, 1e-10);
            Assert.AreEqual(f(expected), search.Value, double.Epsilon);
        }
コード例 #23
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);
        }
コード例 #24
0
        protected float GetAoA(Conditions conditions, float offsettingForce, bool useThrust = true, bool dryTorque = false, float guess = float.NaN, float pitchInputGuess = float.NaN, bool lockPitchInput = false, float tolerance = 0.0001f)
        {
            if (lockPitchInput && (float.IsNaN(pitchInputGuess) || float.IsInfinity(pitchInputGuess)))
            {
                pitchInputGuess = 0;
            }
            Vector3     thrustForce = useThrust ? this.GetThrustForce(conditions) : Vector3.zero;
            BrentSearch solver;

            if (lockPitchInput)
            {
                solver = new BrentSearch((aoa) => GetLiftForceMagnitude(this.GetLiftForce(conditions, (float)aoa, pitchInputGuess) + thrustForce, (float)aoa) - offsettingForce,
                                         -10 * Mathf.Deg2Rad, 35 * Mathf.Deg2Rad, 0.0001);
            }
            else
            {
                solver = new BrentSearch((aoa) => GetLiftForceMagnitude(this.GetLiftForce(conditions, (float)aoa, GetPitchInput(conditions, (float)aoa, dryTorque, pitchInputGuess)) + thrustForce, (float)aoa)
                                         - offsettingForce, -10 * Mathf.Deg2Rad, 35 * Mathf.Deg2Rad, 0.0001);
            }

            if (float.IsNaN(guess) || float.IsInfinity(guess))
            {
                solver.FindRoot();
            }
            else
            {
                solver.LowerBound = guess - 2 * Mathf.Deg2Rad;
                solver.UpperBound = guess + 2 * Mathf.Deg2Rad;
                if (!solver.FindRoot())
                {
                    solver.LowerBound = guess - 5 * Mathf.Deg2Rad;
                    solver.UpperBound = guess + 5 * Mathf.Deg2Rad;
                    if (!solver.FindRoot())
                    {
                        solver.LowerBound = Mathf.Min(-10 * Mathf.Deg2Rad, guess - 10 * Mathf.Deg2Rad);
                        solver.UpperBound = Mathf.Max(35 * Mathf.Deg2Rad, guess + 10 * Mathf.Deg2Rad);
                        solver.FindRoot();
                    }
                }
            }

            return((float)solver.Solution);
        }
コード例 #25
0
ファイル: MultiLayerPerceptron.cs プロジェクト: 2021SIA/TP3
        private double optimizing(Vector <double>[] input,
                                  Vector <double>[] V,
                                  Matrix <double>[] w,
                                  int M,
                                  Vector <double>[] h,
                                  Vector <double>[] delta,
                                  Vector <double>[] trainingOutput,
                                  Matrix <double>[] deltaW,
                                  int batch,
                                  double error,
                                  int[] rand)
        {
            Func <double, double> function = x => loop(input, V, M, h, delta, trainingOutput, deltaW, batch, error, x, rand, w);
            BrentSearch           search   = new BrentSearch(function, 0, 1);
            bool   success = search.Minimize();
            double min     = search.Solution;

            return(min);
        }
コード例 #26
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:
            var search = new BrentSearch(n =>
            {
                Samples = n;
                ComputePower();

                return(Power);
            },

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

            Samples = search.Find(requiredPower) ? search.Solution : double.NaN;
            Power   = requiredPower;
        }
コード例 #27
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);
        }
コード例 #28
0
        public static EdgeDistance ClosestDistanceBetweenTwoCurves(IMathUtility m, ICurve curve0, ICurve curve1)
        {
            var curveDomain = curve1.Domain();

            var solver = new BrentSearch
                             (t =>
            {
                var pt = curve1.PointAt(t);
                return((curve0.ClosestPointOn(pt).Point - pt).Length());
            }
                             , curveDomain[0]
                             , curveDomain[1]
                             );

            solver.Minimize();
            var param = solver.Solution;

            var pt1  = curve1.PointAt(param);
            var pt0  = curve0.ClosestPointOn(pt1).Point;
            var edge = new Edge3(pt1, pt0);

            return(new EdgeDistance(edge, solver.Value));
        }
コード例 #29
0
        public void FindTest()
        {
            //  Example from http://en.wikipedia.org/wiki/Brent%27s_method
            double value = 10;

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

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

            Assert.AreEqual(expected, actual, 1e-6);
            Assert.AreEqual(value, f(actual), 1e-5);

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

            Assert.IsTrue(isSuccess);
            Assert.AreEqual(BrentSearchStatus.Success, search.Status);
            Assert.AreEqual(expected, search.Solution, 1e-6);
            Assert.AreEqual(value, search.Value, 1e-5);
        }
コード例 #30
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;
     }
 }