int64_t binom(int64_t n, int64_t k) { if(k == 0 || k == n) return 1; if(DP[n][k] != -1) return DP[n][k]; DP[n][k] = binom(n - 1, k - 1) + binom(n - 1, k); DP[n][k] %= M; return DP[n][k]; }
//This function generates the Zernike Polynomials. Please see: Efficient Cartesian representation of Zernike polynomials in computer memory //SPIE Vol. 3190 pp. 382 to get more details about the implementation void PolyZernikes::create(const Matrix1D<int> & coef) { Matrix2D<int> * fMatT; int nMax=(int)VEC_XSIZE(coef); for (int nZ = 0; nZ < nMax; ++nZ) { if (VEC_ELEM(coef,nZ) == 0) { fMatT = new Matrix2D<int>(1,1); dMij(*fMatT,0,0)=0; //*fMatT = 0; } else { // Note that the paper starts in n=1 and we start in n=0 int n = (size_t)ZERNIKE_ORDER(nZ); int l = 2*nZ-n*(n+2); int m = (n-l)/2; Matrix2D<int> testM(n+1,n+1); fMatT = new Matrix2D<int>(n+1,n+1); int p = (l>0); int q = ((n % 2 != 0) ? (abs(l)-1)/2 : (( l > 0 ) ? abs(l)/2-1 : abs(l)/2 ) ); l = abs(l); //We want the positive value of l m = (n-l)/2; for (int i = 0; i <= q; ++i) { int K1=binom(l,2*i+p); for (int j = 0; j <= m; ++j) { int factor = ( (i+j)%2 ==0 ) ? 1 : -1 ; int K2=factor * K1 * fact(n-j)/(fact(j)*fact(m-j)*fact(n-m-j)); for (int k = 0; k <= (m-j); ++k) { int ypow = 2 * (i+k) + p; int xpow = n - 2 * (i+j+k) - p; dMij(*fMatT,xpow,ypow) +=K2 * binom(m-j,k); } } } } fMatV.push_back(*fMatT); } }
double log_fact_table::cum_binomial_left(int x, int N, double prob) { // this is less strictly p(x < kin_node) *** NOT EQUAL *** if (x <= 0) return 0; if (x > N) return 1; if (prob < 1e-11) return 1; if (x > N * prob) return 1 - cum_binomial_right(x, N, prob); --x; double pzero = binom(x, N, prob); if (pzero <= 1e-40) return 0; double z_zero = 1.; double sum = z_zero; while (true) { --x; z_zero *= (1 - prob) * double(x + 1) / ((N - x) * prob); //cout<<"zzero sum "<<z_zero<<" "<<sum<<" "<<(ga + x)<<endl; if (z_zero < log_table_pr * sum) break; sum += z_zero; } return pzero * sum; }
MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); /*kozepre teszi a nyito kepernyot*/ QRect available_geom = QDesktopWidget().availableGeometry(); QRect current_geom = frameGeometry(); setGeometry(available_geom.width() / 2 - current_geom.width() / 2, available_geom.height() / 2 - current_geom.height() / 2, current_geom.width(), current_geom.height()); /********************************/ connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close())); connect(ui->actionSave, SIGNAL(triggered()), this, SLOT(MenTXT())); connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout())); connect(ui->actionBinom, SIGNAL(triggered()), this, SLOT(binom()) ); connect(ui->actionHelp, SIGNAL(triggered()), this, SLOT(showHelp())); connect(ui->actionPrint, SIGNAL(triggered()), this, SLOT(printIt())); ui->mainToolBar->addAction(ui->actionSave); ui->mainToolBar->addAction(ui->actionPrint); ui->mainToolBar->addSeparator(); ui->mainToolBar->addAction(ui->actionBinom); ui->mainToolBar->addSeparator(); ui->mainToolBar->addAction(ui->actionHelp); verzio = "2010-03-03"; settingClear(); }
double log_fact_table::cum_binomial_right(int x, int N, double prob) { // this is bigger or equal p(x >= kin_node) *** EQUAL *** //cout<<"x "<<x<<" N "<<N <<" prob "<<prob<<endl; if (x <= 0) return 1; if (x > N) return 0; if (prob - 1 > -1e-11) return 1; if (x < N * prob) return 1 - cum_binomial_left(x, N, prob); double pzero = binom(x, N, prob); if (pzero <= 1e-40) return 0; double z_zero = 1.; double sum = z_zero; while (true) { z_zero *= prob * double(N - x) / ((x + 1) * (1 - prob)); x++; //cout<<"zzero sum "<<z_zero<<" "<<sum<<" "<<endl; if (z_zero < log_table_pr * sum) break; sum += z_zero; } return pzero * sum; }
static void cache_3dfac(double *facs, int l, double *r) { int l1 = l + 1; double *facx = facs; double *facy = facs + l1*l1; double *facz = facy + l1*l1; double xx[16]; double yy[16]; double zz[16]; double bfac; int i, j, off; xx[0] = 1; yy[0] = 1; zz[0] = 1; for (i = 1; i <= l; i++) { xx[i] = xx[i-1] * r[0]; yy[i] = yy[i-1] * r[1]; zz[i] = zz[i-1] * r[2]; } for (i = 0; i <= l; i++) { for (j = 0; j <= i; j++) { bfac = binom(i,j); off = i*l1+j; facx[off] = bfac * xx[i-j]; facy[off] = bfac * yy[i-j]; facz[off] = bfac * zz[i-j]; } } }
int main (){ int n,k; while (scanf("%d%d", &n, &k) == 2) printf ("%d choose %d = %llu\n", n, k, binom(n,k)); return 0; }
long long binommod(long long a,long long b,long long p){ long long x=a,y=b; long long ret=1; for(;x>0||y>0;){ ret=(ret*binom(x%p,y%p,p))%p; x/=p;y/=p; } return ret; }
/** basis polynomial for regularized kernel */ double BasisPoly(int m, int r, double xx) { int k; double sum=0.0; for (k=0; k<=m-r; k++) { sum+=binom(m+k,k)*pow((xx+1.0)/2.0,(double)k); } return sum*pow((xx+1.0),(double)r)*pow(1.0-xx,(double)(m+1))/(1<<(m+1))/fak(r); /* 1<<(m+1) = 2^(m+1) */ }
void BinomialFactor::mkFactor(matrix_t &m) const{ boost::math::binomial binom(N_, prob_); //Return vector with probabilities over x for(int j = 0; j < m.size2(); ++j){ if( j+minv_ > N_) m(0,j) = 0; else m(0,j) = pdf( binom, j+minv_); } }
/** Generalized Lagrange basis polynomials (including derivatives up to degree p) * B_j(y) := r^j BasisPoly(p,j,y) * satisfies the 2p+2 Hermite interpolation conditions * B_j^k(-1) = delta(k,j), for k=0,...,p, * B_j^k(1) = 0, for k=0,...,p. * I.e., each B_j(y) is equal to 1 in the j-th derivative at y=-1 and zero in all other interpolation points. * Analogously, we get the derivates at y=1 via * C_j(y) := (-r)^j BasisPoly(p,j,-y) * that satisfies the 2p+2 Hermite interpolation conditions * C_j^k(-1) = 0, for k=0,...,p, * C_j^k(1) = delta(k,j), for k=0,...,p. * */ static fcs_float BasisPoly(fcs_int p, fcs_int j, fcs_float y) { fcs_int k; fcs_float sum=0.0; for (k=0; k<=p-j; k++) { sum+=binom(p+k,k)*fcs_pow((y+1.0)/2.0,(fcs_float)k); } return sum*fcs_pow((y+1.0),(fcs_float)j)*fcs_pow(1.0-y,(fcs_float)(p+1))/(1<<(p+1))/fak(j); /* 1<<(p+1) = 2^(p+1) */ }
/** Integrated generalized Lagrange basis polynomials * B_j(y) := r^(j+1) (IntBasisPoly(p,j,y) - IntBasisPoly(p,j,-1)) * satisfies the 2p+1 Hermite interpolation conditions * B_j^k(-1) = delta(k,j), for k=0,...,p, * B_j^k(1) = 0, for k=1,...,p. (the function value at y=-1 is not interpolated) * Analogously, we get the derivates at y=1 via * C_j(y) := (-r)^(j+1) (IntBasisPoly(p,j,-y) - IntBasisPoly(p,j,1)) * that satisfies the 2p+1 Hermite interpolation conditions * C_j^k(-1) = 0, for k=0,...,p, * C_j^k(1) = delta(k,j), for k=1,...,p. * */ static fcs_float IntBasisPoly(fcs_int p, fcs_int j, fcs_float y) { fcs_int k,l; fcs_float sum1=0.0, sum2=0.0; for (l=0; l<=p; l++) { sum1 = 0.0; for (k=0; k<=p-j-1; k++) { sum1 += binom(p+k-1,k)*fak(j+k)/fak(j+k+1+l)*fcs_pow((1.0+y)/2.0,(fcs_float)k); } sum2 += fcs_pow(1.0+y,(fcs_float)l)*fcs_pow(1.0-y,(fcs_float)(p-l))/fak(p-l)*sum1; } return sum2 * fak(p)/fak(j)/(1<<p)*fcs_pow(1.0+y,(fcs_float)(j+1)); /* 1<<p = 2^p */ }
/****************************************************************************** * Function: Cube::coord_slice_sorted * * Purpose: Given a particular slice of edges, extract the associated sorted * slice coordinate from the current cube position. * * Params: None. * * Returns: The value of the sorted slice coordinate. This coordinate is a * number in the range 0..11879 which describes the positions (order * matters) of the 4 edges belonging in the slice. * * Operation: Calculates the lexicographic position x of the set of 4 positions * occupied by the four slice edges, and also the lexicographic * position y of the permutation of these 4 edges among themselves, * and calculates the coordinate as 24x + y. ******************************************************************************/ int Cube::coord_slice_sorted(std::vector<int> edges) { // Local variables n, k. int n = edge_permutation.size(); int k = edges.size(); // The order in which the edges making up this slice appear in the current // cube position. std::vector<int> order = {}; // Calculate the lexicographic rank of the four positions occupied by // the slice edges. int pos_rank = 0; while (n-- > 0) { int curr_edge = edge_permutation[n]; if (std::find(edges.begin(), edges.end(), curr_edge) != edges.end()) { // We've found one of the slice edges, so update the rank and note // the order in which we found this edge. pos_rank += binom(n, k--); order.push_back(curr_edge); } } // Now calculate the lexicographic rank of the permutation of the four // edges among themselves int perm_rank = 0; int factorial = 1; for (int ii = order.size() - 1; ii >= 0; --ii) { int high_count = 0; for (int jj = ii + 1; jj < order.size(); ++jj) { if (order[jj] > order[ii]) { ++high_count; } } perm_rank += high_count * factorial; factorial *= (order.size() - ii); } // Return the combination of these two data which makes the coordinate return 24 * pos_rank + perm_rank; }
/** * Computes binomial coefficient @a n over @a k. * The implementation takes care that numbers don't become * unnecessarily large during the computation to avoid * overflow. * * @param n "over" parameter * @param k "under" parameter * @return @a n over @a k */ static unsigned binom(unsigned n, unsigned k) { unsigned result; unsigned i; if (0 == k) { return 1; } if (2*k > n) { result = binom(n, n - k); } else { result = n; for (i = 2; i <= k; i++) { result *= (n + 1 - i); result /= i; } } return result; }
void testPascal(double tol) { for (int size=1; size<20; size++) { Matrix<T,Dynamic,Dynamic> A(size,size), B(size,size), C(size,size); A.setZero(); for (int i=0; i<size-1; i++) A(i+1,i) = static_cast<T>(i+1); B.setZero(); for (int i=0; i<size; i++) for (int j=0; j<=i; j++) B(i,j) = static_cast<T>(binom(i,j)); C = A.matrixFunction(expfn); std::cout << "testPascal: size = " << size << " error funm = " << relerr(C, B); VERIFY(C.isApprox(B, static_cast<T>(tol))); C = A.exp(); std::cout << " error expm = " << relerr(C, B) << "\n"; VERIFY(C.isApprox(B, static_cast<T>(tol))); } }
int main() { // // Start with something we know will overflow: // my_distributions::normal norm(10, 2); errno = 0; std::cout << "Result of quantile(norm, 0) is: " << quantile(norm, 0) << std::endl; std::cout << "errno = " << errno << std::endl; errno = 0; std::cout << "Result of quantile(norm, 1) is: " << quantile(norm, 1) << std::endl; std::cout << "errno = " << errno << std::endl; // // Now try a discrete distribution: // my_distributions::binomial binom(20, 0.25); std::cout << "Result of quantile(binom, 0.05) is: " << quantile(binom, 0.05) << std::endl; std::cout << "Result of quantile(complement(binom, 0.05)) is: " << quantile(complement(binom, 0.05)) << std::endl; }
int binom(int n, int k) { return (n < k) ? 0 : (n == k) ? 1 : (binom(n-1, k) * n / (n-k)); }
/** * Return multiset coefficient. * * @param n "over" parameter * @param k "under" parameter * @return @a n over @a k */ static unsigned multiset_coeff(unsigned n, unsigned k) { return binom(n + k - 1, k); }
int main() { std_setup(); int n=6; double a=1.0; transform_args args( a,n,0 ); { double xi_f = 10.0; int N = 500; double h = xi_f/N; double *rp = ml_alloc<double> (2*N+1); double *ip = ml_alloc<double> (2*N+1); double *xi = ml_alloc<double> (2*N+1); for ( int j=-N; j<=N; j++ ) { args.xi = h*j; xi[j+N] = args.xi; rp[j+N] = integrate_R ( real_part, (void *)(&args) ); ip[j+N] = integrate_R ( imag_part, (void *)(&args) ); } output( xi, rp, ip, 2*N+1, "/workspace/output/temp/FTF" ); } //--------------------- { double xf = 10.0; int N = 500; double h = xf/N; double *F = ml_alloc<double> (2*N+1); double *X = ml_alloc<double> (2*N+1); for ( int j=-N; j<=N; j++ ) { double x = h*j; X[j+N] = x; F[j+N] = exp(-a*x*x)*pow(x,n); } output( X, F, 2*N+1, "/workspace/output/temp/F" ); } //----------------------- { double xi_f = 10.0; int N = 500; double h = xi_f/N; double *FTR = ml_alloc<double> (2*N+1); double *FTI = ml_alloc<double> (2*N+1); double *Xi = ml_alloc<double> (2*N+1); ml_poly<double > P0(n); P0 = 0.0; ml_poly<double > P1(n); P1 = 0.0; ml_poly<double > P2(n); P2 = 0.0; ml_poly<double > P3(n); P3 = 0.0; for ( int k=0; k<=n; k++ ) { if (k%4 == 0) P0[k] = binom(n,k)*dfact2n_n[n-k]*sqrtpi*pow(a,-n)*pow(2.0,k-2*n); if (k%4 == 1) P1[k] = binom(n,k)*dfact2n_n[n-k]*sqrtpi*pow(a,-n)*pow(2.0,k-2*n); if (k%4 == 2) P2[k] = binom(n,k)*dfact2n_n[n-k]*sqrtpi*pow(a,-n)*pow(2.0,k-2*n); if (k%4 == 3) P3[k] = binom(n,k)*dfact2n_n[n-k]*sqrtpi*pow(a,-n)*pow(2.0,k-2*n); } ml_poly<double > PR(n); P0 = 0.0; ml_poly<double > PI(n); P1 = 0.0; PR = P0; PR -= P2; PI = P1; PI-= P3; for ( int j=-N; j<=N; j++ ) { double xi = h*j; Xi[j+N] = xi; FTR[j+N] = exp(-xi*xi/(a*4))*PR(xi); FTI[j+N] = exp(-xi*xi/(a*4))*PI(xi); } output( Xi, FTR, FTI, 2*N+1, "/workspace/output/temp/test" ); } std_exit(); }
/* used as pileup callback function which is not ideal since this can * only work on one position (has to be ensured by caller). * * No cov means I won't be called through mpileup and no output will * be generated. Non-sig pv means I'm not sure and no ouput will be * generated. Only if pv is sig we will print the var * * needs to return void to be used as function pointer to mpileup */ void uniq_snv(const plp_col_t *p, void *confp) { uniq_conf_t *conf = (uniq_conf_t *)confp; char *af_char = NULL; float af; int is_uniq = 0; int is_indel; int coverage; is_indel = vcf_var_is_indel(conf->var); #ifdef DISABLE_INDELS if (is_indel) { LOG_WARN("uniq logic can't be applied to indels." " Skipping indel var at %s %d\n", conf->var->chrom, conf->var->pos+1); return; } #endif if (0 != strcmp(p->target, conf->var->chrom) || p->pos != conf->var->pos) { LOG_ERROR("wrong pileup for var. pileup for %s %d. var for %s %d\n", p->target, p->pos+1, conf->var->chrom, conf->var->pos+1); return; } coverage = p->coverage_plp; if (is_indel) { coverage -= p->num_tails; } if (1 > coverage) { return; } if (conf->uni_freq <= 0.0) { if (! vcf_var_has_info_key(&af_char, conf->var, "AF")) { LOG_FATAL("%s\n", "Couldn't parse AF (key not found) from variant"); /* hard to catch error later */ exit(1); } af = strtof(af_char, (char **)NULL); /* atof */ free(af_char); if (af < 0.0 || af > 1.0) { float new_af; new_af = af<0.0 ? 0.01 : 1.0; /* hard to catch error later */ LOG_FATAL("Invalid (value out of bound) AF %f in variant. Resetting to %f\n", af, new_af); af = new_af; } } else { assert(conf->uni_freq <= 1.0); af = conf->uni_freq; } if (conf->use_det_lim) { /* given the current base counts and their error probs, * would we've been able to detect at given frequency. */ long double pvalues[NUM_NONCONS_BASES]; double *err_probs; /* error probs (qualities) passed down to snpcaller */ int num_err_probs; int alt_bases[NUM_NONCONS_BASES];/* actual alt bases */ int alt_counts[NUM_NONCONS_BASES]; /* counts for alt bases handed down to snpcaller */ int alt_raw_counts[NUM_NONCONS_BASES]; /* raw, unfiltered alt-counts */ varcall_conf_t varcall_conf; int bonf = 1; float alpha = 0.01; init_varcall_conf(&varcall_conf); if (debug) { dump_varcall_conf(&varcall_conf, stderr); } plp_to_errprobs(&err_probs, &num_err_probs, alt_bases, alt_counts, alt_raw_counts, p, &varcall_conf); LOG_DEBUG("at %s:%d with cov %d and num_err_probs %d\n", p->target, p->pos, coverage, num_err_probs); /* Now pretend we see AF(SNV-to-test)*coverage variant * bases. Truncate to int, i.e err on the side of caution * during rounding (assume fewer alt bases) */ alt_counts[0] = af * num_err_probs; /* don't use coverage as that is before filtering */ alt_counts[1] = alt_counts[2] = 0; if (snpcaller(pvalues, err_probs, num_err_probs, alt_counts, bonf, alpha)) { fprintf(stderr, "FATAL: snpcaller() failed at %s:%s():%d\n", __FILE__, __FUNCTION__, __LINE__); free(err_probs); return; } /* only need to test first pv */ if (pvalues[0] * (float)bonf < alpha) { /* significant value means given the counts and * qualities we would have been able to detect this * uncalled SNV had it been present at the given * frequency. But since we didn't this is a uniq * variant. * * No point in adding this as phred qual because it * means the opposite of UQ */ vcf_var_add_to_info(conf->var, uniq_flag); } LOG_VERBOSE("%s %d num_quals=%d assumed-var-counts=%d would-have-been-detectable=%d\n", conf->var->chrom, conf->var->pos+1, num_err_probs, alt_counts[0], is_uniq); free(err_probs); } else { int alt_count; double pvalue; char info_str[128]; if (is_indel) { int ref_len = strlen(conf->var->ref); int alt_len = strlen(conf->var->alt); if (ref_len > alt_len) { /* deletion */ char *del_key = malloc((strlen(conf->var->ref)+1)*sizeof(char)); strcpy(del_key, conf->var->ref+1); del_event *it_del = find_del_sequence(&p->del_event_counts, del_key); if (it_del) { alt_count = it_del->count; } else { alt_count = 0; } /* LOG_DEBUG("%s>%s k:%s c:%d\n", conf->var->ref, conf->var->alt, del_key, alt_count); */ free(del_key); } else { /* insertion */ char *ins_key = malloc((strlen(conf->var->alt)+1)*sizeof(char)); strcpy(ins_key, conf->var->alt+1); ins_event *it_ins = find_ins_sequence(&p->ins_event_counts, ins_key); if (it_ins) { alt_count = it_ins->count; } else { alt_count = 0; } /* LOG_DEBUG("%s>%s k:%s c:%d\n", conf->var->ref, conf->var->alt, ins_key, alt_count);*/ free(ins_key); } } else { alt_count = base_count(p, conf->var->alt[0]); } #ifdef DEBUG LOG_DEBUG("Now testing af=%f cov=%d alt_count=%d at %s %d for var:", af, coverage, alt_count, p->target, p->pos+1); #endif /* this is a one sided test */ if (0 != binom(&pvalue, NULL, coverage, alt_count, af)) { LOG_ERROR("%s\n", "binom() failed"); return; } snprintf(info_str, 128, "%s=%d", uniq_phred_tag, PROB_TO_PHREDQUAL_SAFE(pvalue)); vcf_var_add_to_info(conf->var, info_str); LOG_DEBUG("%s %d %s>%s AF=%f | %s (p-value=%g) | BAM alt_count=%d cov=%d (freq=%f)\n", conf->var->chrom, conf->var->pos+1, conf->var->ref, conf->var->alt, af, is_uniq ? "unique" : "not necessarily unique", pvalue, alt_count, coverage, alt_count/(float)coverage); } }
/* Неефективен рекурсивен вариант */ unsigned long binom(unsigned n, unsigned k) { if (k > n) return 0; else if (0 == k || k == n) return 1; else return binom(n-1, k-1) + binom(n-1, k); }
int main(void) { printf("%lu\n", binom(7,3)); return 0; }
int main(void) { char choice='x'; int a,b, exit=0; float fa,fb; do { printf("> "); fflush(stdin); scanf("%1s", &choice); switch(choice) { case '+': scanf("%d %d", &a, &b); printf("# %d\n",add(a,b)); break; case '-': scanf("%d %d", &a, &b); printf("# %d\n",sub(a,b)); break; case '/': scanf("%f %f", &fa, &fb); printf("# %.2f\n",div(fa, fb)); break; case 'd': scanf("%d %d", &a, &b); printf("# %d\n",iDiv(a,b)); break; case 'm': scanf("%d %d", &a, &b); printf("# %d\n",mod(a,b)); break; case '*': scanf("%d %d", &a, &b); printf("# %d\n",mul(a,b)); break; case '^': scanf("%d %d", &a,&b); printf("# %lld\n",nthPower(a, b)); break; case '!': scanf("%d", &a); printf("# %lld\n",fact(a)); break; case 's': scanf("%d", &a); printf("# %d\n",sum(a)); break; case 'a': scanf("%d", &a); printf("# %.2f\n",avg(a)); break; case 'c': scanf("%d %d", &a, &b); printf("# %lld\n",binom(a,b)); break; case 'p': scanf("%d", &a); if(prime(a)) printf("# y\n"); else printf("# n\n"); break; case 'q': exit = 1; break; default:printf("Unknown arguement: %c\n", choice); } } while(!exit); return 0; }
/** * Return true with probability 1/π. * * @tparam Random the type of the random generator. * @param[in,out] r a random generator. * @return true with probability 1/π. **********************************************************************/ template<class Random> bool operator()(Random& r) { // Return true with prob 1/pi. int n = geom4(r) + geom4(r) + (prob59(r) ? 1 : 0); for (int j = 3; j--; ) if (!binom(r, n)) return false; return true; }