int CDFTools<T>::rank( const Vector<T>& x, const Matrix<T>& distributionSamples, const Vector<T>& xEvals, const Vector<T>& distributionAverage) const { const int numSamples = distributionSamples.getSize1(); Vector<T> maxDifferences( 1+numSamples ); Vector<T> maxDiffBuffer; Vector<T> ignored1, ignored2; T xMaxDiff; differences( x, cdf(x), xEvals, distributionAverage, maxDiffBuffer, ignored1, ignored2 ); xMaxDiff = maxDifferences[0] = maxDiffBuffer[1]; for (int i = 0; i < numSamples; ++i) { differences( distributionSamples[i], cdf(distributionSamples[i]), xEvals, distributionAverage, maxDiffBuffer, ignored1, ignored2 ); maxDifferences[i+1] = maxDiffBuffer[1]; } maxDifferences.sort(); int r = 0; while ( maxDifferences[r] != xMaxDiff ) { ++r; } return r; }
/* Returns an approximated upper bound for the base probability of an event given the number of events and the number of samples. The confidence probability is taken from the parameters. @param k number of positive events @param n number of samples @return upper bound for the base probability */ double binomialDistribution::upperBound(const int& k, const int& n) const { const parameters& param=getParameters(); double conf=param.confidence; double p=0.5; double l=0.; double h=1.0; double prob=cdf(k,p,n); double lastProb=0.; double acc=param.accuracy; //cout << param.accuracy << endl; while (fabs(conf-prob)>acc) { if (prob < conf) { h=p; p=0.5*(l+p); } else { l=p; p=0.5*(p+h); } lastProb=prob; prob=cdf(k,p,n); if (fabs(lastProb-prob)<(acc/1000)) { return 2.; } //cout << p << " " << prob << " " << fabs(conf-prob) << endl; } return p; }
static inline uint32_t ex4_sym2prob(double sym) { // sym -= .5; const long double fac = TOTALPROB - EX4_MAX_VALUE; #ifdef EX4_HISTOS double cd = 0; for(int i = EX4_MIN; i < sym; i++) cd+=ex4_histo[i]; // return (ld)TOTALPROB * cd / ex4_histo_sum; return EX4_MIN_PROB*(sym-EX4_MIN) + fac * cd / ex4_histo_sum; #elif !defined(EX4_GG) ld g = (1-EX4_BOX_MIX)*cdf(sym/gdevs[curBlock]); if (sym >= -EX4_BOX_RADIUS) { if (sym > EX4_BOX_RADIUS) g+=EX4_BOX_MIX; else g += EX4_BOX_BONUS*(sym+EX4_BOX_RADIUS); } return EX4_MIN_PROB*(sym-EX4_MIN) + fac * g; #else double alpha = alphas[curBlock], beta = betas[curBlock]; ld g = cdf(sym/EX4_GAUSS_VAR); double gg = gcdf(sym/alpha, beta); // printf("gg %Lf %Lf %f\n", sym/alpha, beta, gg); // assert(gg>=0); // printf("diff %f\n", sym-mid); double r = EX4_GAUSS_RATIO; return EX4_MIN_PROB*(sym-EX4_MIN) + fac * (r*g + (1-r)*gg); #endif }
int main() { int N = 10000000; double * b = new double[N]; double begin = current_time(); #if 1 for(int i = 0; i < N; i += BLK) { double a[BLK]; int idx[BLK]; for(int j = 0; j < BLK; j++) { a[j] = rand() / (double) 0xFFFFFFFF; idx[j] = rand() % 3; } for(int j = 0; j < BLK; j++) b[i+j] = cdf(a[j]) * sd[idx[j]] + means[idx[j]]; } #else for(int i = 0; i < N; i++) { double a = rand() / (double) 0xFFFFFFFF; size_t idx = rand() % 3; b[i] = cdf(a) * sd[idx] + means[idx]; } #endif printf("%f\n", b[0]); printf("Elapsed: %f\n", current_time()-begin); }
void NormalMeanPostFactor::mkFactor(matrix_t &m) const{ //Remember to convert to index space boost::math::normal dist( (postmean_-minv_)*bins_/(maxv_-minv_), std::sqrt(postvar_)*bins_/(maxv_-minv_) ); for(int i = 0; i < m.size2(); ++i){ m(0,i) = cdf(dist, i+1)-cdf(dist,i); } }
void EuropeanOptionBlack76::calculateInternalOptionParameters() { d1 = (log(forward/strike) / standardDeviation + standardDeviation / 2.0); d2 = d1 - (standardDeviation); Nd1 = cdf(n_0_1, d1); Nd2 = cdf(n_0_1, d2); internalParamtersSet = true; }
void ContContFactor::mkFactor(matrix_t &m) const{ for(matrix_t::iterator1 it1 = m.begin1(); it1 != m.end1(); ++it1){ boost::math::normal norm( it1.index1()*alpha_+beta_, sqrt(var_) ); for(matrix_t::iterator2 it2 = it1.begin(); it2 != it1.end(); ++it2){ //TODO Lazy evaluation? *it2 = cdf(norm, it2.index2()) - cdf(norm, it2.index2()-1); } } }
/* Truncated normal probability density function, on the log scale, with support [-bnd,+bnd], including the normalizing constant */ double dtrnormln(const double x, const double mu, const double sigma2, const double bnd) { double pln = -Inf; if ( (sigma2>0) && (x>=-bnd) && (x<=bnd) ) { boost::math::normal pnorm(mu,sqrt(sigma2)); pln = - 0.5 * log(sigma2) - 0.5 * (x-mu) * (x-mu) / sigma2 - log(cdf(pnorm,bnd) - cdf(pnorm,-bnd)); } return (pln); }
double EuropeanPutBlack76::getPremium(double forward, double strike, double standardDeviation, double discountFactor) { double d1 = (log(forward/strike) / standardDeviation + standardDeviation / 2.0); double d2 = d1 - (standardDeviation); boost::math::normal s; // Construct a standard normal distribution s double Nd1 = cdf(s, d1); double Nd2 = cdf(s, d2); return (- forward * (1-Nd1) + strike * (1-Nd2)) * discountFactor; }
//avec vol non constante //vol = sqrt( \int_0^T \sigma^2(u) du ) double Black_Price_vol2(const double& fwd, const double& strike, const double& vol, const double& T) //(check) { std::cout << "SJ : " << fwd << ", strike : " << strike << ", vol : " << vol << ", T : " << T << std::endl ; assert(vol > 0 && T > 0 && fwd >0 && strike >0); double d1 = (log(fwd/strike) + 0.5 * vol * vol) / vol ; double d2 = d1 - vol; boost::math::normal_distribution<> nd(0,1); double N1 = cdf(nd,d1); double N2 = cdf(nd,d2); return fwd*N1-strike*N2; }
static inline void ex4_init_block(int block) { curBlock = block; #ifdef EX4_HISTOS ex4_histo_sum = 0; ex4_pascal_level = 2 ; // (14-block)/5; for(int i=EX4_MIN; i <= EX4_MAX; i++) { ex4_histo[i] = 100000* (cdf((i+0.5)/gdevs[block]) - cdf((i-0.5)/gdevs[block])); ex4_histo_sum += ex4_histo[i]; } #endif }
//! without discount factor: r=0 double Black_Price(const double& fwd, const double& strike, const double& vol, const double& T) { assert(vol > 0 && T > 0 && fwd >0 && strike >0); double variance = vol*vol*T; double d1 = (log(fwd/strike) + 0.5*variance)/sqrt(variance); double d2 = d1 - sqrt(variance); boost::math::normal_distribution<> nd(0,1); double N1 = cdf(nd,d1); double N2 = cdf(nd,d2); return fwd*N1-strike*N2; }
void IonAcoustic_Initializer::init_particle(realkind& px, realkind& py, realkind& pz, int& ix, int& iy, int& iz, realkind& vx, realkind& vy, realkind& vz, int ispecies, int iptcl,int nptcls,int ioffset) { // Set Position Values, ifloat = 0-2 raised_cos cdf(alpha,1.0/kt); int nv1 = 4; int iptcl_new = floor((((double)iptcl*pdata->nptcls_device[0]))/((double)nptcls)); iptcl_new = iptcl_new*pdata->node_info->nTasks_g + (pdata->node_info->rank_g); iptcl_new = iptcl; int idist = iptcl_new%(nptcls/nv1); double temp_x; px = distribution_intrp((idist)/(1.0/nv1*nptcls),0.0,pdata->Lx,cdf)+0.5*pdata->Lx; // px = distribution_intrp(drandom(),0.0,pdata->Lx,cdf); //vx = 0.0; // vx = (2*(iptcl%2)-1)*sqrt(2.0*pdata->Te/(pdata->mspecies[0]*mass_e)); py = 0.5; pz = 0.5; ix = floor(px*pdata->didx); iy = floor(py*pdata->didy); iz = floor(pz*pdata->didz); px = px*pdata->didx - ix; py = py*pdata->didy - iy; pz = pz*pdata->didz - iz; ix = ((ix%pdata->nx)+pdata->nx)%pdata->nx; // Set Velocity Values, ifloat = 3-5 // realkind ux = alpha*v_shift*sin((px+ix)*pdata->dxdi/kt) + v_shift; realkind ux = alpha*sin((px+ix)*pdata->dxdi/kt)*9.7e-4*kt + v_shift; if(ispecies == 0) vx = box_muller(ux,sqrt(2.0*2.0e-4/(pdata->mspecies[ispecies]*mass_e))); else vx = box_muller(ux,sqrt(2.0*2.0e-4/(pdata->mspecies[ispecies]*mass_e))); vy = 0; vz = 0; }
void CopulaLatentMarkovNet::predict(vector<double>& prediction) { random_.reset(new CRandomMersenne(FLAGS_ep_randseed)); for (int i = 0; i < num_nodes_; ++i) if (observed_labels_[i] == 0) { // LOG(INFO) << "node " << i << ": " << m_by_ep_[i] << " " << v_by_ep_[i]; boost::math::normal nd(0.0, gmn_marginal_scale_[i]); boost::math::logistic ld(logistic_->get_mean(i), logistic_->scale_); double z = 0.0; for (int sample = 0; sample < FLAGS_num_marginal_samples; ++sample) { double u = random_->Random(); // LOG(INFO) << "sample " << sample << ": " << "u: "; boost::math::normal qnd(m_by_ep_[i], v_by_ep_[i]); double t = quantile(qnd, u); // LOG(INFO) << "t: " << t; u = cdf(nd, t); // LOG(INFO) << "u: " << u; if (u > 1.0-1e-10) u = 1.0 - 1e-10; else if (u < 1e-10) u = 1e-10; z += quantile(ld, u); } prediction.push_back(z/FLAGS_num_marginal_samples); /* double u = cdf(nd, m_by_ep_[i]); if (u > 1.0-1e-10) u = 1.0 - 1e-10; else if (u < 1e-10) u = 1e-10; prediction.push_back(quantile(ld, u)); */ } }
double run(NumberGenerator & gen, Distribution distrib) const { const int m = n; typedef std::vector<double> saved_temp; saved_temp a(m,1.0), b(m,0); std::vector<int> c(m,0); for(int i = 0; i < n; ++i) { double val = static_cast<double>(gen()); double y = cdf(distrib, val); int k = static_cast<int>(std::floor(m*y)); if(k >= m) --k; // should not happen a[k] = (std::min)(a[k], y); b[k] = (std::max)(b[k], y); ++c[k]; } double kplus = 0, kminus = 0; int j = 0; for(int k = 0; k < m; ++k) { if(c[k] > 0) { kminus = (std::max)(kminus, a[k]-j/static_cast<double>(n)); j += c[k]; kplus = (std::max)(kplus, j/static_cast<double>(n) - b[k]); } } kplus *= std::sqrt(double(n)); kminus *= std::sqrt(double(n)); // std::cout << "k+ " << kplus << " k- " << kminus << std::endl; return kplus; }
Matrix<T> CDFTools<T>::percentiles( const vector<const Vector<T>*>& x, const Vector<T>& xEvals, const Vectorf& percents) const { const int numSamples = x.size(); const int numEvals = xEvals.getSize(); const int numPercents = percents.getSize(); Matrix<T> matrix( numEvals, numSamples ); Matrix<T> y( numPercents, numEvals ); for (int i = 0; i < numSamples; ++i) { matrix.setColumn( i, cdf(*x[i],xEvals) ); } for (int j = 0; j < numEvals; ++j) { matrix[j].sort(); for (int p = 0; p < numPercents; ++p) { y(p,j) = matrix[j].percentile( percents[p] ); } } return y; }
void PartFilter::resample() { double invNbSamp = 1./mModels.size(); Eigen::VectorXf cdf(mModels.size()); cdf[0]=mCurrentWeights[0]; for (int i=1 ; i<mModels.size() ; i++) { cdf[i]=cdf[i-1]+mCurrentWeights[i]; } int i=0; double u = randUnif(invNbSamp); for (int j=0 ; j<mModels.size() ; j++) { while(u>cdf[i]) { i++; } for (int k=0 ; k<mOrientationVec[i].size() ; k++) { (*mOrientationVec[j][k])=(*mOrientationVec[i][k]); (*mOffsetVec[j][k])=(*mOffsetVec[i][k]); } mCurrentWeights[j]=invNbSamp; u=u+invNbSamp; } }
/** Randomly selects a point in the given tree node by considering probabilities * Runtime: O(S*S + log(S*S)) */ inline Eigen::Vector2f ProbabilityCellPoint(const Eigen::MatrixXf& m0, int scale, int x, int y) { x *= scale; y *= scale; const auto& b = m0.block(x, y, scale, scale); // build cdf std::vector<float> cdf(scale*scale); for(int i=0; i<scale; ++i) { for(int j=0; j<scale; ++j) { float v = b(j,i); int q = scale*i + j; if(q > 0) { cdf[q] = cdf[q-1] + v; } else { cdf[q] = v; } } } // sample in cdf boost::variate_generator<boost::mt19937&, boost::uniform_real<float> > rnd( Rnd(), boost::uniform_real<float>(0.0f, cdf.back())); float v = rnd(); // find sample auto it = std::lower_bound(cdf.begin(), cdf.end(), v); int pos = std::distance(cdf.begin(), it); return Eigen::Vector2f(x + pos%scale, y + pos/scale); }
double CopulaLatentMarkovNet::compute_loglikelihoodpart(double ts, const boost::math::normal& nd, double msigma) { // make use the quantile function of logistic distribution double ss = logistic_->scale_; double logcdf = log(cdf(nd, ts)); double logsf = log(cdf(complement(nd, ts))); double lres = -logcdf; /* if (abs(logcdf-logsf) < 50) lres = log(1.0+exp(logsf-logcdf)); else if (logsf > logcdf) lres = logsf; else lres = -logcdf; */ double logisticlog = logsf - logcdf - log(ss) - 2.0*lres; double gausslog = ts/msigma; gausslog = -0.5*gausslog*gausslog; return logisticlog - gausslog; }
void EEMS::propose_birthdeath_qVoronoi(Proposal &proposal) { int newqtiles = nowqtiles,r; double u = draw.runif(); double pBirth = 0.5; double pDeath = 0.5; boost::math::normal pnorm(0.0,sqrt(nowqrateS2)); proposal.newqEffcts = nowqEffcts; proposal.newqSeeds = nowqSeeds; // If there is exactly one tile, rule out a death proposal if ((nowqtiles==1) || (u<0.5)) { // Propose birth if (nowqtiles==1) { pBirth = 1.0; } newqtiles++; MatrixXd newqSeed = MatrixXd::Zero(1,2); randpoint_in_habitat(newqSeed); pairwise_distance(nowqSeeds,newqSeed).col(0).minCoeff(&r); // The new tile is assigned a rate by perturbing the current rate at the new seed double nowqEffct = nowqEffcts(r); double newqEffct = draw.rtrnorm(nowqEffct,params.qEffctProposalS2,params.qEffctHalfInterval); insertRow(proposal.newqSeeds,newqSeed.row(0)); insertElem(proposal.newqEffcts,newqEffct); // Compute log(proposal ratio) and log(prior ratio) proposal.newratioln = log(pDeath/pBirth) - dtrnormln(newqEffct,nowqEffct,params.qEffctProposalS2,params.qEffctHalfInterval) - log(cdf(pnorm,params.qEffctHalfInterval) - cdf(pnorm,-params.qEffctHalfInterval)); proposal.newpi = nowpi + log((nowqtiles+params.negBiSize)/(newqtiles/params.negBiProb)) - 0.5 * log(nowqrateS2) - 0.5 * newqEffct*newqEffct/nowqrateS2; } else { // Propose death if (nowqtiles==2) { pBirth = 1.0; } newqtiles--; int qtileToRemove = draw.runif_int(0,newqtiles); MatrixXd oldqSeed = nowqSeeds.row(qtileToRemove); removeRow(proposal.newqSeeds,qtileToRemove); removeElem(proposal.newqEffcts,qtileToRemove); pairwise_distance(proposal.newqSeeds,oldqSeed).col(0).minCoeff(&r); double nowqEffct = proposal.newqEffcts(r); double oldqEffct = nowqEffcts(qtileToRemove); // Compute log(prior ratio) and log(proposal ratio) proposal.newratioln = log(pBirth/pDeath) + dtrnormln(oldqEffct,nowqEffct,params.qEffctProposalS2,params.qEffctHalfInterval) + log(cdf(pnorm,params.qEffctHalfInterval) - cdf(pnorm,-params.qEffctHalfInterval)); proposal.newpi = nowpi + log((nowqtiles/params.negBiProb)/(newqtiles+params.negBiSize)) + 0.5 * log(nowqrateS2) + 0.5 * oldqEffct*oldqEffct/nowqrateS2; } proposal.move = Q_VORONOI_BIRTH_DEATH; proposal.newqtiles = newqtiles; proposal.newll = eval_birthdeath_qVoronoi(proposal); }
VAR* diverg(VAR* A){ VAR* ret_var = new VAR; int type1 = A->get_type(); if(type1==0 || type1==1) ret_var->set_type(-1); else { ret_var->set_type(1); for(int x = 0; x < DIM_SIZE; x++){ for(int y = 0; y < DIM_SIZE; y++){ for(int z = 0; z < DIM_SIZE; z++){ ret_var->sf[x][y][z] = cdf(A,x,y,z,0,0) + cdf(A,x,y,z,1,1) + cdf(A,x,y,z,2,2); } } } } delete A; return ret_var; }
double egHWU::ncChiSqSurvival(double df, double ncp, double q) { if(q<0) q=0; double p_higher_tail=1.0 - cdf(boost::math::non_central_chi_squared(df, ncp), q); return p_higher_tail; }
double BS::BlackFormula(double forward, double strike, double sigma, double discount) { if (sigma < 0) throw ("Error : the variance input cannot be negative"); double d1 = (log(forward/strike) + 0.5*sigma*sigma)/sigma; double d2 = d1 - sigma; boost::math::normal_distribution<> nd(0,1); double N1 = cdf(nd,d1); double N2 = cdf(nd,d2); return discount*(forward*N1-strike*N2); }
T nc_beta_ccdf(T a, T b, T nc, T x) { #ifdef NC_BETA_CCDF_FUNCTION_TO_TEST return NC_BETA_CCDF_FUNCTION_TO_TEST(a, b, nc, x); #else return cdf(complement(boost::math::non_central_beta_distribution<T>(a, b, nc), x)); #endif }
RealType operator()(const RealType& df) { if(df <= tools::min_value<RealType>()) return 1; chi_squared_distribution<RealType, Policy> cs(df); RealType result; if(ratio > 0) { RealType r = 1 + ratio; result = cdf(cs, quantile(complement(cs, alpha)) / r) - beta; } else { // ratio <= 0 RealType r = 1 + ratio; result = cdf(complement(cs, quantile(cs, alpha) / r)) - beta; } return result; }
// Cumulative density function double StandardNormalDistribution::cdf(const double& x) const { double k = 1.0/(1.0 + 0.2316419*x); double k_sum = k*(0.319381530 + k*(-0.356563782 + k*(1.781477937 + k*(-1.821255978 + 1.330274429*k)))); if (x >= 0.0) { return (1.0 - (1.0/(pow(2*M_PI,0.5)))*exp(-0.5*x*x) * k_sum); } else { return 1.0 - cdf(-x); } }
double NormalDistribution::ppf(double p) { const double a[6] = { -3.969683028665376e+01, 2.209460984245205e+02, -2.759285104469687e+02, 1.383577518672690e+02, -3.066479806614716e+01, 2.506628277459239e+00 }; const double b[5] = { -5.447609879822406e+01, 1.615858368580409e+02, -1.556989798598866e+02, 6.680131188771972e+01, -1.328068155288572e+01 }; const double c[6] = { -7.784894002430293e-03, -3.223964580411365e-01, -2.400758277161838e+00, -2.549732539343734e+00, 4.374664141464968e+00, 2.938163982698783e+00 }; const double d[4] = { 7.784695709041462e-03, 3.224671290700398e-01, 2.445134137142996e+00, 3.754408661907416e+00 }; register double q, t, u; if (isnan(p) || p > 1.0 || p < 0.0) { throw(std::runtime_error("Invalid input")); } if (p == 0.0) return -INFINITY; if (p == 1.0) return INFINITY; q = std::min(p,1-p); if (q > 0.02425) { /* Rational approximation for central region. */ u = q-0.5; t = u*u; u = u*(((((a[0]*t+a[1])*t+a[2])*t+a[3])*t+a[4])*t+a[5]) /(((((b[0]*t+b[1])*t+b[2])*t+b[3])*t+b[4])*t+1); } else { /* Rational approximation for tail region. */ t = sqrt(-2*log(q)); u = (((((c[0]*t+c[1])*t+c[2])*t+c[3])*t+c[4])*t+c[5]) /((((d[0]*t+d[1])*t+d[2])*t+d[3])*t+1); } /* The relative error of the approximation has absolute value less than 1.15e-9. One iteration of Halley's rational method (third order) gives full machine precision... */ t = cdf(u)-q; /* error */ t = t*M_SQRT2PI*exp(u*u/2); /* f(u)/df(u) */ u = u-t/(1+u*t/2); /* Halley's method */ return (p > 0.5 ? -u : u); }
inline RealType cdf(const complemented2_type<hypergeometric_distribution<RealType, Policy>, U>& c) { BOOST_MATH_STD_USING static const char* function = "boost::math::cdf(const hypergeometric_distribution<%1%>&, const %1%&)"; RealType r = static_cast<RealType>(c.param); unsigned u = itrunc(r, typename policies::normalise<Policy, policies::rounding_error<policies::ignore_error> >::type()); if(u != r) { return boost::math::policies::raise_domain_error<RealType>( function, "Random variable out of range: must be an integer but got %1%", r, Policy()); } return cdf(complement(c.dist, u)); }
void CompactDecimalFormatTest::CheckLocale(const Locale& locale, UNumberCompactStyle style, const ExpectedResult* expectedResults, int32_t expectedResultLength) { UErrorCode status = U_ZERO_ERROR; LocalPointer<CompactDecimalFormat> cdf(createCDFInstance(locale, style, status)); if (U_FAILURE(status)) { dataerrln("Unable to create format object - %s", u_errorName(status)); return; } char description[256]; sprintf(description,"%s - %s", locale.getName(), StyleStr(style)); for (int32_t i = 0; i < expectedResultLength; i++) { CheckExpectedResult(cdf.getAlias(), &expectedResults[i], description); } }
void OpenSource(CString &dir) { CWedDoc *pDoc; //P2N("OpenSource %p '%s' \r\n", dir, dir); CFileDialogST cdf(TRUE); CString droot, dresult, dfile, fname; char *buff = (char*)malloc(MAXFILENAMES + 1); if(!buff) { AfxMessageBox("Cannot get memory for OpenFile"); return; } *buff = '\0'; //if(dir == "") // cdf.m_ofn.lpstrInitialDir = droot; //else cdf.m_ofn.lpstrInitialDir = dir; cdf.m_ofn.lpstrFilter = Ffilter; cdf.m_ofn.lpstrFile = (char *)buff; cdf.m_ofn.nMaxFile = MAXFILENAMES; cdf.m_ofn.nFilterIndex = 1; cdf.m_ofn.Flags |= OFN_ALLOWMULTISELECT; if(cdf.DoModal() == IDOK) { POSITION pos = cdf.GetStartPosition(); while(TRUE) { if (!pos) break; fname = cdf.GetNextPathName(pos); pDoc = (CWedDoc*) AfxGetApp()->OpenDocumentFile(fname); if(!pDoc) break; if(YieldToWinEx()) break; } dir = fname; PathToDir(dir); } free(buff); }