Пример #1
0
int main(int argc, char const *argv[]) {
	
	int cases, size;
	int flag = 1;	
	scanf("%d", &cases);

	while(cases--) {

		scanf("%d", &size);

		float data[size];
		int i;

		for(i = 0; i < size; i++)
			scanf("%f", &data[i]);

		double branch = (size - 1) * log(2);

		float sum = 0.0;
		for(i = 0; i < size; i++)
			if(data[i] > 0)
				sum += exp(log(data[i]) + log(binomial(size - 1, i)) - branch);
			else 
				sum -= exp(log(-data[i]) + log(binomial(size - 1, i)) - branch);
		printf("Case #%d: %.3f\n", flag, sum);
		flag++;
	}

	return 0;

}
Пример #2
0
    lower_binomial::lower_binomial(unsigned N,unsigned n)
    {
	/* Subtract the total binomial sum until n is smaller than it: */

	n%=(1<<N);
	
	/* Start summing binomials until their sum exceeds n: */

	unsigned m=0;
	unsigned k=0;
	do
	{
	    k+=binomial(N,m);
	    ++m;
	}
	while(k<=n and m != N);

	/* Subtract the last term again: */

	k-=binomial(N,m-1);
	
	/* Store the obtained integers in their respective data members: */
	
	order=m-2;
	binom=binomial(N,order);
	binom_sum=k;
	difference=n-binom_sum;
    }
Пример #3
0
// A static function is not visible in other compilation units.
static long binomial(long n, long k) {
	if (k == 0 || n == k) return 1;

	if (n > k && k > 0) return binomial(n-1, k) + binomial(n-1, k-1);

	return 0;
}
Пример #4
0
double binomial_prefactor(int s, int ia, int ib, double xpa, double xpb) {
    int t;
    double sum=0.;
    for (t=0; t<s+1; t++)
        if ((s-ia <= t) && (t <= ib))
            sum += binomial(ia,s-t)*binomial(ib,t)*pow(xpa,ia-s+t)*pow(xpb,ib-t);
    return sum;
}
int binomial(int N,int k)
{
	if(knownBino[N][k]!=UNKNOWN)
		return(knownBino[N][k]);
	
	if(k==0 || N==k)
		return(knownBino[N][k]=1);

	return(knownBino[N][k]=binomial(N-1,k)+binomial(N-1,k-1));
}
Пример #6
0
static ex binomial_eval(const ex & x, const ex &y)
{
	if (is_exactly_a<numeric>(y)) {
		if (is_exactly_a<numeric>(x) && ex_to<numeric>(x).is_integer())
			return binomial(ex_to<numeric>(x), ex_to<numeric>(y));
		else
			return binomial_sym(x, ex_to<numeric>(y));
	} else
		return binomial(x, y).hold();
}
Пример #7
0
int main() {
    printf("%d\n", binomial(6, 3));
    printf("%d\n", binomial(6, 8));
    printf("%d\n", binomial(5, 5));
    printf("%d\n", binomial(100, 5));
    int a[100];
    binomialCoefficient(7, a);
    for (int i = 0; i <= 7; i++) printf("%d ", a[i]);
    return 0;
}
Пример #8
0
ex row_mul::GetSum(int i, int nj) const
{
	ex s = s_taylor;
	if(nj == int(nops() - 1))
		return op(nj).coeff(s, i);
	ex res;
	for(int j = 0; j <= i; j++)
		res += binomial(j,0)*op(nj).coeff(s, j)*binomial(i, j)*GetSum(i - j, nj+1);
	return res;
}
/** Changes the basis of p to be bernstein.
 \param p the Symmetric basis polynomial
 \returns the Bernstein basis polynomial

 if the degree is even q is the order in the symmetrical power basis,
 if the degree is odd q is the order + 1
 n is always the polynomial degree, i. e. the Bezier order
 sz is the number of bezier handles.
*/
void sbasis_to_bezier (Bezier & bz, SBasis const& sb, size_t sz)
{
    if (sb.size() == 0) {
        THROW_RANGEERROR("size of sb is too small");
    }

    size_t q, n;
    bool even;
    if (sz == 0)
    {
        q = sb.size();
        if (sb[q-1][0] == sb[q-1][1])
        {
            even = true;
            --q;
            n = 2*q;
        }
        else
        {
            even = false;
            n = 2*q-1;
        }
    }
    else
    {
        q = (sz > 2*sb.size()-1) ?  sb.size() : (sz+1)/2;
        n = sz-1;
        even = false;
    }
    bz.clear();
    bz.resize(n+1);
    double Tjk;
    for (size_t k = 0; k < q; ++k)
    {
        for (size_t j = k; j < n-k; ++j) // j <= n-k-1
        {
            Tjk = binomial(n-2*k-1, j-k);
            bz[j] += (Tjk * sb[k][0]);
            bz[n-j] += (Tjk * sb[k][1]); // n-k <-> [k][1]
        }
    }
    if (even)
    {
        bz[q] += sb[q][0];
    }
    // the resulting coefficients are with respect to the scaled Bernstein
    // basis so we need to divide them by (n, j) binomial coefficient
    for (size_t j = 1; j < n; ++j)
    {
        bz[j] /= binomial(n, j);
    }
    bz[0] = sb[0][0];
    bz[n] = sb[0][1];
}
Пример #10
0
ex row_power::GetSum(int i, int nj) const
{
	ex s = s_taylor;
	if(!is_exactly_a<numeric>(op(1).evalf()))
		ERROR_15(op(1), op(0))
	if(nj == int(ex_to<numeric>(op(1).eval()).to_int() - 1))
		return op(0).coeff(s, i);
	ex res;
	for(int j = 0; j <= i; j++)
		res += binomial(j,0)*op(0).coeff(s, j)*binomial(i, j)*GetSum(i - j, nj+1);
	return res;
}
Пример #11
0
    //--------------------------------------------------------------------------
    Real LossDist::binomialProbabilityOfAtLeastNEvents(int n, vector<Real>& p) {
    //--------------------------------------------------------------------------
        CumulativeBinomialDistribution binomial(p[0], p.size());
        return 1.0 - binomial(n-1);
        /*
        Real defp = 0;
        for (Size i = n; i <= p.size(); i++)
            defp += binomialProbabilityOfNEvents (i, p);

        return defp;
        */
    }
Пример #12
0
bool
ImageBufAlgo::make_kernel (ImageBuf &dst, string_view name,
                           float width, float height, float depth,
                           bool normalize)
{
    int w = std::max (1, (int)ceilf(width));
    int h = std::max (1, (int)ceilf(height));
    int d = std::max (1, (int)ceilf(depth));
    // Round up size to odd
    w |= 1;
    h |= 1;
    d |= 1;
    ImageSpec spec (w, h, 1 /*channels*/, TypeDesc::FLOAT);
    spec.depth = d;
    spec.x = -w/2;
    spec.y = -h/2;
    spec.z = -d/2;
    spec.full_x = spec.x;
    spec.full_y = spec.y;
    spec.full_z = spec.z;
    spec.full_width = spec.width;
    spec.full_height = spec.height;
    spec.full_depth = spec.depth;
    dst.reset (spec);

    if (Filter2D *filter = Filter2D::create (name, width, height)) {
        // Named continuous filter from filter.h
        for (ImageBuf::Iterator<float> p (dst);  ! p.done();  ++p)
            p[0] = (*filter)((float)p.x(), (float)p.y());
        delete filter;
    } else if (name == "binomial") {
        // Binomial filter
        float *wfilter = ALLOCA (float, width);
        for (int i = 0;  i < width;  ++i)
            wfilter[i] = binomial (width-1, i);
        float *hfilter = (height == width) ? wfilter : ALLOCA (float, height);
        if (height != width)
            for (int i = 0;  i < height;  ++i)
                hfilter[i] = binomial (height-1, i);
        float *dfilter = ALLOCA (float, depth);
        if (depth == 1)
            dfilter[0] = 1;
        else
            for (int i = 0;  i < depth;  ++i)
                dfilter[i] = binomial (depth-1, i);
        for (ImageBuf::Iterator<float> p (dst);  ! p.done();  ++p)
            p[0] = wfilter[p.x()-spec.x] * hfilter[p.y()-spec.y] * dfilter[p.z()-spec.z];
    } else {
Пример #13
0
int main() {
	int n, k;

	scanf("%d %d", &n, &k);

	printf("%d\n", ( k < 0 || k > n )? 0 : binomial(n, k));
}
Пример #14
0
// A static function is not visible in other compilation units.
static long binomial(long n, long k) {
	if (k == 0 || n == k) return 1;

	if (n > k && k > 0) return binomial(n, k-1)*(n-k+1)/k;

	return 0;
}
Пример #15
0
void test_some_math()
{
      // GCD tests
      assert(gcd(54,24) == gcd(12,90) && gcd(13,11) == 1);
      // LCM tests
      assert(lcm(114920, 14300) == 6320600);
      // Binomial coefficient test
      assert(binomial(10,2) == 45);
      // Test add
      assert(add(3,5) == 8 && add(7,3) == 10);
      // Test odd or even numbers
      assert(!is_even(1) && is_even(2) && !is_even(77) && is_even(500));
      // Test if bit n is set
      assert(!isbitNset(22, 3) && isbitNset(22,4));
      // Test set bit
      assert(setbitN(22,3) == 30 && setbitN(2,0) == 3);
      // Test unset bit
      assert(unsetbitN(30,3) == 22 && unsetbitN(3,0) == 2);
      // Test toggle
      assert(togglebitN(togglebitN(22,3),3) == 22);
      // Test modulo (power of two)
      assert(modulo(7,2) == 1 && modulo(6666,2) == 0 && modulo(64,8) == 0);
      // Test negate nibbles
      assert(neg_nibbles(173,0) == 160 && neg_nibbles(429,1) == 256);;
      // Test powX
      assert(powX(7,11) == 1977326743 && pow(2,8) == 256 && pow(123123,0) == 1);
}
Пример #16
0
static void allocPools( BigInt n ){
    nToTheThird = (BigInt)pow(n, 1.0 / 3);

    logn = (BigInt)(log(pow(n, 2.00001 / 3)) / log(2.0)) + 1;
    factorsMultiplied = new BigInt[nToTheThird];
    totalFactors = new BigInt[nToTheThird];
    factors = new BigInt[nToTheThird * logn];
    numPrimeBases = new BigInt[nToTheThird];
    DPrime = new BigInt[(nToTheThird + 1) * logn];
    binomials = new BigInt[128*128+ 128];
    for (BigInt j = 0; j < 128; j++) 
        for (BigInt k = 0; k <= j; k++)
            binomials[j * 128 + k]= binomial(j, k);
    for (BigInt j = 0; j < logn; j++) DPrime[j] = 0;
    curBlockBase = 0;

    t = n - 1;

    nToTheHalf = (BigInt)pow(n, 1.0 / 2);
    numDPowers = (BigInt)(log(pow(n, 2.00001 / 3)) / log(2.0)) + 1;
    dPrime = new double[(nToTheThird + 1) * (numDPowers + 1)];

    S1Val = 1;
    S1Mode = 0;
    S3Vals = new BigInt[nToTheThird + 1];
    S3Modes = new BigInt[nToTheThird + 1];

    ended = false;
    maxSieveValue = (BigInt)(pow(n, 2.00001 / 3));

    for (BigInt j = 2; j < nToTheThird + 1; j++){
        S3Modes[j] = 0;
        S3Vals[j] = 1;
    }
}
Пример #17
0
/*
 * binomial probability for n or more successes
 * out of N tries
 * with p sucess rate in each try.
 */
double binomial2(double p, int n, int N) {
	double b = 0;
	for (int i = n; i <= N; i++) {
		b += binomial(p, n, N);
	}
	return b;
}
Пример #18
0
vector<vector<double> > Perseus::binomial(int maxOrder){
	try {
		vector<vector<double> > binomial(maxOrder+1);
		
		for(int i=0;i<=maxOrder;i++){
			binomial[i].resize(maxOrder+1);
			binomial[i][0]=1;
			binomial[0][i]=0;
		}
		binomial[0][0]=1;
		
		binomial[1][0]=1;
		binomial[1][1]=1;
		
		for(int i=2;i<=maxOrder;i++){
			binomial[1][i]=0;
		}
		
		for(int i=2;i<=maxOrder;i++){
			for(int j=1;j<=maxOrder;j++){
				if(i==j){	binomial[i][j]=1;									}
				if(j>i)	{	binomial[i][j]=0;									}
				else	{	binomial[i][j]=binomial[i-1][j-1]+binomial[i-1][j];	}
			}
		}
		
		return binomial;
	}
	catch(exception& e) {
		m->errorOut(e, "Perseus", "binomial");
		exit(1);
	}
}
Пример #19
0
const Polynomial&
CoordinateChange::forwardTriangle_() {
  std::map< TriangleAddress, Polynomial >::const_iterator iterFIJ;
  const size_t wSize(wI_.size());
  for (Power j = 1; j <= currentGrade_ - 1; ++j) {
    for (Power i = 0; i <= currentGrade_ - 1 - j; ++i) {
      iterFIJ = fIJ_.find(TriangleAddress(i, j));
      if (iterFIJ == fIJ_.end()) {
        iterFIJ = fIJ_.find(TriangleAddress(i + 1, j - 1));
        assert(iterFIJ != fIJ_.end());
        Polynomial temp(iterFIJ->second);
        for (Power k = 0; k <= i; ++k) {
          assert((i + 1 - k) < wSize);
          const Polynomial& wTerm(wI_.at(i + 1 - k));
          iterFIJ = fIJ_.find(TriangleAddress(k, j - 1));
          assert(iterFIJ != fIJ_.end());
          const Polynomial& inner(iterFIJ->second);
          checkGrades_(i, j, inner, wTerm);
          temp += Coeff(binomial(i, k)) * algebra_.lieBracket(inner, wTerm);
        }
        fIJ_.insert(std::map< TriangleAddress, Polynomial >::value_type(TriangleAddress(i, j), temp));
      }
    }
  }
  iterFIJ = fIJ_.find(TriangleAddress(0, currentGrade_ - 1));
  assert(iterFIJ != fIJ_.end());
  return (iterFIJ->second);
}
Пример #20
0
void RNG::multinom(uint size, const double* probs, uint num_probs, uint* samp)
{
  if (num_probs == 0) return;
  for (uint i = 0; i < num_probs; i++) samp[i] = 0;
  if (size == 0) return;

  vector<double> fixed_probs(num_probs);
  double total_prob = 0.;
  for (uint i = 0; i < num_probs; i++) {
    const double pp = probs[i];
    //if (std::isfinite(pp) && pp >= 0)
    if ((pp == pp) && pp >= 0)
      total_prob += (fixed_probs[i] = pp);
  }

  if (total_prob == 0.) return;

  for (uint i = 0; i < num_probs-1; i++) {
    if (fixed_probs[i] > 0.) {
      samp[i] = binomial(fixed_probs[i] / total_prob, size);
      size -= samp[i];
    }
    if (size == 0) return;
    total_prob -= fixed_probs[i];
  }
  samp[num_probs - 1] = size;

} // RNG::multinomial
Пример #21
0
/* 
 * NOTE: We call this on the root node, which will clear all the a of non-leaf
 * nodes and builds the multipole moments (a) for every remainging cell in 
 * the tree.
 */
static void
accumulate_cell_multipoles(struct cell *this_)
{
    if(this_ == 0)
        return;
    else if(this_->childs[0] != 0) {
        /* NOTE: clear a to (0,0) if this is not a leaf node. */
        for(uint32_t i = 0; i < data.num_coeffs; i++) {
            this_->a[i] = V2(0, 0);
        }
    }

    for(uint32_t i = 0; i < 4; i++) {
        accumulate_cell_multipoles(this_->childs[i]);
    }

    /* do the actual work */
    if(this_->parent != 0) {
        this_->parent->a[0] += this_->a[0];
        v2 z = this_->parent->center - this_->center;
        for(uint32_t k = 1; k < data.num_coeffs; k++) {
            this_->parent->a[k] -= (this_->a[0]/k) * pow(z, k);
            for(uint32_t l = 1; l <= k; l++) {
                this_->parent->a[k] += binomial(k - 1, l - 1) *
                    this_->a[l] * pow(z, k - l);
            }
        }
    }
}
Пример #22
0
void MixMod::CalcMat()
{
int i,j;


 for(j=0;j<k;j++)
  {
   for(i=0;i<n;i++)
   {
     switch (dens)
     {
     case 0: // normal density
      {
     xf[i][j]=normal (x[i][0],t[j],x[i][3]);
      break;
      }
     case 1:  // poisson density
      {
      xf[i][j]=poisson(x[i][0],t[j]*x[i][2]);
      break;
      }
     case 2: // binomial density
      {
      xf[i][j]=binomial (x[i][0],x[i][2],t[j]);
      break;
      }
    }  // end of switch
   }  // end of i-loop
  } // end if j-loop
             //
 }
Пример #23
0
void undifference(double* series, unsigned int size, unsigned int d, double* pre_sample_series){

	unsigned int i, j;
	double* data;

	data = (double*)malloc((size+d)*sizeof(double));
	memcpy(data,series,size*sizeof(double));
	memcpy(data+size,pre_sample_series,d*sizeof(double));

	for(i=0;i<size;i++){
		int sign = 1;
		for(j=1;j<=d;j++){

			data[size-i-1] += sign*binomial(d,j)*data[size-i-j+1];
			sign *= -1;

		}

	}

	memcpy(series,data,size*sizeof(double));

	free(data);

}
Пример #24
0
static gdouble f(gint i,gint l,gint m,gdouble A,gdouble B)
{
	gint j,jmin,jmax;
	gdouble sum=0.0;

	jmin = 0;
	if(jmin<i-m) jmin =i-m;
	jmax = i;
	if(jmax>l) jmax = l;
	for( j=jmin;j<=jmax;j++)
	{
		sum += binomial(l,j)*binomial(m,i-j)*
		dpn(-A,l-j)*dpn(-B,m-i+j);

	}
	return sum; 
}
Пример #25
0
int RAIDProcess::msgDelay() {
	RAIDProcessState *myState = (RAIDProcessState*) getState();
	double ldelay;

	// Hard coded for now... add to ssl later
	sourcedist = UNIFORM;
	first = 1;
	second = 2;

	switch (sourcedist) {
	case UNIFORM: {
		Uniform uniform(first, second, myState->getGen());
		ldelay = uniform();
		break;
	}
	case NORMAL: {
		Normal normal(first, second, myState->getGen());
		ldelay = normal();
		break;
	}
	case BINOMIAL: {
		Binomial binomial((int) first, second, myState->getGen());
		ldelay = binomial();
		break;
	}
	case POISSON: {
		Poisson poisson(first, myState->getGen());
		ldelay = poisson();
		break;
	}
	case EXPONENTIAL: {
		NegativeExpntl expo(first, myState->getGen());
		ldelay = expo();
		break;
	}
	case FIXED:
		ldelay = (int) first;
		break;
	default:
		ldelay = 0;
		cerr << "Improper Distribution for a Source Object!!!" << "\n";
		break;
	}
	return ((int) ldelay);

}
  int multi_binomial(const MultiIndex<I, DIMENSION>& beta,
		     const MultiIndex<I, DIMENSION>& alpha)
  {
    int r(binomial(beta[0], alpha[0]));
    for (unsigned int i(1); i < DIMENSION; i++)
      r *= binomial(beta[i], alpha[i]);
    return r;
  }
Пример #27
0
void
eval_binomial(void)
{
	push(cadr(p1));
	eval();
	push(caddr(p1));
	eval();
	binomial();
}
Пример #28
0
int
main (void)
{
  int row, pos;
  int r = scanf ("%i%i", &row, &pos);
  assert (r == 2);
  printf ("%i", binomial (row, pos));
  return 0;
}
void binomial_test ( )

/******************************************************************************/
/*
  Purpose:

    BINOMIAL_TEST tests BINOMIAL.

  Licensing:

    This code is distributed under the GNU LGPL license.

  Modified:

    18 February 2012

  Author:

    John Burkardt
*/
{
  double c;
  double e;
  int m;
  double r;
  double s0;
  double sigma;
  double t1;

  printf ( "\n" );
  printf ( "BINOMIAL_TEST:\n" );
  printf ( "  A demonstration of the binomial method\n" );
  printf ( "  for option valuation.\n" );

  s0 = 2.0;
  e = 1.0;
  r = 0.05;
  sigma = 0.25;
  t1 = 3.0;
  m = 256;

  printf ( "\n" );
  printf ( "  The asset price at time 0 S0    = %g\n", s0 );
  printf ( "  The exercise price        E     = %g\n", e );
  printf ( "  The interest rate         R     = %g\n", r );
  printf ( "  The asset volatility      SIGMA = %g\n", sigma );
  printf ( "  The expiry date           T1    = %g\n", t1 );
  printf ( "  The number of intervals   M     = %d\n", m );

  c = binomial ( s0, e, r, sigma, t1, m );

  printf ( "\n" );
  printf ( "  The option value is %g\n", c );

  return;
}
Пример #30
0
ex row_power_z::GetSum(int i)
{
	ex s = s_taylor;
	if(op(0).coeff(s, 0).is_zero())
		return 0;
	if(i)
	{
		ex res;
		for(int j = 0; j < i; j++)
		{
			// для более долгого, но более точного вычисления нужно раскомментировать первую строку. Иначе вторую...
			//res += Tk[j]*op(0).coeff(s, i-j)*(binomial(i-1, j)*op(1) - binomial(i-1, j-1));
			res += sym_tk(this, j)*op(0).coeff(s, i-j)*(binomial(i-1, j)*op(1) - binomial(i-1, j-1));
		}
		return (res/op(0).coeff(s, 0));
	}
	else
		return pow(op(0).coeff(s, 0), op(1));
}