Ejemplo n.º 1
0
Archivo: p3a.c Proyecto: DavidToca/acm
double solve()
{
	double c, s;
	int i, j, k, r;

	r = n - 1;
	k = r >> 1;

	if (r & 1) {
		c = exp(lgamma(r + 1) - lgamma(k + 1) - lgamma(r - k + 1) - r * l2);
		for (s = 0., i = k, j = k + 1; i >= 0; i--, j++) {
			s += c * (a[i] + a[j]);
			c *= i / (double)(r - i + 1.);
		}
	} else {
		c = exp(lgamma(r + 1) - 2 * lgamma(k + 1) - r * l2);
		s = c * a[k];
		c *= k / (double)(r - k + 1.);
		for (i = k - 1, j = k + 1; i >= 0; i--, j++) {
			s += c * (a[i] + a[j]);
			c *= i / (double)(r - i + 1.);
		}
	}

	return s;
}
// 2x2 (one-sided) Fisher's exact test
// see B. Moore. (2004) On Log Likelihood and the Significance of Rare Events
double fisher_exact(int cfe, int ce, int cf)
{
  assert(cfe <= ce);
  assert(cfe <= cf);

  int a = cfe;
  int b = (cf - cfe);
  int c = (ce - cfe);
  int d = (num_lines - ce - cf + cfe);
  int n = a + b + c + d;

  double cp = exp(lgamma(1+a+c) + lgamma(1+b+d) + lgamma(1+a+b) + lgamma(1+c+d) - lgamma(1+n) - lgamma(1+a) - lgamma(1+b) - lgamma(1+c) - lgamma(1+d));
  double total_p = 0.0;
  int tc = std::min(b,c);
  for (int i=0; i<=tc; i++) {
    total_p += cp;
//      double lg = lgamma(1+a+c) + lgamma(1+b+d) + lgamma(1+a+b) + lgamma(1+c+d) - lgamma(1+n) - lgamma(1+a) - lgamma(1+b) - lgamma(1+c) - lgamma(1+d); double cp = exp(lg);
//      print(a,b,c,d,cp);
    double coef = (double)(b)*(double)(c)/(double)(a+1)/(double)(d+1);
    cp *= coef;
    ++a;
    --c;
    ++d;
    --b;
  }
  return total_p;
}
void add(mymatrix *matrix, int smpls, unsigned l, int i)
{
    unsigned j,k;
    for (j = 0; j < l; ++j)
        for (k = j; k < l; ++k)
	    matrix[OFFSET(i,samples[j],samples[k])].count++;

    for (j = 0; j < smpls; ++j)
        for (k = j + 1; k < smpls; ++k)
            if (freq[j] || freq[k])
            {
                if (freq[j] < PRECMP && freq[k] < PRECMP) // The most common case is this one
                {
                    unsigned offset = OFFSET(i,j,k);
                    matrix[offset].log    += pow( prelog[freq[j]]  - prelog[freq[k]],  2);
                    matrix[offset].sqrt   += pow( presqrt[freq[j]] - presqrt[freq[k]], 2);
                    matrix[offset].lgamma += (freq[j] + freq[k] < PRECMP ? prelgamma[freq[j] + freq[k]] : lgamma(freq[j] + freq[k] + 1))
                        - prelgamma[freq[j]] - prelgamma[freq[k]] - (freq[j] + freq[k] + 1);
                }
                else
                {
                    unsigned offset = OFFSET(i,j,k);  // Rare case in our data
                    matrix[offset].log    += pow( log(1+freq[j]) - log(1+freq[k]), 2);
                    matrix[offset].sqrt   += pow( sqrt(freq[j])  - sqrt(freq[k]),  2);
                    matrix[offset].lgamma += lgamma(freq[j] + freq[k] + 1) - lgamma(freq[j] + 1) 
                                           - lgamma(freq[k] + 1) - (freq[j] + freq[k] + 1);
                }
            }
}
Ejemplo n.º 4
0
double compute_likelihood(document* doc, lda_model* model, double** phi, double* var_gamma) {
	double likelihood = 0, digsum = 0, var_gamma_sum = 0, dig[model->num_topics];
	int k = 0, n = 0, index = 0;
  memset(dig,0.0,sizeof(dig));

	for (k = 0; k < model->num_topics; k++)
	{
		dig[k] = digamma(var_gamma[k]);
		var_gamma_sum += var_gamma[k];
	}
	digsum = digamma(var_gamma_sum);

	likelihood = lgamma(model->alpha * model->num_topics) -
               model->num_topics *
               lgamma(model->alpha) -
               lgamma(var_gamma_sum);

	for (k = 0; k < model->num_topics; k++)
	{
		likelihood += (model->alpha - 1)*(dig[k] - digsum) + lgamma(var_gamma[k]) - (var_gamma[k] - 1)*(dig[k] - digsum);

		for (n = 0; n < doc->length; n++)
		{
			if (phi[n][k] > 0)
			{
        index = doc->words[n];
				likelihood += doc->counts[n]*
					(phi[n][k]*((dig[k] - digsum) - log(phi[n][k])
					+ model->log_prob_w[k][index]));
			}
		}
	}
	return(likelihood);
}
Ejemplo n.º 5
0
static double aterms(double mya, void *mydata) {
  int i, t;
  double val = 0;
  double la = log(mya);
#ifdef A_DEBUG
  float save_a = ddC.SX->a;
  double like;
#endif
  S_remake(ddC.SX, mya);
  for (i=0; i<ddN.DT; i++) {
    uint32_t Td_ = 0;
    for (t=0; t<ddN.T; t++) {
      Td_ += ddS.Tdt[i][t];
      if ( ddS.Ndt[i][t]>1 ) {
	val += S_S(ddC.SX,ddS.Ndt[i][t],ddS.Tdt[i][t]);
      }
    }
    val += Td_*la + lgamma(ddP.bpar/mya+Td_) - lgamma(ddP.bpar/mya);
  }  
  myarms_evals++;
#ifdef A_DEBUG
  yap_message("Eval aterms(%lf) = %lf (S had %f)", mya, val, save_a);
  ddP.apar = mya;
  cache_update("a");
  like = likelihood();
  if ( last_val != 0 ) {
    yap_message(", lp=%lf diffs=%lf vs %lf\n", like, 
		val-last_val, like-last_like);
  }
  last_like = like;
  last_val = val;
#endif
  return val;
}
Ejemplo n.º 6
0
static double awterms(double myaw, void *mydata) {
  int i, t;
  double val = 0;
  double law = log(myaw);
#ifdef A_DEBUG
  float save_a = ddC.SY->a;
  double like;
#endif
  S_remake(ddC.SY, myaw);
  for (t=0; t<ddN.T; t++) {
    uint32_t Tw_ = 0;
    for (i=0; i<ddN.W; i++) {
      Tw_ += ddS.Twt[i][t];
      if ( ddS.Nwt[i][t]>1 ) {
        val += S_S(ddC.SY,ddS.Nwt[i][t],ddS.Twt[i][t]);
      }
    }
    val += Tw_*law + lgamma(ddP.bwpar/myaw+Tw_) - lgamma(ddP.bwpar/myaw);
  }
  myarms_evals++;
#ifdef A_DEBUG
  yap_message("Eval awterms(%lf) = %lf (S had %f)", myaw, val, save_a);
  ddP.awpar = myaw;
  cache_update("aw");
  like = likelihood();
  if ( last_val != 0 ) {
    yap_message(", lp=%lf diffs=%lf vs %lf\n", like,
                val-last_val, like-last_like);
  }
  last_like = like;
  last_val = val;
#endif
  return val;
}
Ejemplo n.º 7
0
Float tweedie_logW(Float y, Float phi, Float p){
  bool ok = (0 < y) && (0 < phi) && (1 < p) && (p < 2);
  if (!ok) return NAN;

  Float p1 = p - 1.0, p2 = 2.0 - p;
  Float a = - p2 / p1, a1 = 1.0 / p1;
  Float cc, w, sum_ww = 0.0, ww_max ;
  double j;

  /* only need the lower bound and the # terms to be stored */
  int jh, jl, jd;
  double jmax = 0;
  Float logz = 0;

  /* compute jmax for the given y > 0*/
  cc = a * log(p1) - log(p2);
  jmax = asDouble( fmax2(1.0, pow(y, p2) / (phi * p2)) );
  logz = - a * log(y) - a1 * log(phi) + cc;

  /* find bounds in the summation */
  /* locate upper bound */
  cc = logz + a1 + a * log(-a);
  j = jmax ;
  w = a1 * j ;
  while (1) {
    j += TWEEDIE_INCRE ;
    if (j * (cc - a1 * log(j)) < (w - TWEEDIE_DROP))
      break ;
  }
  jh = ceil(j);
  /* locate lower bound */
  j = jmax;
  while (1) {
    j -= TWEEDIE_INCRE ;
    if (j < 1 || j * (cc - a1 * log(j)) < w - TWEEDIE_DROP)
      break ;
  }
  jl = imax2(1, floor(j)) ;
  jd = jh - jl + 1;

  /* set limit for # terms in the sum */
  int nterms = imin2(imax(&jd, 1), TWEEDIE_NTERM), iterm ;
  Float *ww = Calloc(nterms, Float) ;
  /* evaluate series using the finite sum*/
  /* y > 0 */
  sum_ww = 0.0 ;
  iterm = imin2(jd, nterms) ;
  for (int k = 0; k < iterm; k++) {
    j = k + jl ;
    ww[k] = j * logz - lgamma(1 + j) - lgamma(-a * j);
  }
  ww_max = dmax(ww, iterm) ;
  for (int k = 0; k < iterm; k++)
    sum_ww += exp(ww[k] - ww_max);
  Float ans = log(sum_ww) + ww_max  ;
  Free(ww);

  return ans;
}
Ejemplo n.º 8
0
void qcache_init(struct gcache_s *lgp, double p) {
  lgp->par = p;
  if ( p>0 ) 
    lgp->lgpar = lgamma(1-2*p) - lgamma(1-p);
  else
    lgp->lgpar = 0;
  memset(lgp->cache, 0, GCACHE*sizeof(lgp->cache[0]));
}
Ejemplo n.º 9
0
 double dbeta(double x, double a, double b)
 {
     double out = (a-1)*std::log(x) + 
         (b-1)*std::log(1-x) + 
         (lgamma(a+b)) - 
         ((lgamma(a)) + (lgamma(b)));
     return(out);
 }
Ejemplo n.º 10
0
 double beta_logp(const T& x, const U& alpha, const V& beta) {
   if(!arma::all(x > 0) || !arma::all(x < 1) ||
      !arma::all(alpha > 0) || !arma::all(beta > 0))
     return -std::numeric_limits<double>::infinity();
   return arma::accu(lgamma(alpha+beta) - lgamma(alpha) - lgamma(beta)
                     + schur_product(alpha - 1.0f, log_approx(x))
                     + schur_product(beta - 1.0f, log_approx(1.0f - x)));
 }
Ejemplo n.º 11
0
double lBeta(vector<vector<Brother> >& groups) {
	double res = 0.0, mult = 1.0;
	for (size_t i = 0; i < groups.size(); ++i) {
		res += lgamma(groups[i].size());
		mult *= groups[i].size();
	}
	return (res - lgamma(mult));
}
Ejemplo n.º 12
0
inline typename boost::math::tools::promote_args<T1, T2>::type
log_falling_factorial(const T1 x, const T2 n) {
    if (is_nan(x) || is_nan(n))
        return std::numeric_limits<double>::quiet_NaN();
    static const char* fun = "log_falling_factorial";
    check_positive(fun, "first argument", x);
    return lgamma(x + 1) - lgamma(x - n + 1);
}
Ejemplo n.º 13
0
Type dbeta(Type x, Type shape1, Type shape2, int give_log)
{
	Type res = exp(lgamma(shape1+shape2) - lgamma(shape1) - lgamma(shape2)) * pow(x,shape1-1) * pow(1-x,shape2-1);
	if(!give_log) 
		return res;
	else 
		return CppAD::CondExpEq(x,Type(0),log(res),lgamma(shape1+shape2) - lgamma(shape1) - lgamma(shape2) + (shape1-1)*log(x) + (shape2-1)*log(1-x));
}
static double lBeta ( const double * vector, const double length ) {
  double result = 0;
  int i;
  for (i = 0; i < ALPHABET_SIZE; i++)
    result += lgamma( vector[i] );
 
  return (result - lgamma( length ));
}
Ejemplo n.º 15
0
  //======================================================================
  double dmvt(const Vector &x,  const Vector &mu, const SpdMatrix &Siginv, double nu,
	      double ldsi, bool logscale){
    long dim = mu.size();
    double nc = lgamma( (nu + dim)/2.0 ) + .5 * ldsi
        - lgamma(nu/2.0) - (.5*dim) * (log(nu) + Constants::log_pi);
    double delta = Siginv.Mdist(x, mu);
    double ans = nc - .5*(nu + dim)*(::log1p(delta/nu));
    return logscale ? ans : exp(ans);
  }
Ejemplo n.º 16
0
double NegBinomial(int kk, double rr, double pp)
{
	double log_pmf = 0;

	if ((kk>=0)&&(rr>0)&&(pp>=0)&&(pp<=1))
		log_pmf = lgamma(kk+rr) - lgamma(kk+1) - lgamma(rr)  + log(1-pp)*rr + log(pp)*kk;

	return exp(log_pmf);
}
Ejemplo n.º 17
0
inline Type dnbinom(const Type &x, const Type &size, const Type &prob,
		    int give_log=0)
{
  Type n=size;
  Type p=prob;
  Type logres = lgamma(x+n)-lgamma(n)-lgamma(x+Type(1))+
    n*log(p)+x*log(Type(1)-p);
  if (give_log) return logres; else return exp(logres);
}
Ejemplo n.º 18
0
// unnormalized log( P(alpha|k,n)) for crp
static double lcrpUNormPost(size_t k, size_t n, double alpha)
{
    // sometimes alpha is zero because of floating point error
    // ASSERT_GREATER_THAN_ZERO(std::cout, alpha);
    ASSERT_GREATER_THAN_ZERO(std::cout, n);
    ASSERT_GREATER_THAN_ZERO(std::cout, k);

    return lgamma(alpha)+double(k)*log(alpha)-lgamma(alpha+double(n));
}
Ejemplo n.º 19
0
void dtweedielogwsmallp(double *y, double *phi, double *power, double *logw) {
  double p,a,a1,r,drop=37,logz,jmax,j,cc,wmax,estlogw,oldestlogw;
  int hij,lowj;
  
  if (*power < 1) error("Error - power<1!");
  if (*power > 2) error("Error - power>2!");
  if (*phi <= 0) error("Error - phi<=0!");
  if (*y <= 0) error("Error - y<=0!");
  p = *power;
  a = (2 - p)/(1 - p);
  a1 = 1 - a;
  r = -a * log(*y) + a * log(p - 1) - a1 * log(*phi) - log(2 - p);
  logz = r;
  
  jmax = (pow(*y,(2 - p)))/(*phi * (2 - p));
  j = fmax2(1, jmax);
  cc = logz + a1 + a * log(-a);
  wmax = a1 * jmax;
  estlogw = wmax;
  while (estlogw > (wmax - drop)) {
    j = j + 2;
    estlogw = j * (cc - a1 * log(j));
  }
  
  hij = (int)ceil(j);
  logz = r;
  jmax = pow(*y,(2 - *power))/(*phi * (2 - *power));
  j = fmax2(1, jmax);
  wmax = a1 * jmax;
  estlogw = wmax;
  while ((estlogw > (wmax - drop)) && (j >= 2)) {
    j = fmax2(1, j - 2);
    oldestlogw = estlogw;
    estlogw = j * (cc - a1 * log(j));
  }
  lowj = (int)fmax2(1, floor(j));
  
  double newj[hij-lowj+1];
  int k;
  for(k=0;k<(hij-lowj+1);k++) newj[k] = lowj+k;
  
  double g[hij-lowj+1]; 
  for(k=0;k<hij-lowj+1;k++) g[k] = lgamma(newj[k]+1)+lgamma(-a*newj[k]);
  
  double A[hij-lowj+1];
  for(k=0;k<hij-lowj+1;k++) A[k] = r*(double)newj[k]-g[k];
  
  double m=fmax2(A[0],hij-lowj+1);
  for(k=0;k<(hij-lowj+1);k++) m = fmax2(A[k],hij-lowj+1);

  double we[hij-lowj+1];
  for(k=0;k<hij-lowj+1;k++) we[k] = exp(A[k]-m);
  double sumwe=0;
  for(k=0;k<hij-lowj+1;k++) sumwe+=we[k];
  *logw=log(sumwe)+m;
}
Ejemplo n.º 20
0
double gammap (double a, double x)
{
  /** Incomplete Gammafunction **/
  if (x < 0 || a <= 0) return 0; /* invalid arguments */

  if (x < a+1)
     return gammap_sr(a,x,lgamma(a));
  else
     return 1-gammaq_cf(a,x,lgamma(a));
}
Ejemplo n.º 21
0
double entropia (double *Ni, int n) {
  double N = 0, S = 0;

  for (int i = 0; i < n; i++) {
    N += Ni [i];
    S -= lgamma (Ni[i] + 1);
  }
  S += lgamma (N + 1) - N * log ((double)n);
  return S;
}
Ejemplo n.º 22
0
Type dbinom(Type k, Type size, Type prob, int give_log=0)
{
  Type logres = lgamma(size + 1) - lgamma(k + 1) - lgamma(size - k + 1);
  // Add 'k * log(prob)' only if k > 0
  logres += CppAD::CondExpGt(k, Type(0), k * log(prob), Type(0) );
  // Add '(size - k) * log(1 - prob)' only if size > k
  logres += CppAD::CondExpGt(size, k, (size - k) * log(1 - prob), Type(0) );
  if (!give_log) return exp(logres);
  else return logres;
}
Ejemplo n.º 23
0
/**************************************************************************
 * binomial exact
 **************************************************************************/
double binomial_exact(int succ, int trials, double prob) {
  double out;
  //note: 
  //gamma(x + 1) = x!
  //lgamma(x) = log(gamma(x)) = log((x-1)!)
  out = lgamma(trials + 1) - lgamma(trials - succ + 1) - lgamma(succ + 1) + 
    log(prob) * succ + log(1.0-prob) * (trials - succ) ;

  return exp(out);
}
Ejemplo n.º 24
0
TEST(AgradRev,lgamma) {
  AVAR a = 3.0;
  AVAR f = lgamma(a);
  EXPECT_FLOAT_EQ(lgamma(3.0),f.val());

  AVEC x = createAVEC(a);
  VEC grad_f;
  f.grad(x,grad_f);
  EXPECT_FLOAT_EQ(boost::math::digamma(3.0),grad_f[0]);
}
Ejemplo n.º 25
0
Archivo: 557.c Proyecto: DavidToca/acm
int main()
{
	int t, n;

	for (scanf("%d", &t); t-- > 0 && scanf("%d", &n) == 1;)
		printf("%.4f\n",
			1. - exp(lgamma(n-1) - 2.*lgamma(n/2.) - (n-2)*log(2.)));

	return 0;
}
Ejemplo n.º 26
0
double pdpmlm_logpcls( pdpm_t * obj, unsigned int cls ) {
    pdpmlm_t * mdl = (pdpmlm_t *) obj->model;
    double logp = 0.0;
    if( obj->gcl[ cls ] == 0 ) { return logp; }
    //compute posterior statistics
    pdpmlm_parm( obj, cls, mdl->s, mdl->m, &mdl->a, &mdl->b, &mdl->d );
    //compute posterior mass
    logp = lgamma( mdl->a / 2 ) - ( mdl->a / 2 ) * log( mdl->b / 2 ) - mdl->d;
    logp += obj->lam * lgamma( obj->gcl[ cls ] );
    return logp;
}
Ejemplo n.º 27
0
double StudentsTLogPdf::f(double nu, double mu, double sigma, const double* xs, size_t n)
{
    double part1 =
        n * (lgamma((nu + 1) / 2) - lgamma(nu / 2) - fastlog(sqrt(nu * M_PI) * sigma));

    double part2 = 0.0;
    for (size_t i = 0; i < n; ++i) {
        part2 += log1p(sq((xs[i] - mu) / sigma) / nu);
    }

    return part1 - ((nu + 1) / 2) * part2;
}
//-------------------------------------------------------------------------------------------------------
// calculate the logarithm of the beta-function for sum of two vectors. In Kimmens script |x| is
// defined as sum_xi, so |x| + |y| = | x + y | !!
// the first vector is an int
static double lBetaSum ( const Count * vector1, 
			 const Count length1, 
			 const double *vector2, 
			 const Count length2) {
    double result = 0;
    int i;
    
    for (i = 0; i < ALPHABET_SIZE; i++)
	result += lgamma( vector1[i] + vector2[i]);
    
    return (result - lgamma( length1 + length2 ));
}
Ejemplo n.º 29
0
//evaluates the ELBO for an individual who is a stayer
double getStayerProb(mm_modelExt model){
    int stayerID = model.getStayerID();

    double t1,t2,t3,t4;
    double phi_sum = 0.0;
    double elbo;
    int j,k,r,n;
    int K = model.getK();
    int J = model.getJ();
    double back_term;
    double dg_phi_sum;
    double phi_ik, delta_ijrnk;

    //Calculate first line and second line
    t1 = 0.0;
    t2 = 0.0;
    t3 = 0.0;
    t4 = 0.0;


    t1 = lgamma(sum(model.getAlpha())) - sum(lgamma(model.getAlpha()));

    for(k = 0; k < K; k++) {
        phi_sum += model.getPhi(stayerID,k);
    }
    dg_phi_sum = boost::math::digamma(phi_sum);

    t4 += lgamma(phi_sum);
    for(k = 0; k < K; k++) {
        phi_ik = model.getPhi(stayerID,k);
        back_term = (boost::math::digamma(phi_ik) - dg_phi_sum);
        t1+= (model.getAlpha(k) - 1.0) * back_term;

        t4 += -lgamma(phi_ik);
        t4 += (phi_ik - 1.0) * back_term;

        for(j = 0; j < J; j++) {
            for(r = 0; r < model.getR(j); r++) {
                for(n = 0; n < model.getN(stayerID, j, r); n++) {
                    delta_ijrnk = model.getDelta(stayerID, j, r, n, k);
                    t2 += delta_ijrnk*back_term;
                    t4 += delta_ijrnk*log(delta_ijrnk);
                }
            }
        }
    }

//compute 3rd line
    t3 = getStayer_logf(model, stayerID);

    elbo = t1 + t2 + t3 - t4;
    return elbo;
}
Ejemplo n.º 30
0
int main(){

	//Given the equation (2n)!/(n!)^2

	int n = 20;
	std::cout << "Calcuating number of routes..." << std::endl;
	long long answer = exp(lgamma((n + n) + 1)) / (exp(lgamma(n + 1))*exp(lgamma(n + 1)));
	std::cout << "The answer is: " << answer+1 << std::endl;

	system("Pause");
	return 0;
}