void GeomData::calculate_CDL() { int i,dom, row; const int* indices = NULL; // elements' coordinates const double* coords[4] = {NULL,NULL,NULL,NULL}; // vector created over elements' edges int num_edges = 3*(dim-1); double* vectors[6]; for (i=0; i<num_edges; i++) { vectors[i] = new double[dim]; } // indices to automate edge vectors creation int idx[6][2] = {{0,1},{1,2},{2,0},{0,3},{1,3},{2,3}}; // Auxiliary variable int pos = dim+1; int k = 0; for (dom=0; dom<_ndom; dom++) { int nelements = numDomElem[dom]; // loop over domains' elements for (row=0; row<nelements; row++) { getElement(dom,row,indices); // get vertices coordinates for (i=0; i<pos; i++) { getCoordinates(indices[i+pos],coords[i]); } // create edge vectors for (i=0; i<num_edges; i++) { const double* vtx1 = coords[ idx[i][0] ]; const double* vtx2 = coords[ idx[i][1] ]; for (int j=0; j<dim; j++) { (vectors[i])[j] = vtx1[j] - vtx2[j]; } } // vectors lengths summation for (i=0; i<num_edges; i++) { elem_CDL[k] = sqrt( inner_product(vectors[i],vectors[i],dim) ); } // take average lenght elem_CDL[k] /= pos; k++; } } for (i=0; i<num_edges; i++) { delete[] vectors[i]; vectors[i] = 0; } }
int main(void) { double a[N]={1, 2, 3}, b[N]={1, 2, 3}, *p = a, *q = b; printf("%f\n", inner_product(p, q, N)); return 0; }
void innerproductTest() { std::cout << "inner product ... "; std::vector<std::complex<double>> x = {1,2,3,4}; std::vector<std::complex<double>> y = {1,std::complex<double>(0,1),1,std::complex<double>(0,1)}; std::complex<double> expected = std::complex<double>(4,-6); bool pass = std::abs(expected - inner_product(x,y)) < 1e-8; if(pass) std::cout << "PASS" << std::endl; else std::cout << "FAIL" << std::endl; }
/*solution saved in b */ void conjugate_gradient(sparse_matrix A, double *b, int size) { double *x, *r, *p, *Ap, *aux, rnew, rold, alfa; int i; x = (double*) malloc(size*sizeof(double)); r = (double*) malloc(size*sizeof(double)); p = (double*) malloc(size*sizeof(double)); Ap = (double*) malloc(size*sizeof(double)); aux = (double*) malloc(size*sizeof(double)); for (i = 0; i < size; i ++) { x[i] = 0; r[i] = b[i]; p[i] = b[i]; } rold = inner_product(r, r, size); /* result of operations from all void functions used here are stored in the last argument */ while (1) { matrix_vector_product(A, p, Ap); alfa = rold / inner_product(p, Ap, size); /*step length*/ vector_scalar_product(p, alfa, size, aux); vector_sum(x, aux, size, x); vector_scalar_product(Ap, alfa, size, aux); vector_subtraction(r, aux, size, r); rnew = inner_product(r, r, size); if (sqrt(rnew) < E) break; vector_scalar_product(p, rnew / rold, size, p); vector_sum(p, r, size, p); rold = rnew; } for (i = 0; i < size; i ++) { b[i] = x[i]; } free(x); free(r); free(p); free(Ap); free(aux); }
double sPredModule::solveCoef(double wrss) { Rcpp::NumericMatrix cc = d_fac.solve(CHOLMOD_L, d_fac.solve(CHOLMOD_P, d_Vtr)); double ans = sqrt(inner_product(cc.begin(), cc.end(), cc.begin(), double())/wrss); Rcpp::NumericMatrix bb = d_fac.solve(CHOLMOD_Pt, d_fac.solve(CHOLMOD_Lt, cc)); copy(bb.begin(), bb.end(), d_coef.begin()); return ans; }
/** * Solve (V'V)coef = Vtr for coef. * * @param wrss weighted residual sum of squares (defaults to 1.) * @return convergence criterion */ double dPredModule::solveCoef(double wrss) { if (d_coef.size() == 0) return 0.; copy(d_Vtr.begin(), d_Vtr.end(), d_coef.begin()); d_fac.update(d_V); d_fac.dtrtrs('T', d_coef.begin()); // solve R'c = Vtr double ans = sqrt(inner_product(d_coef.begin(), d_coef.end(), d_coef.begin(), double())/wrss); d_fac.dtrtrs('N', d_coef.begin()); // solve R beta = c; return ans; }
double blok::deviation(){ double total = std::accumulate(content.begin(), content.end(), 0); double mean = total / content.size(); vector<unsigned int> zero_mean( content ); transform( zero_mean.begin(), zero_mean.end(), zero_mean.begin(),bind2nd( minus<double>(), mean ) ); double deviation = inner_product( zero_mean.begin(),zero_mean.end(), zero_mean.begin(), 0.0 ); deviation = sqrt( deviation / ( content.size() - 1 ) ); return deviation; }
int main(int argc, char *argv[]) { double a[5] = {1,2,3,4,5}; double b[5] = {1,2,3,4,5}; printf("The sum of the product of the two arrays is %f\n", inner_product(a,b,5)); getchar(); getchar(); return 0; }
const vector DOK::conjugate_gradient(const vector& b, vector& x, size_t max_iter, double eps) const { // vector x; vector r = b - *this * x; vector p = r; double rsold = inner_product(r, r); size_t i; for(i = 0; i < max_iter && rsold > eps; ++i) { vector Ap = *this * p; double alpha = rsold / inner_product(p, Ap); x += alpha * p; r -= alpha * Ap; double rsnew = inner_product(r, r); p *= rsnew / rsold; p += r; rsold = rsnew; } if (i == max_iter) printf("exce\n"); return x; }
REAL CMetaModel::Test( const REAL* prInputs, const REAL* prOutputs, int count ) { vector<REAL> vcOutputs( GetOutputs() ); //calculate the error function under the current weight REAL rError = 0; for( int i=0; i<count; i++ ){ Predict( prInputs + i*GetInputs(), &vcOutputs[0] ); rError += inner_product( vcOutputs.begin(), vcOutputs.end(), prOutputs, 0.0, plus<REAL>(), minus_pow<REAL>(2.0) ) / GetOutputs(); } return rError/count; }
matrix1d calc_mean_var(matrix1d points) { double sum = 0, mu = 0, sigma_sq = 0, sdev = 0, dev = 0; sum = accumulate(points.begin(), points.end(), 0.0); mu = sum / points.size(); sdev = inner_product(points.begin(), points.end(), points.begin(), 0.0); sigma_sq = sdev/points.size() - mu*mu; matrix1d m_and_v; m_and_v.push_back(mu); m_and_v.push_back(sigma_sq); return m_and_v; }
void CRegionalMetaModel::ComputeDistance( vector< vector<REAL> >& vcInputs, vector<REAL>& vcPtCen, dist_pair_vector& vcDists ) { int nsize = vcInputs.size(); vcDists.clear(); vcDists.reserve( nsize ); for( int i=0; i<nsize; i++ ){ REAL dist = inner_product( vcInputs[i].begin(), vcInputs[i].end(), vcPtCen.begin(), 0.0, plus<REAL>(), diff_sqr<REAL>() ); dist = sqrt(dist); vcDists.push_back( dist_pair(i, dist) ); } sort( vcDists.begin(), vcDists.end(), op_dist_less() ); }
static float _diff_disc_formfactor(Vertex *p, Element *e_src, Vertex *p_disc, float area, Vertex *normal, long process_id) { Vertex vec_sd ; float dist_sq ; float fnorm ; float cos_s, cos_d, angle_factor ; vec_sd.x = p_disc->x - p->x ; vec_sd.y = p_disc->y - p->y ; vec_sd.z = p_disc->z - p->z ; dist_sq = vec_sd.x*vec_sd.x + vec_sd.y*vec_sd.y + vec_sd.z*vec_sd.z ; fnorm = area / ((float)M_PI * dist_sq + area) ; /* (2) Now, consider angle to the other patch from the normal. */ normalize_vector( &vec_sd, &vec_sd ) ; cos_s = inner_product( &vec_sd, &e_src->patch->plane_equ.n ) ; cos_d = -inner_product( &vec_sd, normal ) ; angle_factor = cos_s * cos_d ; /* Return the form factor */ return( fnorm * angle_factor ) ; }
Field<dim> lbfgs( const Functional& F, const Gradient& dF, const Field<dim>& phi_start, const unsigned int m, const double eps ) { double cost_old = std::numeric_limits<double>::infinity(); double cost = F(phi_start); Field<dim> phi0(phi_start); DualField<dim> df0 = dF(phi_start); const auto& discretization = phi0.get_discretization(); // Create vectors for storing the last few differences of the guesses, // differences of the gradients, and the inverses of their inner products std::vector<Field<dim>> s(m, Field<dim>(discretization)); std::vector<DualField<dim>> y(m, DualField<dim>(discretization)); std::vector<double> rho(m); // As an initial guess, we will assume that the Hessian inverse is a // multiple of the inverse of the mass matrix double gamma = 1.0; for (unsigned int k = 0; std::abs(cost_old - cost)/cost > eps; ++k) { const Field<dim> p = -lbfgs_two_loop(df0, s, y, rho, gamma); const Field<dim> phi1 = line_search(F, phi0, df0, p, eps); const DualField<dim> df1 = dF(phi1); s[0] = phi1 - phi0; y[0] = df1 - df0; const double cos_angle = inner_product(y[0], s[0]); const double norm_y = norm(y[0]); rho[0] = 1.0 / cos_angle; gamma = cos_angle / (norm_y * norm_y); std::rotate(s.begin(), s.begin() + 1, s.end()); std::rotate(y.begin(), y.begin() + 1, y.end()); std::rotate(rho.begin(), rho.begin() + 1, rho.end()); phi0 = phi1; df0 = df1; cost_old = cost; cost = F(phi0); } return phi0; }
inline Real mixed_product (const T1& v1, const T2& v2, const T3& v3, T4& temp) { // sanity checks cf3_assert(v1.size() == 3); cf3_assert(v2.size() == 3); cf3_assert(v3.size() == 3); cf3_assert(temp.size() == 3); cross_product(v1, v2, temp); return inner_product(v3, temp); }
// calculate linear interpolation of relative frequency estimates based on joint count and marginal counts //unused for now; enable in config? double LinearInterpolationFromCounts(vector<float> &joint_counts, vector<float> &marginals, vector<float> &multimodelweights) { vector<float> p(marginals.size()); for (size_t i=0; i < marginals.size(); i++) { if (marginals[i] != 0) { p[i] = joint_counts[i]/marginals[i]; } } double p_weighted = inner_product(p.begin(), p.end(), multimodelweights.begin(), 0.0); return p_weighted; }
void update_vector(double *b, double **Q, int rows, int columns, double *gamma) { int i, k; double *u, factor; u = malloc((rows) * sizeof(double)); for (k = 0; k < columns; k ++) { u[0] = 1; for (i = k + 1; i < rows; i ++) u[i - k] = Q[i][k]; factor = gamma[k]*inner_product(u, b, rows, k); for (i = k; i < rows; i ++) b[i] -= factor*u[i - k]; } free(u); }
//数值算法 void stl_numeric_algo(){ double array[] = {-2,2,4,4,5}; double array1[] = {2,3,4,5,6}; vector<double> a(array,array + sizeof(array)/sizeof(double)); vector<double> b(array1,array1 + sizeof(array1)/sizeof(double)); vector<double> result(10); cout<<"accumulate func: "<<accumulate(a.begin(), a.end(), 0, minus<double>())<<endl; cout<<"inner product func: "<<inner_product(a.begin(),a.end(),b.begin(),0.0,plus<double>(),multiplies<double>())<<endl; adjacent_difference(a.begin(),a.end(),result.begin()); cout<<"adjacent_difference : "<<result<<endl; partial_sum(result.begin(),result.end(),result.begin()); cout<<"partial_sum : "<<result<<endl; ostream_iterator<double> myout(cout, " "); copy(result.begin(), result.end(), myout); }
//------------------------------------------------------------------------------------ void calcShadowMatrix(const float groundplane[], const float lightpos[], float shadowMatrix[]) { float dot = inner_product(groundplane, groundplane+4, lightpos, 0.f); for(int y = 0; y < 4;++y) { for(int x = 0; x < 4; ++x) { shadowMatrix[y*4+x] = - groundplane[y]*lightpos[x]; if (x == y) shadowMatrix[y*4+x] += dot; } } }
virtual double energy( const typename domain_space_type::element_type & de, const typename dual_image_space_type::element_type & ie ) const { auto matrix = M_backend->newMatrix( _test=this->dualImageSpace(), _trial=this->domainSpace(), _pattern=M_pattern ); sumAllMatrices( matrix, true ); matrix->close(); vector_ptrtype _v1( M_backend->newVector( _test=de.functionSpace() ) ); *_v1 = de;_v1->close(); vector_ptrtype _v2( M_backend->newVector( _test=ie.functionSpace() ) ); *_v2 = ie; vector_ptrtype _v3( M_backend->newVector( _test=ie.functionSpace() ) ); M_backend->prod( matrix, _v1, _v3 ); return inner_product( _v2, _v3 ); }
int main(int argc, char** argv) { _(); vec_as_string(); vec_fill_and_remove(); vec_not1(); vec_bind2nd(); verse_iterator_find_if(); reverse_iterator_find_if(); inner_product(); descending_sort(); deque_push_erase(); deque_invalidate(); deque_assign(); return EXIT_SUCCESS; }
double correlation(const Cit &start1, const Cit &end1, const Cit &start2) { const auto end2 = start2 + distance(start1, end1); const auto mean1 = accumulate(start1, end1, 0.0) / distance(start1, end1); const auto mean2 = accumulate(start2, end2, 0.0) / distance(start2, end2); const auto numerator = inner_product( start1, end1, start2, 0.0, plus<double>(), [=](double a, double b) noexcept { return (a - mean1) * (b - mean2); }); const auto squaredError1 = accumulate(start1, end1, 0.0, [mean1](double sum, double x) noexcept { return sum + (x - mean1) * (x - mean1); }); const auto squaredError2 = accumulate(start2, end2, 0.0, [mean2](double sum, double x) noexcept { return sum + (x - mean2) * (x - mean2); }); const auto denominator = sqrt(squaredError1) * sqrt(squaredError2); return numerator / denominator; }
int main(void) { double a[N], b[N], n = 0, sum, *p; printf("Enter %d elements for array A: ", N); for (p = a; p < a + N; p++){ scanf("%lf", p); n++; } printf("Enter %d elements for array B: ", N); for (p = b; p < b + N; p++){ scanf("%lf", p); } sum = inner_product(a, b, n); printf("%lf\n", sum); return 0; }
double entropy(const Matrix3_3 &matrix) { array<double, 3> H; for (int i = 0; i < 3; i++) { const auto _row = row(matrix, i); array<double, 3> multipliedByLog; transform(begin(_row), end(_row), begin(multipliedByLog), [](double x) { return x * log(x) / log(2); }); H[i] = accumulate(begin(multipliedByLog), end(multipliedByLog), 0.0); } array<double, 3> P; for (int i = 0; i < 3; i++) { const auto column = col(matrix, i); P[i] = accumulate(begin(column), end(column), 0.0); } return -inner_product(begin(P), end(P), begin(H), 0.0); }
void polarization(double * function_1, double left_endpoint, double right_endpoint, int num_points, double * integral){ int flag = 1; int ii; double beta = 1.0; //defining the size of the interval(s). note this is num_points+1 because the interval can't start at zero. double h = (right_endpoint - left_endpoint)/(num_points+1.0); //allocating memory for new vector for X * some arbitrary vector. double * psi_hat; psi_hat = (double*)malloc(num_points*sizeof(double)); X_operator(beta, num_points, right_endpoint, left_endpoint, psi_hat, function_1, flag); inner_product(&function_1[0], &psi_hat[0], left_endpoint, right_endpoint, num_points, integral); free(psi_hat); }
void Do_Statistics( std::vector < std::vector <double>> data) { std::cout << "Doing Stats" << std::endl; std::string rchange = "flat"; std::ofstream statisticsOutputFile; statisticsOutputFile.open("Statistic_Output_" + rchange +".txt"); std::vector<int> binCount; std::vector<double> typeAverage; std::vector<int> weights; double maxCellNumber = data.at(0).at(1); for(int i =0; i < data.size(); i++){ weights.push_back(i); } //Type average is the dot product between the 0:number_muts //Bin count is counting the non zero bins for(int rows=0; rows < data.size(); rows++){ auto countt = std::count(data.at(rows).begin()+1, data.at(rows).end(), 0); binCount.push_back(data.at(rows).size() - 1 - countt); double dotProduct = inner_product(data.at(rows).begin()+1, data.at(rows).end(), weights.begin(), 0)/maxCellNumber; typeAverage.push_back(dotProduct); } //wirting to a file the r$i is for ggplot for(int j = 0; j < binCount.size(); j++){ statisticsOutputFile << data.at(j).at(0) << "\t" << typeAverage.at(j) << "\t" << binCount.at(j) << "\t" << rchange << std::endl; } statisticsOutputFile.close(); }
//the compute distance is undertaken an overhaull. I prefere to compute the probability instead of the //euclidean distance. void CRegionalMetaModel::ComputeDistance( vector< vector<REAL> >& mxInputs, vector<REAL>& vcPtCen, dist_pair_vector& vcDists ) { int rows = mxInputs.size(); int cols = mxInputs.front().size(); /*compute the center of the hyperecllipsoid*/ vector<REAL> center(cols, 0.0); for( vector< vector<REAL> >::iterator iter=mxInputs.begin(); iter!=mxInputs.end(); iter++ ) transform( center.begin(), center.end(), iter->begin(), center.begin(), plus<REAL>() ); transform( center.begin(), center.end(), center.begin(), bind2nd(divides<REAL>(), rows) ); /*compute the standard deviation of the columns*/ //compute sum( (x-u)*(x-u) ) for each column vector<REAL> stds(cols, 0.0); for( int i=0; i<rows; i++ ) for( int j=0; j<cols; j++ )stds[j] += sqr( center[j] - mxInputs[i][j] ); //using compose function operator to do "sqrt( sum/N-1 )" transform( stds.begin(), stds.end(), stds.begin(), compose_f_gx( ptr_fun(sqrt), bind2nd(divides<double>(), rows-1) ) ); /* compute the radius */ REAL alpha = 1.5; vector<REAL> radius(cols); transform( stds.begin(), stds.end(), radius.begin(), bind2nd(multiplies<REAL>(), alpha) ); for( i=0; i<cols; i++ )if( radius[i]<=0.0001 )radius[i]=0.0001; /* compute the distance for each point */ vector<REAL> radius_sqr(cols); transform( radius.begin(), radius.end(), radius.begin(), radius_sqr.begin(), multiplies<REAL>() ); for( i=0; i<rows; i++ ){ vector<REAL> temp(cols); transform( mxInputs[i].begin(), mxInputs[i].end(), center.begin(), temp.begin(), diff_sqr<REAL>() ); REAL distance = inner_product( temp.begin(), temp.end(), radius_sqr.begin(), 0.0, plus<REAL>(), divides<REAL>() ); vcDists.push_back( dist_pair(i, distance) ); } sort( vcDists.begin(), vcDists.end(), op_dist_less() ); }
static void set_init_cond_magnt(double *B) { for (int i = 0; i < N0; i++) for (int k = 0; k < N2-1; k++) for (int j = 0; j < N1-1; j++) { const struct vector pos = {(double)i, (double)j+0.5, (double)k+0.5}; // othnormal component const struct vector p_xyz = othnormal_position<c>(pos); const struct vector b_xyz = init_cond_magnt(p_xyz); // physical component vertical with the grid // Covariant basic vector is a member of coordinate transformation // matrix here. const double b = inner_product( covariant_basic_vector<c, c>(pos), b_xyz); // Convert to physical length. *magnt_flux<N1, N2>(i, j, k, B) = b * vector_length(contravariant_basic_vector<c, c>(pos)); } }
static void set_init_cond_elect(double *E) { for (int i = 0; i < N0-1; i++) for (int k = 0; k < N2; k++) for (int j = 0; j < N1; j++) { const struct vector pos = {(double)i+0.5, (double)j, (double)k}; // othnormal component const struct vector p_xyz = othnormal_position<c>(pos); const struct vector e_xyz = init_cond_elect(p_xyz); // unphysical components along to the grid. // Contravariant basic vector is a member of coordinate transformation // matrix here. const double e = inner_product( contravariant_basic_vector<c, c>(pos), e_xyz); // Convert to physical length. *elect_field<N1, N2>(i, j, k, E) = e * vector_length(covariant_basic_vector<c, c>(pos)); } }
// calculate a unit vector normal to each external face void GeomData::calculate_extFaceVersor(pMesh theMesh) { int row = 0; double dij[3], norma; int ndom = getNumDomains(); for (int i=0; i<ndom; i++) { FIter fit = M_faceIter(theMesh); while ( pFace face = FIter_next(fit) ) { // only external boudanry faces if (F_numRegions(face)==1) { if (faceBelongToDomain(face,domainList[i])) { getDij(face,domainList[i],dij); norma = sqrt( inner_product(dij,dij,3) ); versor_ExtBdryElem[0].setValue(row,0,dij[0]/norma); versor_ExtBdryElem[0].setValue(row,1,dij[1]/norma); versor_ExtBdryElem[0].setValue(row,2,dij[2]/norma); row++; } } } FIter_delete(fit); } }