public EventModuleView()
        {
            InitializeComponent();
            this.currentBrentPriceLabel    = new Label();
            this.crudeOilBrentPriceLabel   = new Label();
            this.crudeOilBrentPriceTextBox = new TextBox();
            this.updatePriceButtton        = new Button();
            this.brent = new Brent();

            brent.CrudeOilBrentPrice = 86;
            brent.BrentPriceChanged += brent_PriceChanged;

            currentBrentPriceLabel.Location = new Point(80, 24);
            currentBrentPriceLabel.Size     = new Size(120, 24);
            currentBrentPriceLabel.Text     = "Current Price: " + brent.CrudeOilBrentPrice.ToString();

            crudeOilBrentPriceLabel.Location = new Point(24, 50);
            crudeOilBrentPriceLabel.Size     = new Size(80, 24);
            crudeOilBrentPriceLabel.Text     = "Brent Price";

            crudeOilBrentPriceTextBox.Location = new Point(120, 50);
            crudeOilBrentPriceTextBox.Size     = new Size(80, 24);

            updatePriceButtton.Location = new Point(50, 80);
            updatePriceButtton.Size     = new Size(120, 40);
            updatePriceButtton.Text     = "Update Crude Oil Price";
            updatePriceButtton.Click   += new EventHandler(updatePriceButtton_Click);

            this.Controls.Add(currentBrentPriceLabel);
            this.Controls.Add(crudeOilBrentPriceLabel);
            this.Controls.Add(crudeOilBrentPriceTextBox);
            this.Controls.Add(updatePriceButtton);
        }
Exemple #2
0
        private VoltageLimitCurve buildVoltageLimitCurve(int count = 50, double Imax = 55, double Umax = 140, double max_speed = 6000)
        {
            var mtpa = buildTableMaxtorquePerAmple();

            VoltageLimitCurve vlc = new VoltageLimitCurve()
            {
                Imax     = Imax,
                Umax     = Umax,
                MaxSpeed = max_speed,
            };

            for (int i = 0; i < count + 1; i++)
            {
                double t   = mtpa.GetMaxTorqueWithCurrentMagnitude(i * Imax / count);
                var    idq = mtpa.GetCurrentForTorque(t);

                // look for speed, that is suitable for given current (in max torque condition) and u=Umax
                double ss      = 0;
                bool   success = Brent.TryFindRoot(s =>
                {
                    var data_ = calculatePointdata(idq.d, idq.q, s);
                    var u_    = Math.Sqrt(data_.ud * data_.ud + data_.uq * data_.uq);
                    return(u_ - Umax);
                }, 100, max_speed, 1e-3, 100, out ss);

                if (success)
                {
                    vlc.speeds.Add(ss);
                    vlc.torques.Add(t);
                    vlc.currents.Add(idq);
                }
            }

            return(vlc);
        }
Exemple #3
0
        public void Oneeq3()
        {
            // Test case from http://www.polymath-software.com/library/nle/Oneeq3.htm
            Func <double, double> f1 = T => Math.Exp(21000 / T) / (T * T) - 1.11e11;

            Assert.AreEqual(551.773822885233, Brent.FindRoot(f1, 550, 560, 1e-2), 1e-2);
        }
Exemple #4
0
        /// <summary>
        /// Computes the inverse of the cumulative distribution function (InvCDF) for the distribution
        /// at the given probability. This is also known as the quantile or percent point function.
        /// </summary>
        /// <param name="p">The location at which to compute the inverse cumulative density.</param>
        /// <param name="location">The location (μ) of the distribution.</param>
        /// <param name="scale">The scale (σ) of the distribution. Range: σ > 0.</param>
        /// <param name="freedom">The degrees of freedom (ν) for the distribution. Range: ν > 0.</param>
        /// <returns>the inverse cumulative density at <paramref name="p"/>.</returns>
        /// <seealso cref="InverseCumulativeDistribution"/>
        /// <remarks>WARNING: currently not an explicit implementation, hence slow and unreliable.</remarks>
        public static double InvCDF(double location, double scale, double freedom, double p)
        {
            if (scale <= 0.0 || freedom <= 0.0)
            {
                throw new ArgumentException(Resources.InvalidDistributionParameters);
            }

            // TODO JVG we can probably do a better job for Cauchy special case
            if (double.IsPositiveInfinity(freedom))
            {
                return(Normal.InvCDF(location, scale, p));
            }

            if (p == 0.5d)
            {
                return(location);
            }

            // TODO PERF: We must implement this explicitly instead of solving for CDF^-1
            return(Brent.FindRoot(x =>
            {
                var k = (x - location) / scale;
                var h = freedom / (freedom + (k * k));
                var ib = 0.5 * SpecialFunctions.BetaRegularized(freedom / 2.0, 0.5, h);
                return x <= location ? ib - p : 1.0 - ib - p;
            }, -800, 800, accuracy: 1e-12));
        }
Exemple #5
0
        public static double inv_m1_beta_black_cxv(double beta, double f, double sigma)
        {
            var s2  = sigma * sigma;
            var igb = inv_g(beta, f);
            var fac = -0.5 * s2;
            var rf  = FS.fun((double cxv) =>
            {
                var mu = igb + fac * cxv;
                var f0 = m1_beta_black(beta, mu, sigma);
                return(f - f0);
            });

            var alpha = 0.5 * beta * s2;
            var guess = alpha == 0.0 ? 1.0 : Math.Min(1.0, Math.Max(0.0, (f + alpha) / alpha));
            var lo    = guess - 1e-3;
            var hi    = guess + 1e-3;

            var tGuess = rf(alpha);

            if (DoubleUtils.ApproximatelyEqual(tGuess, 0.0, 100.0 * DoubleUtils.DoubleEpsilon))
            {
                return(igb + fac * alpha);
            }

            NumericalRecipes.zbrac(rf, ref lo, ref hi);
            var cxvRoot = Brent.FindRoot(rf, lo, hi);

            return(igb + fac * cxvRoot);
        }
Exemple #6
0
        /// <summary>
        /// Calculates the throughput at which the expected time to FC the given movements =
        /// timeThresholdBase + time span of the movements
        /// </summary>
        private static double calculateFCTimeTP(IEnumerable <OsuMovement> movements)
        {
            if (movements.Count() == 0)
            {
                return(0);
            }

            double mapLength     = movements.Last().Time - movements.First().Time;
            double timeThreshold = timeThresholdBase + mapLength;

            double maxFCTime = calculateFCTime(movements, tpMin);

            if (maxFCTime <= timeThreshold)
            {
                return(tpMin);
            }

            double minFCTime = calculateFCTime(movements, tpMax);

            if (minFCTime >= timeThreshold)
            {
                return(tpMax);
            }

            double fcTimeMinusThreshold(double tp) => calculateFCTime(movements, tp) - timeThreshold;

            return(Brent.FindRoot(fcTimeMinusThreshold, tpMin, tpMax, tpPrecision));
        }
Exemple #7
0
        /// <summary>
        ///     Creates a new <see cref="NonLinearRankFitnessFunction{TProgram}" /> with the given parameters.
        /// </summary>
        /// <param name="programComparer">The object used to compare programs and determine their ranking.</param>
        /// <param name="population">The list of programs whose fitness can be computed by this function.</param>
        /// <param name="selectivePressure">
        ///     The probability of the best individual being selected compared to the average probability of selection of all
        ///     individuals.
        /// </param>
        public NonLinearRankFitnessFunction(
            IComparer <TProgram> programComparer, IPopulation <TProgram> population, double selectivePressure)
            : base(programComparer, population)
        {
            var n = population.Count;

            this.SelectivePressure = Math.Max(1d, Math.Min(n - 2d, selectivePressure));

            // finds the root of the polynomial
            try
            {
                this._root      = Brent.FindRootExpand(this.Polynomial, -n, n, 1E-08, 1000);
                this._rootFound = true;
            }
            catch (NonConvergenceException)
            {
            }

            // stores the exponential sum
            this._rootFactor = 0d;
            var pow = 1d;

            for (var i = 0; i < n; i++)
            {
                this._rootFactor += pow;
                pow *= this._root;
            }

            this._rootFactor = n / this._rootFactor;
        }
Exemple #8
0
        public void Oneeq19b()
        {
            // Test case from http://www.polymath-software.com/library/nle/Oneeq19b.htm
            Func <double, double> f1 = z =>
            {
                const double P    = 200;
                const double Pc   = 33.5;
                const double T    = 631;
                const double Tc   = 126.2;
                const double Pr   = P / Pc;
                const double Tr   = T / Tc;
                double       Asqr = 0.4278 * Pr / Math.Pow(Tr, 2.5);
                const double B    = 0.0867 * Pr / Tr;
                double       Q    = B * B + B - Asqr;
                double       r    = Asqr * B;
                double       p    = (-3 * Q - 1) / 3;
                double       q    = (-27 * r - 9 * Q - 2) / 27;
                double       R    = Math.Pow(p / 3, 3) + Math.Pow(q / 2, 2);
                double       V    = (R > 0) ? Math.Pow(-q / 2 + Math.Sqrt(R), 1 / 3) : 0;
                double       WW   = (R > 0) ? (-q / 2 - Math.Sqrt(R)) : (0);
                double       psi1 = (R < 0) ? (Math.Acos(Math.Sqrt((q * q / 4) / (-p * p * p / 27)))) : (0);
                double       W    = (R > 0) ? (Math.Sign(WW) * Math.Pow(Math.Abs(WW), 1 / 3)) : (0);
                double       z1   = (R < 0) ? (2 * Math.Sqrt(-p / 3) * Math.Cos((psi1 / 3) + 2 * 3.1416 * 0 / 3) + 1 / 3) : (0);
                double       z2   = (R < 0) ? (2 * Math.Sqrt(-p / 3) * Math.Cos((psi1 / 3) + 2 * 3.1416 * 1 / 3) + 1 / 3) : (0);
                double       z3   = (R < 0) ? (2 * Math.Sqrt(-p / 3) * Math.Cos((psi1 / 3) + 2 * 3.1416 * 2 / 3) + 1 / 3) : (0);
                double       z0   = (R > 0) ? (V + W + 1 / 3) : (0);

                return(z * z * z - z * z - Q * z - r);
            };

            double x = Brent.FindRoot(f1, -0.5, 1.2, 1e-14);

            Assert.AreEqual(1.06831213384200, x, 1e-7);
            Assert.AreEqual(0, f1(x), 1e-14);
        }
Exemple #9
0
        public void Oneeq2a()
        {
            // Test case from http://www.polymath-software.com/library/nle/Oneeq2a.htm
            Func <double, double> f1 = T =>
            {
                const double x1     = 0.332112;
                const double x2     = 1 - x1;
                const double G12    = 0.07858889;
                const double G21    = 0.30175355;
                double       P2     = Math.Pow(10, 6.87776 - 1171.53 / (224.366 + T));
                double       P1     = Math.Pow(10, 8.04494 - 1554.3 / (222.65 + T));
                double       t1     = x1 + x2 * G12;
                double       t2     = x2 + x1 * G21;
                double       gamma2 = Math.Exp(-Math.Log(t2) - (x1 * (G12 * t2 - G21 * t1)) / (t1 * t2));
                double       gamma1 = Math.Exp(-Math.Log(t1) + (x2 * (G12 * t2 - G21 * t1)) / (t1 * t2));
                double       k1     = gamma1 * P1 / 760;
                double       k2     = gamma2 * P2 / 760;
                return(1 - k1 * x1 - k2 * x2);
            };

            double x = Brent.FindRoot(f1, 0, 100, 1e-14, 100);

            Assert.AreEqual(58.7000023925600, x, 1e-5);
            Assert.AreEqual(0, f1(x), 1e-14);
        }
Exemple #10
0
        public void Oneeq7()
        {
            // Test case from http://www.polymath-software.com/library/nle/Oneeq7.htm
            Func <double, double> f1 = x => x / (1 - x) - 5 * Math.Log(0.4 * (1 - x) / (0.4 - 0.5 * x)) + 4.45977;

            Assert.AreEqual(0.757396293891, Brent.FindRoot(f1, 0, 0.79, 1e-2), 1e-2);
        }
Exemple #11
0
        public void LocalMinima()
        {
            Func <double, double> f1 = x => x * x * x - 2 * x + 2;

            Assert.AreEqual(0, f1(Brent.FindRoot(f1, -5, 5, 1e-14, 100)), 1e-14);
            Assert.AreEqual(0, f1(Brent.FindRoot(f1, -2, 4, 1e-14, 100)), 1e-14);
        }
Exemple #12
0
        public void Oneeq16()
        {
            // Test case from http://www.polymath-software.com/library/nle/Oneeq16.htm
            Func <double, double> f1 = T =>
            {
                const double y     = 0.7;
                const double x     = 1.7;
                const double z     = 1 - y - 0.02;
                const double CH4   = 0;
                const double C2H6  = 0;
                const double COtwo = y + 2 * z;
                const double H2O   = 2 * y + 3 * z;
                const double N2    = 0.02 + 3.76 * (2 * y + 7 * z / 2) * x;
                const double O2    = (2 * y + 7 * z / 2) * (x - 1);
                const double alp   = 3.381 * CH4 + 2.247 * C2H6 + 6.214 * COtwo + 7.256 * H2O + 6.524 * N2 + 6.148 * O2;
                const double bet   = 18.044 * CH4 + 38.201 * C2H6 + 10.396 * COtwo + 2.298 * H2O + 1.25 * N2 + 3.102 * O2;
                const double gam   = -4.3 * CH4 - 11.049 * C2H6 - 3.545 * COtwo + 0.283 * H2O - 0.001 * N2 - 0.923 * O2;
                const double H0    = alp * 298 + bet * 0.001 * 298 * 298 / 2 + gam * 1e-6 * 298 * 298 * 298 / 3;
                double       Hf    = alp * T + bet * 0.001 * T * T / 2 + gam * 1e-6 * T * T * T / 3;
                double       xx    = 1;

                return(212798 * y * xx + 372820 * z * xx + H0 - Hf);
            };

            double r = Brent.FindRoot(f1, 1000, 3000);

            Assert.AreEqual(1779.48406483697, r, 1e-5);
            Assert.AreEqual(0, f1(r), 1e-9);
        }
Exemple #13
0
        public static bool TryFindRoot(Func <double, double> function, double lowerBound, double upperBound, out double root, double accuracy = 1e-6, int maxIterations = 100)
        {
            try
            {
                double lowerBoundValue = function(lowerBound);
                if (lowerBoundValue == 0.0 && lowerBoundValue == function(upperBound))
                {
                    // For our usage, we don't want to consider a constant function at zero to have any roots.
                    root = lowerBound;
                    return(false);
                }

                if (Brent.TryFindRoot(function, lowerBound, upperBound, accuracy: accuracy, maxIterations: maxIterations, root: out root))
                {
                    return(true);
                }

                return(Bisection.TryFindRoot(function, lowerBound, upperBound, accuracy: accuracy, maxIterations: maxIterations, root: out root));
            }
            catch (ArithmeticException)
            {
                root = double.NaN;
                return(false);
            }
        }
Exemple #14
0
        public void Oneeq6b()
        {
            // Test case from http://www.polymath-software.com/library/nle/Oneeq6b.htm
            Func <double, double> f1 = V =>
            {
                const double R     = 0.08205;
                const double T     = 273.0;
                const double B0    = 0.05587;
                const double A0    = 2.2769;
                const double C     = 128300.0;
                const double A     = 0.01855;
                const double B     = -0.01587;
                const double P     = 100.0;
                const double Beta  = R * T * B0 - A0 - R * C / (T * T);
                const double Gama  = -R * T * B0 * B + A0 * A - R * C * B0 / (T * T);
                const double Delta = R * B0 * B * C / (T * T);

                return(R * T * V * V * V + Beta * V * V + Gama * V + Delta - P * V * V * V * V);
            };

            double x = Brent.FindRoot(f1, 0.1, 1, 1e-14);

            Assert.AreEqual(0.174749600398905, x, 1e-5);
            Assert.AreEqual(0, f1(x), 1e-13);
        }
Exemple #15
0
        /// <summary>
        /// Bootstraps the specified priceable assets.
        /// </summary>
        /// <param name="priceableAssets">The priceable assets.</param>
        /// <param name="baseDate">The base date.</param>
        /// <param name="extrapolationPermitted">The extrapolationPermitted flag.</param>
        /// <param name="interpolationMethod">The interpolationMethod.</param>
        /// <param name="tolerance">Solver tolerance to use.</param>
        /// <returns></returns>
        public static TermPoint[] Bootstrap(IEnumerable <IPriceableRateAssetController> priceableAssets,
                                            DateTime baseDate, Boolean extrapolationPermitted,
                                            InterpolationMethod interpolationMethod, Double tolerance)
        {
            const double defaultGuess = 0.9;
            const double min          = 0.000000001;
            const double max          = 2;
            //only works for linear on zero.
            InterpolationMethod interp = InterpolationMethodHelper.Parse("LogLinearInterpolation");
            //  Add the first element (date : discount factor) to the list
            var points = new Dictionary <DateTime, double> {
                { baseDate, 1d }
            };
            var items
                = new Dictionary <DateTime, Pair <string, decimal> > {
                { baseDate, new Pair <string, decimal>("", 1m) }
                };
            var  solver = new Brent();
            bool first  = true;

            // Add the rest
            foreach (IPriceableRateAssetController priceableAsset in priceableAssets)
            {
                DateTime assetMaturityDate = priceableAsset.GetRiskMaturityDate();
                if (points.Keys.Contains(assetMaturityDate))
                {
                    continue;
                }
                if (assetMaturityDate < points.Keys.Last())
                {
                    throw new InvalidOperationException("The maturity dates of the assets must be consecutive order");
                }
                if (first)
                {
                    first = false;
                    // Add the first point
                    points.Add(assetMaturityDate, defaultGuess);
                    var curve = new SimpleDiscountFactorCurve(baseDate, interp, extrapolationPermitted, points);
                    points[assetMaturityDate] = (double)priceableAsset.CalculateDiscountFactorAtMaturity(curve);
                }
                else
                {
                    //This now should automatically extrapolate the required discount factor on a flat rate basis.
                    var curve = new SimpleDiscountFactorCurve(baseDate, interp, extrapolationPermitted, points);
                    //The first guess, which should be correct for all priceable assets with analytical solutions that have been implemented.
                    points.Add(assetMaturityDate, (double)priceableAsset.CalculateDiscountFactorAtMaturity(curve));
                }
                var objectiveFunction = new RateAssetQuote(priceableAsset, baseDate, interpolationMethod,
                                                           extrapolationPermitted, points, tolerance);
                // Check whether the guess was close enough
                if (!objectiveFunction.InitialValue())
                {
                    double guess = Math.Max(min, points[assetMaturityDate]);
                    points[assetMaturityDate] = solver.Solve(objectiveFunction, tolerance, guess, min, max);
                }
                items.Add(assetMaturityDate, new Pair <string, decimal>(priceableAsset.Id, (decimal)points[assetMaturityDate]));
            }
            return(TermPointsFactory.Create(items));
        }
Exemple #16
0
        public static double BlackScholesImpliedVol(this EuropeanOption option, Date valueDate, double spot, double rate, double div, double price)
        {
            Func <double, double> option_price = x => BlackScholesPrice(option, valueDate, spot, x, rate, div) - price;

            double impliedvol = Brent.FindRoot(option_price, 1e-4, 1000, 1e-8, 1000);

            return(impliedvol);
        }
Exemple #17
0
        ///<summary>
        ///</summary>
        ///<param name="maturityDate">redemption date</param>
        ///<param name="lastCouponDate">last coupon date</param>
        ///<param name="couponRate">coupon rate</param>
        ///<param name="couponFrequency">coupons per year,1 for annual, 2 for semi, 4 for quarterly</param>
        ///<param name="faceValue">The face value of the bond.</param>
        ///<param name="dirtyPrice">dirty price</param>
        ///<returns></returns>
        public static double CalculateBondYTM(DateTime maturityDate, DateTime lastCouponDate, double couponRate, int couponFrequency, double faceValue, double dirtyPrice)
        {
            var c = new CalculateBondYTMObjectiveFunctionClass(maturityDate, lastCouponDate, couponRate, couponFrequency, faceValue, dirtyPrice);
            // Instantiate and initialise the equation solver.
            var solver = new Brent();

            return(solver.Solve(c, .0000001, couponRate, 0.01));
        }
Exemple #18
0
        public static double InvCDF(double a, double b, double p)
        {
            //if (a < 0.0 || b < 0.0 || p < 0.0 || p > 1.0) {
            //    throw new ArgumentException(Resources.InvalidDistributionParameters);
            //}

            return(Brent.FindRoot(x => SpecialFunctions.BetaRegularized(a, b, x) - p, 0.0, 1.0, accuracy: 1e-12));
        }
Exemple #19
0
        /// <summary>
        /// Find first miss count achievable with at least probability p
        /// </summary>
        private static double getMissCount(double p, double[] missProbabilities)
        {
            var distribution = new PoissonBinomial(missProbabilities);

            Func <double, double> cdfMinusProb = missCount => distribution.Cdf(missCount) - p;

            return(Brent.FindRootExpand(cdfMinusProb, -100, 1000));
        }
Exemple #20
0
        public void Oneeq7()
        {
            // Test case from http://www.polymath-software.com/library/nle/Oneeq7.htm
            // not solvable with this method
            Func <double, double> f1 = x => x / (1 - x) - 5 * Math.Log(0.4 * (1 - x) / (0.4 - 0.5 * x)) + 4.45977;

            Assert.Throws <NonConvergenceException>(() => Brent.FindRoot(f1, 0, 0.79, 1e-2));
        }
Exemple #21
0
        public void Oneeq3()
        {
            // Test case from http://www.polymath-software.com/library/nle/Oneeq3.htm
            // not solvable with this method
            Func <double, double> f1 = T => Math.Exp(21000 / T) / (T * T) - 1.11e11;

            Assert.Throws <NonConvergenceException>(() => Brent.FindRoot(f1, 550, 560, 1e-2));
        }
Exemple #22
0
        /// <summary>
        /// Bootstraps the specified priceable assets.
        /// </summary>
        /// <param name="priceableAssets">The priceable assets.</param>
        /// <param name="baseDate">The base date.</param>
        /// <param name="extrapolationPermitted">The extrapolationPermitted flag.</param>
        /// <param name="interpolationMethod">The interpolationMethod.</param>
        /// <param name="tolerance">Solver tolerance to use.</param>
        /// <returns></returns>
        public static TermPoint[] Bootstrap(List <IPriceableFxAssetController> priceableAssets,
                                            DateTime baseDate, Boolean extrapolationPermitted,
                                            InterpolationMethod interpolationMethod, Double tolerance)
        {
            const Double        solveRateGap     = 0.015d;//should we need more precising perhaps???
            const Decimal       dfamMinThreshold = 0.0m;
            const Decimal       defaultGuess     = 0.9m;
            const Double        accuracy         = 0.000001d;
            InterpolationMethod interp           = InterpolationMethodHelper.Parse("LinearInterpolation"); //only works for linear on zero.

            priceableAssets = priceableAssets.OrderBy(a => a.GetRiskMaturityDate()).ToList();
            var  dates           = new List <DateTime>();
            var  discountFactors = new List <double>();
            var  items           = new Dictionary <DateTime, Pair <string, decimal> >();
            bool firstTime       = true;

            foreach (var asset in priceableAssets)
            {
                DateTime assetMaturityDate = asset.GetRiskMaturityDate();
                //check if the maturity date is already in the list. If not contimue.
                if (items.ContainsKey(assetMaturityDate))
                {
                    continue;
                }
                decimal guess = asset.ForwardAtMaturity > dfamMinThreshold ? asset.ForwardAtMaturity : defaultGuess;
                decimal dfam;
                if (firstTime)
                {
                    firstTime = false;
                    dates.Add(assetMaturityDate);
                    discountFactors.Add(Convert.ToDouble(guess));
                    dfam = asset.CalculateImpliedQuote(new SimpleFxCurve(baseDate, interp, extrapolationPermitted, dates, discountFactors));
                    discountFactors[0] = (double)dfam;
                }
                else
                {
                    //The first guess, which should be correct for all priceable assets with analytical solutions that have been implemented.
                    //So far this is only wrt Depos and Futures...This now should automatically extrapolate the required discount factor on a flat rate basis.
                    dfam = asset.CalculateImpliedQuote(new SimpleFxCurve(baseDate, interp, extrapolationPermitted, dates, discountFactors));
                    discountFactors.Add((double)dfam);
                    dates.Add(assetMaturityDate);
                }
                //Add a check on the dfam so that the solver is only called if outside the tolerance.
                var objectiveFunction = new FxAssetQuote(asset, baseDate, interpolationMethod,
                                                         extrapolationPermitted, dates, discountFactors, tolerance);
                if (!objectiveFunction.InitialValue())
                {
                    var timeInterval  = Actual365.Instance.YearFraction(baseDate, assetMaturityDate);
                    var solveInterval = Math.Exp(-solveRateGap * timeInterval);
                    var min           = Math.Max(0, (double)dfam * solveInterval);
                    var max           = (double)dfam / solveInterval;
                    var solver        = new Brent();
                    dfam = (decimal)solver.Solve(objectiveFunction, accuracy, (double)dfam, min, max);
                }
                items.Add(assetMaturityDate, new Pair <string, decimal>(asset.Id, dfam));
            }
            return(TermPointsFactory.Create(items));
        }
Exemple #23
0
        public void Oneeq1()
        {
            // Test case from http://www.polymath-software.com/library/nle/Oneeq1.htm
            Func <double, double> f1 = z => 8 * Math.Pow((4 - z) * z, 2) / (Math.Pow(6 - 3 * z, 2) * (2 - z)) - 0.186;
            double x = Brent.FindRoot(f1, 0.1, 0.9, 1e-14, 100);

            Assert.AreEqual(0.277759543089215, x, 1e-9);
            Assert.AreEqual(0, f1(x), 1e-16);
        }
Exemple #24
0
        public static double beta_black_break_even_to_sigma(double beta, double f, double t, double breakEven, double dt = 1.0 / 365.0)
        {
            var rf = FS.fun((double sigma) => beta_black_break_even(beta, f, t, sigma, dt) - breakEven);
            var x1 = 1.0;
            var x2 = 5.0;

            NumericalRecipes.zbrac(rf, ref x1, ref x2);
            return(Brent.FindRoot(rf, x1, x2));
        }
Exemple #25
0
        public static double yieldBrent(Brent solver, Bond bond, double cleanPrice, DayCounter dayCounter, Compounding compounding, Frequency frequency)
        {
            double ret = NQuantLibcPINVOKE.BondFunctions_yieldBrent__SWIG_3(Brent.getCPtr(solver), Bond.getCPtr(bond), cleanPrice, DayCounter.getCPtr(dayCounter), (int)compounding, (int)frequency);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Exemple #26
0
        public void Oneeq17()
        {
            // Test case from http://www.polymath-software.com/library/nle/Oneeq17.htm
            Func <double, double> f1 = rp => rp - 0.327 * Math.Pow(0.06 - 161 * rp, 0.804) * Math.Exp(-5230 / (1.987 * (373 + 1.84e6 * rp)));

            double x = Brent.FindRoot(f1, 0, 0.00035, 1e-13);

            Assert.AreEqual(0.000340568862275, x, 1e-5);
            Assert.AreEqual(0, f1(x), 2e-14);
        }
        public static double InvCDF(double d1, double d2, double p)
        {
            //if (d1 <= 0.0 || d2 <= 0.0) {
            //    throw new ArgumentException(Resources.InvalidDistributionParameters);
            //}

            return(Brent.FindRoot(
                       x => SpecialFunctions.BetaRegularized(d1 / 2.0, d2 / 2.0, d1 * x / (d1 * x + d2)) - p,
                       0, 1000, accuracy: 1e-12));
        }
Exemple #28
0
        public static double ibeta_black(double beta, OptionType optType, double F, double K, double T, double premium)
        {
            var rf = FS.fun((double sigma) => beta_black(beta, optType, F, K, T, sigma) - premium);

            var lo = 1.0;
            var hi = 5.0; // If very deep in-out of the money, will fail. f(lo) = f(hi), zbrac only moves low

            NumericalRecipes.zbrac(rf, ref lo, ref hi);
            return(Brent.FindRoot(rf, lo, hi));
        }
Exemple #29
0
    private static void test05()

    //****************************************************************************80
    //
    //  Purpose:
    //
    //    TEST05 tests CYCLE_BRENT for F5.
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    17 June 2012
    //
    //  Author:
    //
    //    John Burkardt
    //
    {
        int lam = 0;
        int mu  = 0;

        Console.WriteLine("");
        Console.WriteLine("TEST05");
        Console.WriteLine("  Test CYCLE_BRENT for F5().");
        Console.WriteLine("  f5(i) = mod ( 16383 * i + 1, 65536 ).");

        int x0 = 1;

        Console.WriteLine("");
        Console.WriteLine("  Starting argument X0 = " + x0 + "");

        Brent.cycle_brent(f5, x0, ref lam, ref mu);

        Console.WriteLine("");
        Console.WriteLine("  Reported cycle length is " + lam + "");
        Console.WriteLine("  Expected value is 8");
        Console.WriteLine("");
        Console.WriteLine("  Reported distance to first cycle element is " + mu + "");
        Console.WriteLine("  Expected value is 0");

        int i = 0;

        x0 = 1;
        Console.WriteLine("  " + i + "  " + x0 + "");
        for (i = 1; i <= 10; i++)
        {
            x0 = f5(x0);
            Console.WriteLine("  " + i + "  " + x0 + "");
        }
    }
Exemple #30
0
        public void Oneeq10()
        {
            // Test case from http://www.polymath-software.com/library/nle/Oneeq10.htm
            Func <double, double> f1 = x => (1.0 / 63.0) * Math.Log(x) + (64.0 / 63.0) * Math.Log(1 / (1 - x)) + Math.Log(0.95 - x) - Math.Log(0.9);

            double r = Brent.FindRoot(f1, .01, 0.35, 1e-14);

            Assert.AreEqual(0.036210083704, r, 1e-5);
            Assert.AreEqual(0, f1(r), 1e-14);
            r = Brent.FindRoot(f1, 0.35, 0.7);
            Assert.AreEqual(0.5, r, 1e-5);
            Assert.AreEqual(0, f1(r), 1e-14);
        }
Exemple #31
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Brent obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }