您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ sum函数代码示例

51自学网 2021-06-03 08:33:28
  C++
这篇教程C++ sum函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中sum函数的典型用法代码示例。如果您正苦于以下问题:C++ sum函数的具体用法?C++ sum怎么用?C++ sum使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了sum函数的29个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: Q_ASSERT

Cn Analitza::operate(Container* c){	Q_ASSERT(c);	Operator *op=0;	Cn ret(0.);	QList<Cn> numbers;		if(c->containerType() > 100)		qDebug() << "wow";		if(c->m_params.isEmpty()) {		m_err << i18n("Empty container: %1").arg(c->containerType());		return Cn(0.);	}		if(c->m_params[0]->type() == Object::oper)		op = (Operator*) c->m_params[0];		if(op!= 0 && op->operatorType()==Object::sum)		ret = sum(*c);	else if(op!= 0 && op->operatorType()==Object::product)		ret = product(*c);	else switch(c->containerType()) {		case Object::apply:		case Object::math:		case Object::bvar:		case Object::uplimit:		case Object::downlimit:		{			if(c->m_params[0]->type() == Object::variable) {				Ci* var= (Ci*) c->m_params[0];								if(var->isFunction())					ret = func(c);				else					ret = calc(c->m_params[0]);			} else {				QList<Object*>::iterator it = c->m_params.begin();				for(; it!=c->m_params.end(); it++) {					if((*it)==0) {						m_err << i18n("Null Object found");						ret.setCorrect(false);						return ret;					} else if((*it)->type() != Object::oper) {						numbers.append(calc(*it));					}				}								if(op==0) {					ret = numbers.first();				} else if(op->nparams()>-1 && numbers.count()!=op->nparams() && op->operatorType()!=Object::minus) {					m_err << i18n("Too much operators for <em>%1</em>").arg(op->operatorType());					ret = Cn(0.);				} else if(numbers.count()>=1 && op->type()==Object::oper) {					if(numbers.count()>=2) {						QList<Cn>::iterator it = numbers.begin();						ret = *it;												++it;						for(; it != numbers.end(); ++it)							reduce(op->operatorType(), &ret, *it, false);											} else {						ret=numbers.first();						reduce(op->operatorType(), &ret, 0., true);					}				} else {					ret = numbers.first();				}			}		}			break;		case Object::declare:		{			if(c->m_params.count()<=1) {				m_err << i18n("Need a var name and a value");				return Cn(0.);			}						Ci *var = (Ci*) c->m_params[0];						switch(c->m_params[1]->type()) {				case Object::variable:					m_vars->modify(var->name(), new Ci(c->m_params[1]));					break;				case Object::value:					m_vars->modify(var->name(), new Cn(c->m_params[1]));					break;				case Object::oper:					m_vars->modify(var->name(), new Operator(c->m_params[1]));					break;				case Object::container:					m_vars->modify(var->name(), new Container(c->m_params[1]));					break;				case Object::none:					m_err << i18n("Unvalid var type");					break;			}		} break;		case Object::lambda://.........这里部分代码省略.........
开发者ID:BackupTheBerlios,项目名称:kalgebra-svn,代码行数:101,


示例2: max

  }  delete hij;  delete vij;  max=-10000;  max_index=0;  for (ii=0;ii<wid;ii++)  {  int imm;     newh[ii]=kk[imm];  }HdeltaMax = max(Hdelta,[],3);hs = sum(HdeltaMax(:));VdeltaMax = max(Vdelta,[],3);vs = sum(VdeltaMax(:));hij = reshape(Hdelta,size(Hdelta,1)*size(Hdelta,2),size(Hdelta,3)); %shij = sum(hij,1);vij = reshape(Vdelta,size(Vdelta,1)*size(Vdelta,2),size(Vdelta,3)); %svij = sum(vij,1);newh = zeros(size(hij,1),1);for ii = 1:size(hij,1), tmp1 = hij(ii,:); tmp2 = vij(ii,:); mtmp1 = max(tmp1); mtmp2 = max(tmp2); mtmp1 = mtmp1(1); mtmp2 = mtmp2(1); mm = max(mtmp1,mtmp2); im1 = find(tmp1==mtmp1); im2 = find(tmp2==mtmp2); if mm == mtmp1, imm = im1(1); else, imm = im2(1); end newh(ii) = kk(imm);endtotal_coarseness = mean(newh);
开发者ID:kjarosz,项目名称:cuda_udat,代码行数:31,


示例3: main

main(){	char sal='0',opt,optarre;	printf("Bernardo Orozco Garza 1719152/n");	printf("Lo llenaras tu o random? 1) TU 0) RANDOM  ");	fflush(stdin);	scanf("%c",&optarre);	while(optarre!='1'&&optarre!='0'){	    printf("ERROR de captura  ");	    fflush(stdin);        scanf("%c",&optarre);	}	printf("Dame el tamano del arreglo (1-10)/t");	scanf("%d",&n);	while(n<1||n>10){		printf("ERROR de captura  ");		scanf("%d",&n);	}	switch(optarre){	    case '1':            printf("Introduce los valores del arreglo/n");            for(i=0;i<n;i++){                for(j=0;j<n;j++){                    printf("%d,%d = ",i+1,j+1);                    scanf("%f",&list[i][j]);                }            }            break;        case '0':            for(i=0;i<n;i++){                for(j=0;j<n;j++){                    list[i][j]=rand() % 10 + 1;                }            }            break;	}	do{		printf("Que quieres hacer? /n 1) SUMA/n 2) RESTA/n 3) DIVICION/n 4) MULTIPLICACION/n 5) ORDENAR ARREGLO/n 6) BUSQUEDA/n 7) SUMA TRIANGULO SUPERIOR E INFERIOR/n 8) SALIR/n");		fflush(stdin);		opt=getch();		while(opt!='1'&&opt!='2'&&opt!='3'&&opt!='4'&&opt!='5'&&opt!='6'&&opt!='7'&&opt!='8'){			printf("ERROR de captura 1-8 ");			fflush(stdin);			opt=getch();		}		switch(opt){			case '1':				sum();				break;			case '2':				res();				break;			case '3':				div();				break;			case '4':				mul();				break;            case '5':				ordenacion();				break;            case '6':                busqueda();				break;            case '7':                triangulo();				break;		}		if(opt!='8'){		printf("/n/ndeseas salir? 1) SI 0) NO ");		fflush(stdin);		scanf("%c",&sal);		}		while(sal!='1'&&sal!='0'){			printf("ERROR de captura 1 o 0 ");			fflush(stdin);			sal=getch();		}		system("cls");	}while(sal=='0'&&opt!='8');	getch();}
开发者ID:Infinity0106,项目名称:Cplusplus,代码行数:83,


示例4: main

main(){	int n;float s=1;float sum(int,float);	scanf("%d",&n);	sum(n,s);} 
开发者ID:xs020105,项目名称:bitprogram,代码行数:6,


示例5: main

int main(int argc, char const *argv[]) {  int *c = (int *)malloc(3 * sizeof(int));  // Изначально вводит тип предполагаемой операции:  // + - сложение  // c - умножение на число  // m - скалярное произведение  // v - векторное произведение  // g - скалярной произведение с кв.формой  int j;  char s;  scanf("%s/n", &s);  for (j = 0; j < 3; j++)    scanf("%d", a + j);  for (j = 0; j < 3; j++)    scanf("%d", b + j);  if (s == '+') {    c = sum(a, b);    printf("Result:/n");    int j;    for (j = 0; j < 3; j++)      printf("%d ", c[j]);  }  if (s == 'c') {    c = cmul(a, b);    printf("Result:/n");    int j;    for (j = 0; j < 3; j++)      printf("%d ", c[j]);  }  if (s == 'v') {    c = vmul(a, b);    printf("Result:/n");    int j;    for (j = 0; j < 1; j++)      printf("%d ", c[j]);  }  if (s == 'm') {    c = scmul(a, b);    printf("Result:/n");    printf("%d ", c[0]);  }  if (s == 'g') {    for (j = 0; j < 3; j++)      scanf("%d", g + j);    c = scmul_g(a, b, g);    printf("Result:/n");    printf("%d ", c[0]);  }  free(c);  return 0;}
开发者ID:heyfaraday,项目名称:homework-asm-repository,代码行数:68,


示例6: r_0

const Real GreensFunction2DAbs::p_int_theta_second(const Real r,                                                   const Real theta,                                                   const Real t) const{    const Real r_0(this->getr0());    const Real a(this->geta());    const Real minusDt(-1e0 * this->getD() * t);    const Integer num_in_term_use(100);    const Integer num_out_term_use(100);    const Real threshold(CUTOFF);    Real sum(0e0);    Real term(0e0);    Integer n(1);    for(; n < num_out_term_use; ++n)    {        Real in_sum(0e0);        Real in_term(0e0);        Real in_term1(0e0);        Real in_term2(0e0);        Real in_term3(0e0);        Real a_alpha_mn(0e0);        Real alpha_mn(0e0);        Real Jn_r_alpha_mn(0e0);        Real Jn_r0_alpha_mn(0e0);        Real Jn_d_1_a_alpha_mn(0e0);// J_n-1(a alpha_mn)        Real Jn_p_1_a_alpha_mn(0e0);// J_n+1(a alpha_mn)        Real n_real(static_cast<double>(n));        int n_int(static_cast<int>(n));        Integer m(1);        for(; m < num_in_term_use; ++m)        {            a_alpha_mn = gsl_sf_bessel_zero_Jnu(n_real, m);            alpha_mn = a_alpha_mn / a;            Jn_r_alpha_mn     = gsl_sf_bessel_Jn(n_int, r * alpha_mn);            Jn_r0_alpha_mn    = gsl_sf_bessel_Jn(n_int, r_0 * alpha_mn);            Jn_d_1_a_alpha_mn = gsl_sf_bessel_Jn(n_int - 1, a_alpha_mn);            Jn_p_1_a_alpha_mn = gsl_sf_bessel_Jn(n_int + 1, a_alpha_mn);            in_term1 = std::exp(alpha_mn * alpha_mn * minusDt);            in_term2 = Jn_r_alpha_mn * Jn_r0_alpha_mn;            in_term3 = Jn_d_1_a_alpha_mn - Jn_p_1_a_alpha_mn;            in_term = in_term1 * in_term2 / (in_term3 * in_term3);            in_sum += in_term;//                 std::cout << "inner sum " << in_sum << ", term" << in_term << std::endl;            if(fabs(in_term/in_sum) < threshold)            {//                     std::cout << "normal exit. m = " << m << " second term" << std::endl;                break;            }        }        if(m == num_in_term_use)            std::cout << "warning: use term over num_in_term_use" << std::endl;//             term = in_sum * std::cos(n_real * theta);        term = in_sum * std::sin(n_real * theta) / n_real;        sum += term;//             std::cout << "outer sum " << sum << ", term" << term << std::endl;        if(fabs(in_sum / (n_real * sum)) < threshold)        {            /* if n * theta is a multiple of /pi, the term may be zero and *             * term/sum become also zero. this is a problem. sin is in a   *             * regeon [-1, 1], so the order of term does not depend on     *             * value of sin, so this considers only (in_sum / n_real).     *///                 std::cout << "normal exit. n = " << n << " second term" << std::endl;            break;        }    }    if(n == num_out_term_use)        std::cout << "warning: use term over num_out_term_use" << std::endl;    return (8e0 * sum / (M_PI * a * a));}
开发者ID:ecell,项目名称:greens_functions,代码行数:83,


示例7: endmembers

////// /brief Vespucci::Math::DimensionReduction::VCA/// Vertex Component Analysis/// /param R The dataset/// /param endmembers Number of endmembers to compute/// /param indices Row indices of pure components./// /param endmember_spectra Spectra of pure components (note that these are in/// columns, not rows as in spectra_)/// /param projected_data Projected data/// /param fractional_abundances Purity of a given spectrum relative to endmember/// /return Convergeance (no actual test implemented...)///bool Vespucci::Math::DimensionReduction::VCA(const arma::mat &R, arma::uword p,         arma::uvec &indices, arma::mat &endmember_spectra,         arma::mat &projected_data, arma::mat &fractional_abundances){//Initializations    arma::uword L = R.n_rows;    arma::uword N = R.n_cols;    if (L == 0 || N == 0){        std::cerr << "No data!" << std::endl;        return false;    }    if (p > L){        std::cerr << "wrong number of endmembers (" << p << ")!"<< std::endl;        std::cerr << "set to 5 or one less than number of spectra" << std::endl;        p = (L < 5? 5: L-1);    }//mat of SNR    arma::mat r_m = mean(R, 1);    arma::mat R_m = arma::repmat(r_m, 1, N); //the mean of each spectral band    arma::mat R_o = R - R_m; //mean-center the data    arma::mat Ud;    arma::vec Sd;    arma::mat Vd;    //arma::svds(Ud, Sd, Vd, arma::sp_mat(R_o * R_o.t()/N), p);    Vespucci::Math::DimensionReduction::svds(R_o*R_o.t()/N, p, Ud, Sd, Vd);    arma::mat x_p;    try{    x_p = Ud.t() * R_o;    }catch(std::exception e){        std::cout << "Ud.t() * R_o" << std::endl;    }    double SNR = Vespucci::Math::DimensionReduction::estimate_snr(R, r_m, x_p);    double SNR_th = 15 + 10*log10(p);//Choose projective projection or projection to p-1 subspace    arma::mat y;    if (SNR < SNR_th){        arma::uword d = p - 1;        Ud = Ud.cols(0, d-1);        projected_data = Ud * x_p.rows(0, d-1) + R_m; //in dimension L        arma::mat x = x_p.rows(0, d-1);//x_p = trans(Ud)*R_o, p-dimensional subspace        //following three lines are one in arma::matlab...        arma::mat sum_squares = sum(pow(x, 2));        double c = sum_squares.max();        c = std::sqrt(c);        y = arma::join_vert(x, c*arma::ones(1, N));      }    else{        arma::uword d = p;        Vespucci::Math::DimensionReduction::svds(R*R.t()/N, p, Ud, Sd, Vd);        arma::svds(Ud, Sd, Vd, arma::sp_mat(R*R.t()/N), d);//R_o is a mean centered version...        x_p = Ud.t() * R;        projected_data = Ud * x_p.rows(0, d-1);        arma::mat x = Ud.t() * R;        arma::mat u = arma::mean(x, 1);        y = x / arma::repmat(sum(x % arma::repmat(u, 1, N)), d, 1);    }    // The VCA algorithm    arma::vec w;    w.set_size(p);    arma::vec f;    arma::rowvec v;    indices.set_size(p);    //there are no fill functions for arma::uvecs    for (arma::uword i = 0; i < p; ++i)        indices(i) = 0;    arma::mat A = arma::zeros(p, p);    double v_max;    double sum_squares;    arma::uvec q1;    A(p-1, 0) = 1;    for (arma::uword i = 0; i < p; ++i){        w.randu();        f = w - A*arma::pinv(A)*w;        sum_squares = std::sqrt(arma::sum(arma::square(f)));        f /= sum_squares;        v = f.t() * y;        v_max = arma::max(arma::abs(v));        q1 = arma::find(arma::abs(v) == v_max, 1);        indices(i) = q1(0);        A.col(i) = y.col(indices(i)); //same as x.col(indices(i));    }    endmember_spectra = projected_data.cols(indices);//.........这里部分代码省略.........
开发者ID:gtrosen,项目名称:Vespucci,代码行数:101,


示例8: switch

Type Foam::fieldValues::cellSource::processValues(    const Field<Type>& values,    const scalarField& V,    const scalarField& weightField) const{    Type result = pTraits<Type>::zero;    switch (operation_)    {        case opSum:        {            result = sum(values);            break;        }        case opSumMag:        {            result = sum(cmptMag(values));            break;        }        case opAverage:        {            result = sum(values)/values.size();            break;        }        case opWeightedAverage:        {            result = sum(values)/sum(weightField);            break;        }        case opVolAverage:        {            result = sum(values*V)/sum(V);            break;        }        case opVolIntegrate:        {            result = sum(values*V);            break;        }        case opMin:        {            result = min(values);            break;        }        case opMax:        {            result = max(values);            break;        }        case opCoV:        {            Type meanValue = sum(values*V)/sum(V);            const label nComp = pTraits<Type>::nComponents;            for (direction d=0; d<nComp; ++d)            {                scalarField vals(values.component(d));                scalar mean = component(meanValue, d);                scalar& res = setComponent(result, d);                res = sqrt(sum(V*sqr(vals - mean))/sum(V))/mean;            }            break;        }        default:        {            // Do nothing        }    }    return result;}
开发者ID:BijanZarif,项目名称:OpenFOAM-2.4.0-MNF,代码行数:75,


示例9: TimeSegmentation

    //Class constructor	TimeSegmentation(Tobj &G, Col <T1> map_in, Col <T1> timeVec_in, uword a, uword b, uword c, uword interptype = 1,					 uword shots = 1)    {		cout << "Entering Class constructor" << endl;	    n1 = a; //Data size	    n2 = b;//Image size	    L = c; //number of time segments	    type = interptype; // type of time segmentation performed	    Nshots = shots; // number of shots	    obj = &G;	    fieldMap = map_in;    	cout << "N1 = " << n1 << endl;		cout << "N2 = " << n2 << endl;		cout << "L = " << L << endl;		AA.set_size(n1, L); //time segments weights	    timeVec = timeVec_in;	    T_min =timeVec.min();	    T1 rangt = timeVec.max()-T_min;		tau = (rangt + datum::eps) / (L - 1); // it was L-1 before	    timeVec = timeVec-T_min;	    uword NOneShot = n1/Nshots;	    if (L==1) {		    tau = 0;		    AA.ones();	    }	    else {			Mat <CxT1> tempAA(NOneShot, L);		    if (type==1) {// Hanning interpolator			    cout << "Hanning interpolation" << endl;			    for (unsigned int ii = 0; ii<L; ii++) {				    for (unsigned int jj = 0; jj<NOneShot; jj++) {					    if ((std::abs(timeVec(jj)-((ii)*tau)))<=tau) {						    tempAA(jj, ii) = 0.5+0.5*std::cos((datum::pi)*(timeVec(jj)-((ii)*tau))/tau);					    }					    else {						    tempAA(jj, ii) = 0.0;					    }				    }			    }			    AA = repmat(tempAA, Nshots, 1);		    }		    else if (type==2) { // Min-max interpolator: Exact LS interpolator			    cout << "Min Max time segmentation" << endl;			    Mat <CxT1> Ltp;			    Ltp.ones(1, L);			    Col <CxT1> ggtp;			    ggtp.ones(n2, 1);			    Mat <CxT1> gg;			    gg = exp(i*fieldMap*tau)*Ltp;			    Mat <CxT1> iGTGGT;			    iGTGGT.set_size(L+1, n2);			    Mat <CxT1> gl;			    gl.zeros(n2, L);			    for (unsigned int ii = 0; ii<L; ii++) {				    for (unsigned int jj = 0; jj<n2; jj++) {					    gl(jj, ii) = pow(gg(jj, ii), (T1) (ii+1));				    }			    }			    Mat <CxT1> G;			    G.set_size(n2, L);			    for (unsigned int jj = 0; jj<L; jj++) {				    if (jj==0) {					    G.col(jj) = ggtp;				    }				    else {					    G.col(jj) = gl.col(jj-1);				    }			    }			    Col <CxT1> glsum;			    Mat <CxT1> GTG;			    GTG.zeros(L, L);			    GTG.diag(0) += n2;			    glsum = sum(gl.t(), 1);				Mat <CxT1> GTGtp(L, L);				for (unsigned int ii = 0; ii < (L - 1); ii++) {					GTGtp.zeros();				    GTGtp.diag(-(T1) (ii+1)) += glsum(ii);				    GTGtp.diag((T1) (ii+1)) += std::conj(glsum(ii));				    GTG = GTG+GTGtp;			    }			    T1 rcn = 1/cond(GTG);			    if (rcn>10*2e-16) { //condition number of GTG				    iGTGGT = inv(GTG)*G.t();			    }			    else {				    iGTGGT = pinv(GTG)*G.t(); // pseudo inverse			    }//.........这里部分代码省略.........
开发者ID:aaronta,项目名称:PowerGrid,代码行数:101,


示例10: objectivex

List objectivex(const arma::mat& transition, NumericVector emissionArray,                const arma::vec& init, IntegerVector obsArray, const arma::imat& ANZ,                IntegerVector emissNZ, const arma::ivec& INZ, const arma::ivec& nSymbols,                const arma::mat& coef, const arma::mat& X, arma::ivec& numberOfStates,                int threads) {  IntegerVector eDims = emissionArray.attr("dim"); //m,p,r  IntegerVector oDims = obsArray.attr("dim"); //k,n,r  arma::cube emission(emissionArray.begin(), eDims[0], eDims[1], eDims[2], false, true);  arma::icube obs(obsArray.begin(), oDims[0], oDims[1], oDims[2], false, true);  arma::icube BNZ(emissNZ.begin(), emission.n_rows, emission.n_cols - 1, emission.n_slices, false, true);  unsigned int q = coef.n_rows;  arma::vec grad(      arma::accu(ANZ) + arma::accu(BNZ) + arma::accu(INZ) + (numberOfStates.n_elem- 1) * q,      arma::fill::zeros);  arma::mat weights = exp(X * coef).t();  if (!weights.is_finite()) {    grad.fill(-arma::math::inf());    return List::create(Named("objective") = arma::math::inf(), Named("gradient") = wrap(grad));  }  weights.each_row() /= sum(weights, 0);  arma::mat initk(emission.n_rows, obs.n_slices);  for (unsigned int k = 0; k < obs.n_slices; k++) {    initk.col(k) = init % reparma(weights.col(k), numberOfStates);  }  arma::cube alpha(emission.n_rows, obs.n_cols, obs.n_slices); //m,n,k  arma::cube beta(emission.n_rows, obs.n_cols, obs.n_slices); //m,n,k  arma::mat scales(obs.n_cols, obs.n_slices); //m,n,k  arma::sp_mat sp_trans(transition);  internalForwardx(sp_trans.t(), emission, initk, obs, alpha, scales, threads);  if (!scales.is_finite()) {    grad.fill(-arma::math::inf());    return List::create(Named("objective") = arma::math::inf(), Named("gradient") = wrap(grad));  }  internalBackwardx(sp_trans, emission, obs, beta, scales, threads);  if (!beta.is_finite()) {    grad.fill(-arma::math::inf());    return List::create(Named("objective") = arma::math::inf(), Named("gradient") = wrap(grad));  }  arma::ivec cumsumstate = arma::cumsum(numberOfStates);  arma::mat gradmat(      arma::accu(ANZ) + arma::accu(BNZ) + arma::accu(INZ) + (numberOfStates.n_elem- 1) * q,      obs.n_slices, arma::fill::zeros);#pragma omp parallel for if(obs.n_slices >= threads) schedule(static) num_threads(threads)       /  default(none) shared(q, alpha, beta, scales, gradmat, nSymbols, ANZ, BNZ, INZ,          /          numberOfStates, cumsumstate, obs, init, initk, X, weights, transition, emission)    for (int k = 0; k < obs.n_slices; k++) {      int countgrad = 0;      // transitionMatrix      if (arma::accu(ANZ) > 0) {        for (int jj = 0; jj < numberOfStates.n_elem; jj++) {          arma::vec gradArow(numberOfStates(jj));          arma::mat gradA(numberOfStates(jj), numberOfStates(jj));          int ind_jj = cumsumstate(jj) - numberOfStates(jj);          for (int i = 0; i < numberOfStates(jj); i++) {            arma::uvec ind = arma::find(ANZ.row(ind_jj + i).subvec(ind_jj, cumsumstate(jj) - 1));            if (ind.n_elem > 0) {              gradArow.zeros();              gradA.eye();              gradA.each_row() -= transition.row(ind_jj + i).subvec(ind_jj, cumsumstate(jj) - 1);              gradA.each_col() %= transition.row(ind_jj + i).subvec(ind_jj, cumsumstate(jj) - 1).t();              for (int j = 0; j < numberOfStates(jj); j++) {                for (unsigned int t = 0; t < (obs.n_cols - 1); t++) {                  double tmp = alpha(ind_jj + i, t, k);                  for (unsigned int r = 0; r < obs.n_rows; r++) {                    tmp *= emission(ind_jj + j, obs(r, t + 1, k), r);                  }                  gradArow(j) += tmp * beta(ind_jj + j, t + 1, k) / scales(t + 1, k);                }              }              gradArow = gradA * gradArow;              gradmat.col(k).subvec(countgrad, countgrad + ind.n_elem - 1) = gradArow.rows(ind);              countgrad += ind.n_elem;            }          }        }      }      if (arma::accu(BNZ) > 0) {        // emissionMatrix        for (unsigned int r = 0; r < obs.n_rows; r++) {//.........这里部分代码省略.........
开发者ID:wondek,项目名称:seqHMM,代码行数:101,


示例11: rhierMnlRwMixture_rcpp_loop

//[[Rcpp::export]]List rhierMnlRwMixture_rcpp_loop(List const& lgtdata, mat const& Z,                                  vec const& deltabar, mat const& Ad, mat const& mubar, mat const& Amu,                                  double nu, mat const& V, double s,                                  int R, int keep, int nprint, bool drawdelta,                                  mat olddelta,  vec const& a, vec oldprob, mat oldbetas, vec ind, vec const& SignRes){// Wayne Taylor 10/01/2014  int nlgt = lgtdata.size();  int nvar = V.n_cols;  int nz = Z.n_cols;    mat rootpi, betabar, ucholinv, incroot;  int mkeep;  mnlMetropOnceOut metropout_struct;  List lgtdatai, nmix;    // convert List to std::vector of struct  std::vector<moments> lgtdata_vector;  moments lgtdatai_struct;  for (int lgt = 0; lgt<nlgt; lgt++){    lgtdatai = lgtdata[lgt];        lgtdatai_struct.y = as<vec>(lgtdatai["y"]);    lgtdatai_struct.X = as<mat>(lgtdatai["X"]);    lgtdatai_struct.hess = as<mat>(lgtdatai["hess"]);    lgtdata_vector.push_back(lgtdatai_struct);      }      // allocate space for draws  vec oldll = zeros<vec>(nlgt);  cube betadraw(nlgt, nvar, R/keep);  mat probdraw(R/keep, oldprob.size());  vec loglike(R/keep);  mat Deltadraw(1,1); if(drawdelta) Deltadraw.zeros(R/keep, nz*nvar);//enlarge Deltadraw only if the space is required  List compdraw(R/keep);    if (nprint>0) startMcmcTimer();      for (int rep = 0; rep<R; rep++){        //first draw comps,ind,p | {beta_i}, delta    // ind,p need initialization comps is drawn first in sub-Gibbs    List mgout;    if(drawdelta) {      olddelta.reshape(nvar,nz);      mgout = rmixGibbs (oldbetas-Z*trans(olddelta),mubar,Amu,nu,V,a,oldprob,ind);    } else {      mgout = rmixGibbs(oldbetas,mubar,Amu,nu,V,a,oldprob,ind);    }        List oldcomp = mgout["comps"];    oldprob = as<vec>(mgout["p"]); //conversion from Rcpp to Armadillo requires explict declaration of variable type using as<>    ind = as<vec>(mgout["z"]);        //now draw delta | {beta_i}, ind, comps    if(drawdelta) olddelta = drawDelta(Z,oldbetas,ind,oldcomp,deltabar,Ad);        //loop over all LGT equations drawing beta_i | ind[i],z[i,],mu[ind[i]],rooti[ind[i]]      for(int lgt = 0; lgt<nlgt; lgt++){        List oldcomplgt = oldcomp[ind[lgt]-1];        rootpi = as<mat>(oldcomplgt[1]);                //note: beta_i = Delta*z_i + u_i  Delta is nvar x nz        if(drawdelta){          olddelta.reshape(nvar,nz);          betabar = as<vec>(oldcomplgt[0])+olddelta*vectorise(Z(lgt,span::all));        } else {          betabar = as<vec>(oldcomplgt[0]);        }                if (rep == 0) oldll[lgt] = llmnl_con(vectorise(oldbetas(lgt,span::all)),lgtdata_vector[lgt].y,lgtdata_vector[lgt].X,SignRes);                //compute inc.root        ucholinv = solve(trimatu(chol(lgtdata_vector[lgt].hess+rootpi*trans(rootpi))), eye(nvar,nvar)); //trimatu interprets the matrix as upper triangular and makes solve more efficient        incroot = chol(ucholinv*trans(ucholinv));                        metropout_struct = mnlMetropOnce_con(lgtdata_vector[lgt].y,lgtdata_vector[lgt].X,vectorise(oldbetas(lgt,span::all)),                                         oldll[lgt],s,incroot,betabar,rootpi,SignRes);                  oldbetas(lgt,span::all) = trans(metropout_struct.betadraw);         oldll[lgt] = metropout_struct.oldll;        }          //print time to completion and draw # every nprint'th draw    if (nprint>0) if ((rep+1)%nprint==0) infoMcmcTimer(rep, R);        if((rep+1)%keep==0){      mkeep = (rep+1)/keep;      betadraw.slice(mkeep-1) = oldbetas;      probdraw(mkeep-1, span::all) = trans(oldprob);      loglike[mkeep-1] = sum(oldll);      if(drawdelta) Deltadraw(mkeep-1, span::all) = trans(vectorise(olddelta));      compdraw[mkeep-1] = oldcomp;    }  }    if (nprint>0) endMcmcTimer();  //.........这里部分代码省略.........
开发者ID:cran,项目名称:bayesm,代码行数:101,


示例12: main

int main(int argc, char *argv[]){  // Initialize POOMA and output stream, using Tester class  Pooma::initialize(argc, argv);  Pooma::Tester tester(argc, argv);  tester.out() << argv[0];  tester.out() << ": DynamicArray dynamic ops w/views." << std::endl;  tester.out() << "-------------------------------------------" << std::endl;  // Create an Interval object to create and index into an Array with  tester.out() << "Creating an Interval<1> object ..." << std::endl;  Interval<1> D1(3);  tester.out() << "D1 = " << D1 << std::endl;  // Create simple dynamic array.  tester.out() << "Creating DynamicArray using domain ..." << std::endl;  DynamicArray<int,Dynamic> a(D1);  tester.check(a.domain().size() == D1.size());  // Initialize dynamic array with scalar.  a = 3;  tester.out() << "Initialized DynamicArray to 3:" << std::endl;  tester.out() << "a = " << a << std::endl;  tester.check(sum(a) == (a.domain().size() * 3));  // Create elements in the array.  tester.out() << "Creating 2 elements at end of a ..." << std::endl;  a.create(2);  a.sync();  tester.out() << "a = " << a << std::endl;  tester.check(a.domain().size() == (D1.size() + 2));#if 0  // This test is bogous, as the comment in Engine/DynamicEngine.cpp::create()  // tells (the check for shared data is commented out):  //   "It would be nice to assert that no-one else is looking at the engine  //    when we perform dynamic operations, but all the particle swap operations  //    take place inside iterates which means the engine is a copy of another  //    engine, so the data is shared."  // Call a function which takes a view and the original DynamicArray  std::cout << "The program should abort in the next operation when it/n";  std::cout << "tries to create elements in an array with an existing view.";  std::cout << std::endl;  tester.out() << "Calling testview with a and a(1,3) ..." << std::endl;  tester.check(testview(tester, a, a(Interval<1>(1,3))));#endif  // Return resulting error code and exit; Tester will shut down POOMA.  tester.out() << "-------------------------------------------" << std::endl;  int retval = tester.results("DynamicArray dynamic ops w/views");  Pooma::finalize();  return retval;}
开发者ID:pathscale,项目名称:freepooma-testsuite,代码行数:61,


示例13: main

void main(){    int a = sum();    printf("The sum is %d/n", a);}
开发者ID:QuinceySun,项目名称:C,代码行数:4,


示例14: main

int main(int argc, char *argv[]){    #include "postProcess.H"    #include "setRootCase.H"    #include "createTime.H"    #include "createMesh.H"    #include "createControl.H"    #include "createFields.H"    #include "createFvOptions.H"    #include "initContinuityErrs.H"    #include "createTimeControls.H"    #include "compressibleCourantNo.H"    #include "setInitialDeltaT.H"    turbulence->validate();    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //    Info<< "/nStarting time loop/n" << endl;    while (runTime.run())    {        #include "readTimeControls.H"        #include "compressibleCourantNo.H"        #include "setDeltaT.H"        runTime++;        Info<< "Time = " << runTime.timeName() << nl << endl;        #include "rhoEqn.H"        // --- Pressure-velocity PIMPLE corrector loop        while (pimple.loop())        {            #include "UEqn.H"            #include "EEqn.H"            // --- Pressure corrector loop            while (pimple.correct())            {                #include "pEqn.H"            }            if (pimple.turbCorr())            {                turbulence->correct();            }        }        rho = thermo.rho();        runTime.write();        Info<< "ExecutionTime = " << runTime.elapsedCpuTime() << " s"  << "  ClockTime = " << runTime.elapsedClockTime() << " s"  << endl;        Info<< "Inflow      : "   << -1.0* sum(phi.boundaryField()[inlet])   <<" [kg/s]" << endl;        Info<< "Outflow     : "   <<       sum(phi.boundaryField()[outlet])  <<" [kg/s]" <<  endl;        Info<< "EnergyInflow  : " << -1.0* sum( phi.boundaryField()[inlet]  * ( thermo.he().boundaryField()[inlet]  + 0.5*magSqr(U.boundaryField()[inlet])  ) )   <<" [W]"  <<  endl;        Info<< "EnergyOutflow : " <<       sum( phi.boundaryField()[outlet] * ( thermo.he().boundaryField()[outlet] + 0.5*magSqr(U.boundaryField()[outlet]) ) )   <<" [W]"  <<  endl;           Info<< "EnergyBalance : " <<       sum( phi.boundaryField()[outlet] * ( thermo.he().boundaryField()[outlet] + 0.5*magSqr(U.boundaryField()[outlet]) ) )                                      +1.0* sum( phi.boundaryField()[inlet]  * ( thermo.he().boundaryField()[inlet]  + 0.5*magSqr(U.boundaryField()[inlet])  ) )   <<" [W]"  <<  endl;        Info<< "rho max/avg/min : " << gMax(thermo.rho()) << " " << gAverage(thermo.rho()) << " " << gMin(thermo.rho()) << endl;        Info<< "T   max/avg/min : " << gMax(thermo.T())   << " " << gAverage(thermo.T())   << " " << gMin(thermo.T())   << endl;        Info<< "P   max/avg/min : " << gMax(thermo.p())   << " " << gAverage(thermo.p())   << " " << gMin(thermo.p())   << endl;        Info<< "Prg max/avg/min : " << gMax(p_rgh)        << " " << gAverage(p_rgh)        << " " << gMin(p_rgh)        << endl;        Info<< "U   max/avg/min : " << max(U.component(2)).value() << " " <<  average(U.component(2)).value() << " " <<  min(U.component(2)).value() << endl;        Info<< "Prg max-min : " << gMax(p_rgh)   -  gMin(p_rgh)        << endl;        Info<< " " << endl;        Info<< "sngrad(rho) :" << gMax(snGradRho.boundaryField()[outlet]) << " " << gAverage(snGradRho.boundaryField()[outlet]) << " " << gMin(snGradRho.boundaryField()[outlet]) << endl;        Info<< " " << endl;    }    Info<< "End/n" << endl;    return 0;}
开发者ID:pupo162,项目名称:ThesisProject,代码行数:80,


示例15: main

Int_t main(Int_t argc, Char_t *argv[]){   ROOT::Mpi::TEnvironment env(argc, argv);   ROOT::Mpi::TIntraCommunicator world;   TVectorT<Double_t> mResult;   Double_t fScalarResult;   TVectorT<Double_t> v1(elements);   TVectorT<Double_t> v2(elements);   for (Int_t i = 0; i < elements; i++) {      v1[i] = i + (i + world.Size());      v2[i] = i * (i + world.Size());   }/////////////////////////////////////////////////Testing methdos with results in single Rank/////////////////////////////////////////////////   ROOT::Mpi::Math::TVectorTWrapper<Double_t> add(v1);   add.Addition(v2, root);   ROOT::Mpi::Math::TVectorTWrapper<Double_t> sub(v1);   sub.Subtraction(v2, root);   ROOT::Mpi::Math::TVectorTWrapper<Double_t> dot(v1);   dot.Dot(v2, root);   ROOT::Mpi::Math::TVectorTWrapper<Double_t> norm2Sqr(v1);   norm2Sqr.Norm2Sqr(root);   ROOT::Mpi::Math::TVectorTWrapper<Double_t> norm1(v1);   norm1.Norm1(root);   ROOT::Mpi::Math::TVectorTWrapper<Double_t> min(v1);   min.Min(root);   ROOT::Mpi::Math::TVectorTWrapper<Double_t> max(v1);   max.Max(root);   ROOT::Mpi::Math::TVectorTWrapper<Double_t> normalize(v1);   normalize.Normalize(root);   ROOT::Mpi::Math::TVectorTWrapper<Double_t> sum(v1);   sum.Sum(root);   if (world.Rank() == root) {      add.GetResult(mResult);      MpiCompareTVectorTest(mResult, v1 + v2, world.Rank(), "Vector Addition Single");      sub.GetResult(mResult);      MpiCompareTVectorTest(mResult, v1 - v2, world.Rank(), "Vector Subtraction Single");      dot.GetResult(fScalarResult);      MpiCompareTest(fScalarResult, Dot(v1, v2) , world.Rank(), "Vector Dot Product Single");      norm2Sqr.GetResult(fScalarResult);      MpiCompareTest(fScalarResult, v1.Norm2Sqr() , world.Rank(), "Vector Norm2Sqr Single");      norm1.GetResult(fScalarResult);      MpiCompareTest(fScalarResult, v1.Norm1() , world.Rank(), "Vector Norm1 Single");      min.GetResult(fScalarResult);      MpiCompareTest(fScalarResult, v1.Min() , world.Rank(), "Vector Min Single");      max.GetResult(fScalarResult);      MpiCompareTest(fScalarResult, v1.Max() , world.Rank(), "Vector Max Single");      normalize.GetResult(mResult);      MpiCompareTest(mResult.Norm2Sqr(), ((1 / TMath::Sqrt(v1.Norm2Sqr()))*v1).Norm2Sqr() , world.Rank(), "Vector Normalize Single");      sum.GetResult(fScalarResult);      MpiCompareTest(fScalarResult, v1.Sum(), world.Rank(), "Vector Sum Single");   }/////////////////////////////////////////////////Testing methdos with results in all ranks  /////////////////////////////////////////////////   ROOT::Mpi::Math::TVectorTWrapper<Double_t> addAll(v1);   add.Addition(v2);   ROOT::Mpi::Math::TVectorTWrapper<Double_t> subAll(v1);   sub.Subtraction(v2);   add.GetResult(mResult);   MpiCompareTVectorTest(mResult, v1 + v2, world.Rank(), "Vector Addition All");   sub.GetResult(mResult);   MpiCompareTVectorTest(mResult, v1 - v2, world.Rank(), "Vector Subtraction All");   ROOT::Mpi::Math::TVectorTWrapper<Double_t> dotAll(v1);   dotAll.Dot(v2);   dotAll.GetResult(fScalarResult);   MpiCompareTest(fScalarResult, Dot(v1, v2) , world.Rank(), "Vector Dot Product All");   ROOT::Mpi::Math::TVectorTWrapper<Double_t> norm2SqrAll(v2);   norm2SqrAll.Norm2Sqr();   norm2SqrAll.GetResult(fScalarResult);   MpiCompareTest(fScalarResult, v2.Norm2Sqr() , world.Rank(), "Vector Norm2Sqr All");//.........这里部分代码省略.........
开发者ID:omazapa,项目名称:RootMpi,代码行数:101,


示例16: pxsnsr

void pxsnsr(vector<vector<Point>> &contours, Mat &Seg_img_red, Mat &Seg_img_blue){	Rect *r = new Rect[contours.size()];   // 定义外接矩形数组	Mat obj_rec_thr = Mat::zeros(Seg_img_red.size(), CV_8UC3);	for (unsigned int i = 0; i < contours.size(); i++)	{		r[i] = boundingRect(Mat(contours[i]));// boundingRect获取这个外接矩形	}	/// 绘出轮廓及其凸包	Mat Seg_img_blue_hull(Seg_img_blue.size(), CV_8U, Scalar(0));	vector<vector<Point> >hull(contours.size());	for (unsigned int i = 0; i< contours.size(); i++)	{		convexHull(Mat(contours[i]), hull[i], false);		fillConvexPoly(Seg_img_blue_hull, &hull[i][0], hull[i].size(), Scalar(1));	}	erode(Seg_img_blue_hull, Seg_img_blue_hull, Mat(), Point(-1, -1), dilate_size);   // 对图像进行之前的膨胀恢复	Seg_img_blue_hull.convertTo(Seg_img_blue_hull, CV_32F);	imshow("Seg_img_blue _hull", Seg_img_blue_hull);	double Evaluation = 0;      // 对潜在目标的打分值初始化	double Evaluation_max = 0;   // 对潜在目标的打分最大值初始化	int index_best = -1;         // 最优轮廓标记 <注意此处初始值应为-1>	int index = 0;               // 轮廓标记	cout << contours.size() << endl;	vector<vector<Point>>::const_iterator itContours = contours.begin();	//for (; itContours != contours.end(); ++itContours)	while (itContours != contours.end())	{		Mat imageROI_red = Seg_img_red(cv::Rect(r[index].x, r[index].y, r[index].width, r[index].height));		Mat imageROI_blue = Seg_img_blue_hull(cv::Rect(r[index].x, r[index].y, r[index].width, r[index].height));		Mat imageROI_red_blue = imageROI_red + imageROI_blue;		threshold(imageROI_red_blue, imageROI_red_blue, 1, 1, THRESH_BINARY);   // 进行阈值分割(大于阈值1等于2时候取 1)		Scalar s1 = sum(imageROI_red_blue);		Scalar s2 = sum(imageROI_blue);		double sum_red = s1.val[0];    // 获取图像块包含在蓝色中的红色像素数量		double sum_blue = s2.val[0];    // 获取图像块中蓝色像素数量		double pixel_sum_rate = rate(sum_red, sum_blue);  // 计算图像块中红蓝像素的比例		cout << "sum_red:" << sum_red << "/t" << "," << "sum_blue:" << sum_blue << "/t";		cout << "pixel_sum_rate:" << pixel_sum_rate << endl;	    // 将红蓝像素比太低的连通域轮廓删除		if ((pixel_sum_rate < threshold_value_pixel_rate) || (sum_red < 12))  // 如当前轮廓不含一定的红色像素		{			itContours = contours.erase(itContours);  // 删除当前轮廓 <特别注意:删除当前轮廓后迭代器自动指向后一个>			index++;			continue;		}		else     // 如当前轮廓含一定的红色像素		{			int aaa = contours.size();  // 用于设置条件断点			Evaluation = sum_red;       // 目标轮廓简单评价值定义			if (Evaluation > Evaluation_max)			{				Evaluation_max = Evaluation;				index_best++;				cout << "index_best - " << index_best  << endl;			}			index++;			itContours++;  // 继续检索下一个轮廓 <此处必须要代码指定迭代器转向后一个轮廓>		}		}	int ttt = contours.size();    // 用于设置条件断点   // 如果仍然有大于一个潜在目标则选取最优的一个	if (ttt > 1) 	{		int index = 0;		vector<vector<Point>>::const_iterator itContours_2 = contours.begin();		while(itContours_2 != contours.end())		{			if (index != index_best)				itContours_2 = contours.erase(itContours_2);			else				++itContours_2; 			index++;		}	}	delete[] r;}
开发者ID:Limags,项目名称:ProjectCarTopLanding_ColorBased,代码行数:84,


示例17: arma_extra_debug_sigprint

inlineboolop_princomp::direct_princomp  (         Mat< std::complex<typename T1::pod_type> >&     coeff_out,         Mat< std::complex<typename T1::pod_type> >&     score_out,         Col<              typename T1::pod_type  >&     latent_out,         Col< std::complex<typename T1::pod_type> >&     tsquared_out,  const Base< std::complex<typename T1::pod_type>, T1 >& X,  const typename arma_cx_only<typename T1::elem_type>::result* junk  )  {  arma_extra_debug_sigprint();  arma_ignore(junk);    typedef typename T1::pod_type     T;  typedef          std::complex<T> eT;    const unwrap_check<T1> Y( X.get_ref(), score_out );  const Mat<eT>& in    = Y.M;    const uword n_rows = in.n_rows;  const uword n_cols = in.n_cols;    if(n_rows > 1) // more than one sample    {    // subtract the mean - use score_out as temporary matrix    score_out = in;  score_out.each_row() -= mean(in); 	      // singular value decomposition    Mat<eT> U;    Col< T> s;        const bool svd_ok = svd(U, s, coeff_out, score_out);         if(svd_ok == false)  { return false; }        // normalize the eigenvalues    s /= std::sqrt( double(n_rows - 1) );        // project the samples to the principals    score_out *= coeff_out;        if(n_rows <= n_cols) // number of samples is less than their dimensionality      {      score_out.cols(n_rows-1,n_cols-1).zeros();            Col<T> s_tmp = zeros< Col<T> >(n_cols);      s_tmp.rows(0,n_rows-2) = s.rows(0,n_rows-2);      s = s_tmp;                // compute the Hotelling's T-squared         s_tmp.rows(0,n_rows-2) = 1.0 / s_tmp.rows(0,n_rows-2);      const Mat<eT> S = score_out * diagmat(Col<T>(s_tmp));                           tsquared_out = sum(S%S,1);       }    else      {      // compute the Hotelling's T-squared         const Mat<eT> S = score_out * diagmat(Col<T>(T(1) / s));                           tsquared_out = sum(S%S,1);      }        // compute the eigenvalues of the principal vectors    latent_out = s%s;        }  else // 0 or 1 samples    {    coeff_out.eye(n_cols, n_cols);        score_out.copy_size(in);    score_out.zeros();          latent_out.set_size(n_cols);    latent_out.zeros();          tsquared_out.set_size(n_rows);    tsquared_out.zeros();    }    return true;  }
开发者ID:KaimingOuyang,项目名称:HPC-K-Means,代码行数:83,


示例18: cdfit_binomial_hsr

// Coordinate descent for logistic modelsRcppExport SEXP cdfit_binomial_hsr(SEXP X_, SEXP y_, SEXP row_idx_,                                    SEXP lambda_, SEXP nlambda_, SEXP lam_scale_,                                   SEXP lambda_min_, SEXP alpha_, SEXP user_, SEXP eps_,                                    SEXP max_iter_, SEXP multiplier_, SEXP dfmax_,                                    SEXP ncore_, SEXP warn_, SEXP verbose_) {  XPtr<BigMatrix> xMat(X_);  double *y = REAL(y_);  int *row_idx = INTEGER(row_idx_);  double lambda_min = REAL(lambda_min_)[0];  double alpha = REAL(alpha_)[0];  int n = Rf_length(row_idx_); // number of observations used for fitting model  int p = xMat->ncol();  int L = INTEGER(nlambda_)[0];  int lam_scale = INTEGER(lam_scale_)[0];  double eps = REAL(eps_)[0];  int max_iter = INTEGER(max_iter_)[0];  double *m = REAL(multiplier_);  int dfmax = INTEGER(dfmax_)[0];  int warn = INTEGER(warn_)[0];  int user = INTEGER(user_)[0];  int verbose = INTEGER(verbose_)[0];  NumericVector lambda(L);  NumericVector Dev(L);  IntegerVector iter(L);  IntegerVector n_reject(L);  NumericVector beta0(L);  NumericVector center(p);  NumericVector scale(p);  int p_keep = 0; // keep columns whose scale > 1e-6  int *p_keep_ptr = &p_keep;  vector<int> col_idx;  vector<double> z;  double lambda_max = 0.0;  double *lambda_max_ptr = &lambda_max;  int xmax_idx = 0;  int *xmax_ptr = &xmax_idx;    // set up omp  int useCores = INTEGER(ncore_)[0];#ifdef BIGLASSO_OMP_H_  int haveCores = omp_get_num_procs();  if(useCores < 1) {    useCores = haveCores;  }  omp_set_dynamic(0);  omp_set_num_threads(useCores);#endif    if (verbose) {    char buff1[100];    time_t now1 = time (0);    strftime (buff1, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now1));    Rprintf("/nPreprocessing start: %s/n", buff1);  }    // standardize: get center, scale; get p_keep_ptr, col_idx; get z, lambda_max, xmax_idx;  standardize_and_get_residual(center, scale, p_keep_ptr, col_idx, z, lambda_max_ptr, xmax_ptr, xMat,                                y, row_idx, lambda_min, alpha, n, p);  p = p_keep; // set p = p_keep, only loop over columns whose scale > 1e-6  if (verbose) {    char buff1[100];    time_t now1 = time (0);    strftime (buff1, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now1));    Rprintf("Preprocessing end: %s/n", buff1);    Rprintf("/n-----------------------------------------------/n");  }  arma::sp_mat beta = arma::sp_mat(p, L); //beta  double *a = Calloc(p, double); //Beta from previous iteration  double a0 = 0.0; //beta0 from previousiteration  double *w = Calloc(n, double);  double *s = Calloc(n, double); //y_i - pi_i  double *eta = Calloc(n, double);  int *e1 = Calloc(p, int); //ever-active set  int *e2 = Calloc(p, int); //strong set  double xwr, xwx, pi, u, v, cutoff, l1, l2, shift, si;  double max_update, update, thresh; // for convergence check  int i, j, jj, l, violations, lstart;    double ybar = sum(y, n) / n;  a0 = beta0[0] = log(ybar / (1-ybar));  double nullDev = 0;  double *r = Calloc(n, double);  for (i = 0; i < n; i++) {    r[i] = y[i];    nullDev = nullDev - y[i]*log(ybar) - (1-y[i])*log(1-ybar);    s[i] = y[i] - ybar;    eta[i] = a0;  }  thresh = eps * nullDev / n;    double sumS = sum(s, n); // temp result sum of s  double sumWResid = 0.0; // temp result: sum of w * r  // set up lambda  if (user == 0) {    if (lam_scale) { // set up lambda, equally spaced on log scale//.........这里部分代码省略.........
开发者ID:YaohuiZeng,项目名称:biglasso,代码行数:101,


示例19: sum

int sum(int idx) {    return idx >= 1 ? tree[idx] + sum(idx - lowbit(idx)) : 0;}
开发者ID:ice1000,项目名称:OI-codes,代码行数:3,


示例20: sum

float sum(float a[], int n){ if (n == 0) return a[0];  else return a[n] + sum(a, n-1);}
开发者ID:alfaha,项目名称:procpp,代码行数:4,


示例21: sum

/*Funktionsdefinitionen*/int sum(int n){    if(n>0)    return n + sum(n-1);    return 0;}
开发者ID:Heyduhuu,项目名称:Level-26,代码行数:7,


示例22: strlen

match *find_best_match(const adapter_array *aa, const char *read,                       float *p_quals, float prior, float p_match, int min_l) {  /*   Take an adapter array, and check the read against all   adapters. Brute force string matching is used. This is to avoid   approximate matching algorithms which required an a priori   specified number mismatches.  */  match *best_match=NULL;  int i, shift, max_shift, found_contam=0;  int *best_arr=NULL, best_adapter=0, best_length=0, best_shift=0, best_score=INT_MIN;  int curr_score, *curr_arr=NULL;  size_t al, rl = strlen(read);  posterior_set *ps=NULL;  float *best_p_quals=NULL;  max_shift = rl - min_l;  for (shift = 0; shift < max_shift; shift++) {    for (i = 0; i < aa->n; i++) {      if (min_l >= aa->adapters[i].length) {        fprintf(stderr, "Minimum match length (option -n) greater than or " /                "equal to length of adapter./n");        exit(EXIT_FAILURE);      }      al = min(aa->adapters[i].length, rl - shift);      curr_arr = score_sequence(&(read)[shift], (aa->adapters[i]).seq, al);      curr_score = sum(curr_arr, al);      if (curr_score > best_score) {        best_score = curr_score;        best_length = al;        best_shift = shift;        best_p_quals = &(p_quals)[shift];        best_arr = curr_arr;        best_adapter = i;        ps = posterior(best_arr, best_p_quals, prior, 0.25, best_length);        found_contam = ps->is_contam;        if (found_contam) {          break;        } else {          free(ps);           ps=NULL;          free(best_arr);        }      } else free(curr_arr);    }    if (found_contam)      break;  }    if (!found_contam) /* no match found */    return NULL;    /* save this match */  best_match = xmalloc(sizeof(match));  best_match->match = best_arr;  best_match->shift = best_shift;  best_match->length = best_length;  best_match->ps = ps;  best_match->score = best_score;  best_match->adapter_index = best_adapter;  best_match->p_quals = best_p_quals;  best_match->match_pos = calloc(best_length, sizeof(int));  for (i = 0; i < best_length; i++)    best_match->match_pos[i] = best_match->match[i] == MATCH_SCORE;  return best_match;}
开发者ID:Bioinformaticsnl,项目名称:scythe,代码行数:68,


示例23: sum

unsigned sum(unsigned n) {  if (n)    return n + sum(n - 1);  else    return 0;}
开发者ID:JasonGross,项目名称:c-semantics,代码行数:6,


示例24: lower_bound

void lower_bound(vrp_problem *vrp, lb_params *lb_par, heurs *lh,                 int ub, int jobs, int *tids, int *sent){    int s_bufid, dummy;    int y, i, alpha, interval;    int *sorted_demand, trials;    int m1, numroutes = vrp->numroutes, capacity = vrp->capacity;    if (!lb_par->lower_bound)        return;    if (vrp->par.verbosity > 1)        printf("/nNow beginning lower bounding ..../n/n");    /*Calculate m1 = maximum # of single vehicle routes*/    sorted_demand  = (int *) calloc (vrp->vertnum, sizeof(int));    memcpy (sorted_demand, vrp->demand, vrp->vertnum*sizeof(int));    qsort (sorted_demand+1, vrp->vertnum-1, sizeof(int), intcompar);    for (m1 = 0;; m1++)        if (!(capacity*(numroutes-m1-1) >=                sum(sorted_demand, m1+2, vrp->vertnum-1)))            break;    trials = (lb_par->lower_bound)*(numroutes-m1);    lh->tids = tids;    lh->jobs = jobs;    if (!jobs) {        fprintf(stderr, "/nNo jobs started .... /n/n");        return;    }    else if (vrp->par.verbosity >2)        printf("/n%i jobs started .../n/n", jobs);    /*-----------------------------------------------------------------------*/    |                  Broadcast data to the lower bounding procedure         |    /*-----------------------------------------------------------------------*/    for(i=0; i<trials; i++) {        s_bufid = init_send(DataInPlace);        send_int_array(&dummy, 1);        send_msg(tids[i%jobs], MST);        sent[i%jobs]++;        broadcast(vrp, tids+(i%jobs), 1);        s_bufid = init_send(DataInPlace);        send_int_array(&numroutes, 1);        send_int_array(&ub, 1);        send_int_array(&lb_par->lb_max_iter, 1);        send_int_array(&m1, 1);        send_msg(tids[i%jobs],  VRP_LB_DATA);    }    interval = lb_par->lb_penalty_mult/lb_par->lower_bound;    for (i=trials-1, y = m1, alpha = lb_par->lb_penalty_mult; i>=0; i--, y++) {        s_bufid = init_send(DataInPlace);        send_int_array(&y, 1);        send_int_array(&alpha, 1);        send_msg(tids[i%jobs], VRP_LB_DATA2);        if (y == numroutes) {            y = m1-1;            alpha -= interval;        }    }    freebuf(s_bufid);    FREE(sorted_demand);}
开发者ID:vladchimescu,项目名称:lpsymphony,代码行数:73,


示例25: main

int main() {  return sum(10);}
开发者ID:JasonGross,项目名称:c-semantics,代码行数:3,


示例26: test_boost_point_arithmetic

int test_boost_point_arithmetic(point_type const& left, point_type const& right){  int error_count = 0;  point_type a(left);  point_type b = right;  point_type sum(a);  boost::geometry::add_point(sum, b);  std::cout << "Point addition: a + b = "            << to_string(sum) << "/n";  error_count += test_expected_value<0>(sum, left.template get<0>() + right.template get<0>());  error_count += test_expected_value<1>(sum, left.template get<1>() + right.template get<1>());  point_type difference(a);  boost::geometry::subtract_point(difference, b);  std::cout << "Point subtraction: a - b = "            << to_string(difference) << "/n";  error_count += test_expected_value<0>(difference, left.template get<0>() - right.template get<0>());  error_count += test_expected_value<1>(difference, left.template get<1>() - right.template get<1>());  point_type pointwise_product(a);  boost::geometry::multiply_point(pointwise_product, b);  std::cout << "Pointwise product: "            << to_string(pointwise_product) << "/n";  error_count += test_expected_value<0>(pointwise_product, left.template get<0>() * right.template get<0>());  error_count += test_expected_value<1>(pointwise_product, left.template get<1>() * right.template get<1>());  point_type pointwise_quotient(a);  boost::geometry::divide_point(pointwise_quotient, b);  std::cout << "Pointwise quotient: "            << to_string(pointwise_quotient) << "/n";  error_count += test_expected_value<0>(pointwise_quotient, left.template get<0>() / right.template get<0>());  error_count += test_expected_value<1>(pointwise_quotient, left.template get<1>() / right.template get<1>());  point_type scalar_product(a);  boost::geometry::multiply_value(scalar_product, 2);  std::cout << "Scalar product: "            << to_string(scalar_product) << "/n";  error_count += test_expected_value<0>(scalar_product, left.template get<0>() * 2);  error_count += test_expected_value<1>(scalar_product, left.template get<1>() * 2);  point_type scalar_quotient(a);  boost::geometry::divide_value(scalar_quotient, 2);  std::cout << "Scalar quotient: "            << to_string(scalar_quotient) << "/n";  error_count += test_expected_value<0>(scalar_quotient, left.template get<0>() / 2);  error_count += test_expected_value<1>(scalar_quotient, left.template get<1>() / 2);  double distance = boost::geometry::distance(left, right);//  double other_distance = left.distance_to(right);  std::cout << "Geographic distance between points: " << distance << "/n";  return error_count;}
开发者ID:atwilso,项目名称:tracktable,代码行数:61,


示例27: depthSum

 int depthSum(vector<NestedInteger>& nestedList) {     return sum(nestedList,1); }
开发者ID:quitz,项目名称:myleetcode,代码行数:3,


示例28: mean

T mean(const libNumerics::vector<T>& v){	return (T) ( sum(v) / v.nrow() );}
开发者ID:flm8620,项目名称:Calib3DTools,代码行数:4,


示例29: result

 result_type result(Args const &args) const {     extractor<SumFeature> sum;     return numeric::fdiv(sum(args), count(args)); }
开发者ID:c-zheng,项目名称:autowiring,代码行数:5,



注:本文中的sum函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ summarize函数代码示例
C++ suite_create函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。