コード例 #1
0
    Rate CreditDefaultSwap::impliedHazardRate(
                               Real targetNPV,
                               const Handle<YieldTermStructure>& discountCurve,
                               const DayCounter& dayCounter,
                               Real recoveryRate,
                               Real accuracy) const {

        boost::shared_ptr<SimpleQuote> flatRate(new SimpleQuote(0.0));

        Handle<DefaultProbabilityTermStructure> probability(
            boost::shared_ptr<DefaultProbabilityTermStructure>(new
                FlatHazardRate(0, WeekendsOnly(),
                               Handle<Quote>(flatRate), dayCounter)));

        MidPointCdsEngine engine(probability, recoveryRate, discountCurve);
        setupArguments(engine.getArguments());
        const CreditDefaultSwap::results* results =
            dynamic_cast<const CreditDefaultSwap::results*>(
                                                       engine.getResults());

        ObjectiveFunction f(targetNPV, *flatRate, engine, results);
        Rate guess = 0.001;
        Rate step = guess*0.1;

        return Brent().solve(f, accuracy, guess, step);
    }
コード例 #2
0
/**
@param hmass The mass enthalpy in J/kg
@param p The pressure in Pa
@returns T The temperature in K
*/
long double IncompressibleBackend::HmassP_flash(long double hmass, long double p){

	class HmassP_residual : public FuncWrapper1D {
	protected:
		double p,x,h_in;
		IncompressibleFluid* fluid;
	protected:
        HmassP_residual(){};
	public:
		HmassP_residual(IncompressibleFluid* fluid, const double &p,  const double &x, const double &h_in){
			this->p = p;
			this->x = x;
			this->h_in = h_in;
			this->fluid = fluid;
		}
		virtual ~HmassP_residual(){};
		double call(double target){
			return fluid->h(target,p,x) - h_in; //fluid.u(target,p,x)+ p / fluid.rho(target,p,x) - h_in;
		}
		//double deriv(double target);
	};

	//double T_tmp = this->PUmass_flash(p, hmass); // guess value from u=h

	HmassP_residual res = HmassP_residual(fluid, p, _fractions[0], hmass);

	std::string errstring;
	double macheps = DBL_EPSILON;
	double tol     = DBL_EPSILON*1e3;
	int    maxiter = 10;
	double result = Brent(&res, fluid->getTmin(), fluid->getTmax(), macheps, tol, maxiter, errstring);
	//if (this->do_debug()) std::cout << "Brent solver message: " << errstring << std::endl;
	return result;
}
コード例 #3
0
ファイル: GlfLikelihoods.cpp プロジェクト: amarawi/gotcloud
double GenotypeLikelihood::OptimizeFrequency()
   {
   a = 0.00001; fa = f(a);
   b = 0.4; fb = f(b);
   c = 0.99999; fc = f(c);

   Brent(0.0001);

   return min;
    }
コード例 #4
0
    Real AnalyticPDFHestonEngine::Pv(Real x_t, Time t) const {
        const Hestonp p = { model_->v0(),
                            model_->kappa(),
                            model_->theta(),
                            model_->sigma(),
                            model_->rho() };
        Real xMax = (xMax_ != Null<Real>()) ? xMax_
            : Brent().solve(boost::bind(&zero_pv, p, _1, x_t, t),
                            0.01, 1.0, 1.0);

        return GaussLobattoIntegral(nIterations_, 0.1*eps_)
               (boost::bind(&pv, p, _1, x_t, t), -xMax, xMax)/M_TWOPI;
    }
コード例 #5
0
    Real RichardsonExtrapolation::operator()(Real t, Real s)
    const {
        QL_REQUIRE(t > 1 && s > 1, "scaling factors must be greater than 1");
        QL_REQUIRE(t > s, "t must be greater than s");

        const Real ft = f_(delta_h_/t);
        const Real fs = f_(delta_h_/s);

        const Real k = Brent().solve(RichardsonEqn(fdelta_h_, ft, fs, t, s),
                                     1e-8, 0.05, 10);

        const Real ts = std::pow(s, k);

        return (ts*fs-fdelta_h_)/(ts-1.0);
    }
コード例 #6
0
    void GaussianRandomDefaultModel::nextSequence(Real tmax) {
        const std::vector<Real>& values = rsg_.nextSequence().value;
        Real a = sqrt(copula_->correlation());
        for (Size j = 0; j < pool_->size(); j++) {
            const string name = pool_->names()[j];
            const Handle<DefaultProbabilityTermStructure>&
                dts = pool_->get(name).defaultProbability(defaultKeys_[j]);

            Real y = a * values[0] + sqrt(1-a*a) * values[j+1];
            Real p = CumulativeNormalDistribution()(y);

            if (dts->defaultProbability(tmax) < p)
                pool_->setTime(name, tmax+1);
            else
                pool_->setTime(name, Brent().solve(Root(dts,p),accuracy_,0,1));
        }
    }
コード例 #7
0
void Efficiency(int k, int N, double conflevel,
      double& mode, double& low, double& high) 
      {
           //If there are no entries, then we know nothing, thus return the prior...
           if (0==N) {
                mode = .5; low = 0.0; high = 1.0; 
                return;
           }

           // Calculate the most probable value for the posterior cross section.
           // This is easy, 'cause it is just k/N

           double efficiency = (double)k/N;

           double low_edge;
           double high_edge;

           if (k == 0) {
                
                low_edge = 0.0;
                high_edge = SearchUpper(low_edge, k, N, conflevel);
           }
           else if (k == N){
                
                high_edge = 1.0;
                low_edge = SearchLower(high_edge, k, N, conflevel);
           }
           else {
                GLOBAL_k = k;
                GLOBAL_N = N;
                CONFLEVEL = conflevel;            
                Brent(0.0, 0.5, 1.0, 1.0e-9, &low_edge);
                high_edge = low_edge + Interval(low_edge);
           }

           // return output
           mode = efficiency;
           low = low_edge;
           high = high_edge;
      }//Efficiency
コード例 #8
0
ファイル: convolvedstudentt.cpp プロジェクト: 21hub/QuantLib
 Real InverseCumulativeBehrensFisher::operator()(const Probability q) const {
     Probability effectiveq;
     Real sign;
     // since the distrib is symmetric solve only on the right side:
     if(q==0.5) {
         return 0.;
     }else if(q < 0.5) {
         sign = -1.;
         effectiveq = 1.-q;
     }else{
         sign = 1.;
         effectiveq = q;
     }
     Real xMin =
         InverseCumulativeNormal::standard_value(effectiveq) * normSqr_;
     // inversion will fail at the Brent's bounds-check if this is not enough
     // (q is very close to 1.), in a bad combination fails around 1.-1.e-7
     Real xMax = 1.e6;
     return sign *
         Brent().solve(boost::bind(std::bind2nd(std::minus<Real>(),
         effectiveq), boost::bind(
             &CumulativeBehrensFisher::operator(),
             distrib_, _1)), accuracy_, (xMin+xMax)/2., xMin, xMax);
 }
コード例 #9
0
void ErrorRateEstimator::EstimateModel()
   {
   trace = false;

   printf("   Assuming per %s error model\n", alleleError ? "allele" : "genotype");

   a = 0.00001;
   fa = f(a);

   printf("      lnLikelihood at lower bound (%.3g) is %.3f\n", a, -fa);

   c = 0.10;
   fc = f(c);

   printf("      lnLikelihood at upper bound (%.3g) is %.3f\n", c, -fc);

   b = (c - a) * 0.4;
   fb = f(b);

   trace = !MerlinCore::quietOutput;
   Brent(0.00001);

   printf("      lnLikelihood at MLE (%.3g) is %.3f           \n", min, -fmin);
   }
コード例 #10
0
ファイル: andy.cpp プロジェクト: dylancarlson/citplus
void cdecl TERMWINDOWMEMBER Andy(const char *Format, const char *Codes, ...)
	{
	char *Vals[32], collect[512];
	const char *Code;
	int n, CodeCount, colCount;
	va_list ap;

	va_start(ap, Codes);

	for (n = 0, CodeCount = strlen(Codes); n < CodeCount && n < 32; ++n)
		{
		Vals[n] = va_arg(ap, char *);
		}

	va_end(ap);

	for (colCount = 0; *Format != '\0'; ++Format)
		{
		if (*Format != '%')
			{
			if (!Brent(&Format, &colCount, collect))
				{
				break;
				}
			continue;
			}

		if (*(++Format) == '\0')
			{
			break;
			}

		if (*Format == '%')
			{
			collect[colCount++] = *Format;
			continue;
			}

		// not stuff
		if (*Format == '[')
			{
			// Scan for close and include-location.
			for (Code = Format; *Code != 0 && *Code != ']'; ++Code);

			if (*Code == '\0')
				{
				break;
				}

			if ((n = strpos(*(Code + 1), Codes)) != 0)
				{
				if (Vals[n - 1][0] == '\0')
					{
					for (++Format; Format < Code; ++Format)
						{
						if (!Brent(&Format, &colCount, collect))
							{
							break;
							}
						}

					if (*Format)
						{
						Format++;
						}
					}
				else
					{
					Format = Code + 1;
					}
				}

			continue;
			}

		if (*Format != '{')
			{
			if ((n = strpos(*Format, Codes)) != 0)
				{
				if (colCount)
					{
					collect[colCount] = 0;
					mFormat(collect);
					colCount = 0;
					}

				mFormat(Vals[n - 1]);
				}

			continue;
			}

		// Scan for close and include-location.
		const char *Include = NULL;
		for (Code = Format; *Code != 0 && *Code != '}'; ++Code)
			{
			if (*Code == '&')
				{
				Include = Code;
				}
			}

		if (*Code == '\0')
			{
			break;
			}

		if (Include == NULL)
			{
			if ((n = strpos(*(Code + 1), Codes)) != 0)
				{
				if (Vals[n - 1][0] != '\0')
					{
					if (colCount)
						{
						collect[colCount] = 0;
						mFormat(collect);
						colCount = 0;
						}

					for (++Format; Format < Code; ++Format)
						{
						if (!Brent(&Format, &colCount, collect))
							{
							break;
							}
						}

					if (*Format)
						{
						Format++;
						}
					}
				else
					{
					Format = Code + 1;
					}
				}
			}
		else
			{
			if ((n = strpos(*(Code + 1), Codes)) != 0)
				{
				if (Vals[n - 1][0] != '\0')
					{
					if (colCount)
						{
						collect[colCount] = 0;
						mFormat(collect);
						colCount = 0;
						}

					for (++Format; Format < Include; ++Format)
						{
						if (!Brent(&Format, &colCount, collect))
							{
							break;
							}
						}

					if (colCount)
						{
						collect[colCount] = 0;
						mFormat(collect);
						colCount = 0;
						}

					mFormat(Vals[n - 1]);

					for (++Format; Format < Code; ++Format)
						{
						if (!Brent(&Format, &colCount, collect))
							{
							break;
							}
						}

					if (*Format)
						{
						Format++;
						}
					}
				else
					{
					Format = Code + 1;
					}
				}
			}
		}

	if (colCount)
		{
		collect[colCount] = 0;
		mFormat(collect);
		}
	}
コード例 #11
0
    void RandomLossLM<C, URNG>::nextSample(
        const std::vector<Real>& values) const 
    {
        const ext::shared_ptr<Pool>& pool = this->basket_->pool();
        this->simsBuffer_.push_back(std::vector<defaultSimEvent> ());

        // half the model is defaults, the other half are RRs...
        for(Size iName=0; iName<copula_->size()/2; iName++) {
            // ...but samples must be full
            /* This is really a trick, we are passing a longer than
            expected set of values in the sample but the last idiosyncratic
            values corresponding to the RR are not used. They are used below
            only if we are in default. This works due to the way the SpotLossLM
            is split in two almost disjoint latent models and that theres no
            check on the vector size in the LM base class.
            */
            Real latentVarSample = 
                copula_->latentVarValue(values, iName);
            Probability simDefaultProb = 
                copula_->cumulativeY(latentVarSample, iName);
            // If the default simulated lies before the max date:
            if (horizonDefaultPs_[iName] >= simDefaultProb) {
                const Handle<DefaultProbabilityTermStructure>& dfts = 
                    pool->get(pool->names()[iName]).  // use 'live' names
                    defaultProbability(this->basket_->defaultKeys()[iName]);
                // compute and store default time with respect to the 
                //  curve ref date:
                Size dateSTride =
                    static_cast<Size>(Brent().solve(// casted from Real:
                    detail::Root(dfts, simDefaultProb), accuracy_, 0., 1.));
                /*
                // value if one approximates to a flat HR; 
                //   faster (>x2) but it introduces an error:..
                // \todo: see how to include this 'polymorphically'. While
                //   not the case in pricing in risk metrics/real  
                //   probabilities the curves are often flat
                static_cast<Size>(ceil(maxHorizon_ * 
                                    std::log(1.-simDefaultProb)
                /std::log(1.-data_.horizonDefaultPs_[iName])));
                */
                // Determine the realized recovery rate:
                /* For this; 'conditionalRecovery' needs to compute the pdef on 
                the realized def event date from the simulation. Yet, this might
                have fallen between todays date and the default TS reference 
                date(usually a two day gap) To avoid requesting a negative time
                probability the date is moved to the TS date 
                Unless the gap is ridiculous this has no practical effect for 
                the RR value*/
                Date today = Settings::instance().evaluationDate();
                Date eventDate = today+Period(static_cast<Integer>(dateSTride), 
                    Days);
                if(eventDate<dfts->referenceDate()) 
                    eventDate = dfts->referenceDate();
                Real latentRRVarSample = 
                    copula_->latentRRVarValue(values, iName);
                Real recovery = 
                    copula_->conditionalRecovery(latentRRVarSample,
                        iName, eventDate);
                this->simsBuffer_.back().push_back(
                  defaultSimEvent(iName, dateSTride, recovery));
                //emplace_back
            }
        /* Used to remove sims with no events. Uses less memory, faster 
        post-statistics. But only if all names in the portfolio have low 
        default probability, otherwise is more expensive and sim access has 
        to be modified. However low probability is also an indicator that 
        variance reduction is needed. */
        //if(simsBuffer.back().empty()) {
        //    emptySims_++;// Size; intilzd to zero
        //    simsBuffer.pop_back();
        //}
        }
    }