::testing::AssertionResult array_are_close(X const &x1, Y const &y1,double precision = 1.e-10) { triqs::arrays::array<typename X::value_type, X::rank> x = x1; triqs::arrays::array<typename X::value_type, X::rank> y = y1; if (x.domain() != y.domain()) return ::testing::AssertionFailure() << "Comparing two arrays of different size " << "\n X = "<< x << "\n Y = "<< y; if (max_element(abs(x - y)) < precision) return ::testing::AssertionSuccess(); else return ::testing::AssertionFailure() << "max_element(abs(x-y)) = " << max_element(abs(x - y)) << "\n X = "<< x << "\n Y = "<< y; }
float Detector::sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) { // Mild variant of Bresenham's algorithm; // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm bool steep = abs(toY - fromY) > abs(toX - fromX); if (steep) { int temp = fromX; fromX = fromY; fromY = temp; temp = toX; toX = toY; toY = temp; } int dx = abs(toX - fromX); int dy = abs(toY - fromY); int error = -dx >> 1; int xstep = fromX < toX ? 1 : -1; int ystep = fromY < toY ? 1 : -1; // In black pixels, looking for white, first or second time. int state = 0; // Loop up until x == toX, but not beyond int xLimit = toX + xstep; for (int x = fromX, y = fromY; x != xLimit; x += xstep) { int realX = steep ? y : x; int realY = steep ? x : y; // Does current pixel mean we have moved white to black or vice versa? if (!((state == 1) ^ image_->get(realX, realY))) { if (state == 2) { return MathUtils::distance(x, y, fromX, fromY); } state++; } error += dy; if (error > 0) { if (y == toY) { break; } y += ystep; error -= dx; } } // Found black-white-black; give the benefit of the doubt that the next pixel outside the image // is "white" so this last point at (toX+xStep,toY) is the right ending. This is really a // small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this. if (state == 2) { return MathUtils::distance(toX + xstep, toY, fromX, fromY); } // else we didn't find even black-white-black; no estimate is really possible return nan(); }
int gcd_iterative(int a, int b) { a = abs(a); b = abs(b); while (a && b) { if (a > b) a -= b; else b -= a; } return a+b; // at least one of these will be 0 }
int gcd(int a, int b) { a = abs(a); b = abs(b); if (a == 0 || b == 0) return a+b; if (a > b) return gcd(a-b, b); return gcd(a, b-a); }
void operator()(T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4) { using std::abs; t1 = adapted_pow(abs(t2), -beta1/(m_steps + 1)) * adapted_pow(abs(t3), -beta2/(m_steps + 1)) * adapted_pow(abs(t4), -beta3/(m_steps + 1)) * adapted_pow(abs(dt1/dt2), -alpha1/(m_steps + 1))* adapted_pow(abs(dt2/dt3), -alpha2/(m_steps + 1)); t1 = 1/t1; };
float CollisionDetector::collideByDist(Vector3 object, Vector3 target) { //A diffInX = abs(target.x - object.x); //B diffInZ = abs(target.z - object.z); //TOA CAH SOH A square + B square = C square dist = sqrt(diffInX * diffInX + diffInZ * diffInZ); return dist; }
static bool roughly_equal_to (const T &lhs, const T &rhs) { assert(!std::numeric_limits<T>::is_integer); using std::max; using std::pow; using std::abs; // last two digits of largest number const T epsilon = max(abs(lhs), abs(rhs)) * pow(T(2), -T(std::numeric_limits<T>::digits-2)); assert(epsilon >= T(0)); assert(abs(lhs) + epsilon >= lhs); assert(abs(rhs) + epsilon >= rhs); //std::cerr << lhs << " " << rhs << " " << epsilon << " " << std::numeric_limits<T>::epsilon() << std::endl; return abs(rhs-lhs) <= epsilon; // "<=", should also work for zero }
bool GameState::canMove(const pos& i_s,const pos& j_s,const pos& i_f,const pos& j_f) const { if(!gameStarted) { DEBUG("game hasn't started"); return false; } //are we moving pieces? if(i_s < 0 || j_s < 0 || i_s > 7 || j_s > 7 || i_f < 0 || j_f < 0 || i_f > 7 || j_f > 7) { DEBUG("not in board"); return false; } //is this inside the board? if(!piece(i_s,j_s)) { DEBUG("no piece"); return false; } if((piece(i_s,j_s) & COLOR_MASK) != toMove) { DEBUG("wrong color"); return false; } //is it this person's turn? if(piece(i_f,j_f)!=0) { DEBUG("moving to occupied"); return false; } // is there something occupying the spot to move to? if(frozen(i_s,j_s)) { DEBUG("frozen"); return false; } if(abs(i_f-i_s)+abs(j_f-j_s)!=1) { DEBUG("too far"); return false; } if(isPawn(piece(i_s,j_s))) { if((i_f-i_s) == (getColor(piece(i_s,j_s)) * 2 - 1)) { DEBUG("pawns don't move back"); return false; } //pawns going in the right direction? } return true; }
void test_runge() { std::cout << "Testing interpolation of Runge's 1/(1+25x^2) function using barycentric interpolation on type " << boost::typeindex::type_id<Real>().pretty_name() << "\n"; std::mt19937 gen(8); boost::random::uniform_real_distribution<Real> dis(0.005f, 0.01f); std::vector<Real> x(100); std::vector<Real> y(100); x[0] = -2; y[0] = 1/(1+25*x[0]*x[0]); for (size_t i = 1; i < x.size(); ++i) { x[i] = x[i-1] + dis(gen); y[i] = 1/(1+25*x[i]*x[i]); } boost::math::barycentric_rational<Real> interpolator(x.data(), y.data(), y.size(), 5); for (size_t i = 0; i < x.size(); ++i) { Real t = x[i]; Real z = interpolator(t); BOOST_CHECK_CLOSE(z, y[i], 0.03); Real z_prime = interpolator.prime(t); Real num = -50*t; Real denom = (1+25*t*t)*(1+25*t*t); if (abs(num/denom) > 0.00001) { BOOST_CHECK_CLOSE_FRACTION(z_prime, num/denom, 0.03); } } Real tol = 0.0001; for (size_t i = 0; i < x.size(); ++i) { Real t = x[i] + dis(gen); Real z = interpolator(t); BOOST_CHECK_CLOSE(z, 1/(1+25*t*t), tol); Real z_prime = interpolator.prime(t); Real num = -50*t; Real denom = (1+25*t*t)*(1+25*t*t); Real runge_prime = num/denom; if (abs(runge_prime) > 0 && abs(z_prime - runge_prime)/abs(runge_prime) > tol) { std::cout << "Error too high for t = " << t << " which is a distance " << t - x[i] << " from node " << i << "/" << x.size() << " associated with data (" << x[i] << ", " << y[i] << ")\n"; BOOST_CHECK_CLOSE_FRACTION(z_prime, runge_prime, tol); } } }
//added by ali 24 Jul 2011 Float analytic_straight_velocity2::operator() (const point & x) { point u; assert(x[1]<=1.); if (abs(x[1]) <= _ys) { u[0]=_Bn/(2.*_ys)*sqr(1.-_ys); } else { u[0]=_Bn/(2.*_ys)*(sqr(1.-_ys)-sqr(abs(x[1])-_ys)); } return u[0]; }
/** * @brief This defines the functionpart of the whole thing. Needed for rheolef::interpolate * * Let \f$ x = (x_0,x_1)\f$ \f[ u(x) = (u_0(x_1), 0) \f] \f{eqnarray} \begin{cases} \frac{f}{2} \left[ |y_w|-\frac{Bn}{|f|} \right]^2 & x_1 \in [\pm Bn / |f|] \\ \frac{f}{2} \left[ \left( |y_w| - \frac{Bn}{|f|} \right )^2- \left( |y| - \frac{Bn}{|f|} \right )^2 \right] & |x_1| > Bn / |f| \end{cases} \f} * @param x point position * @return analytic velocity */ point analytic_straight_velocity ::operator() (const point & x) { point u; Float yc = _Bn / abs(_dpdx); if (abs(x[1]) <= yc) { u[0]=(_dpdx/2)*sqr(abs(_ywall)-yc); } else { u[0]=(_dpdx/2)*(sqr(abs(_ywall)-yc)-sqr(abs(x[1])-yc)); } return u; }
void Elevator::setDestinationBasedOnRiders() // reset toFloor based on riders' destinations { if (hasRiders()==true) { setDestination(&(r[0].getDestination())); } for (int i=0; i<r.size(); i++) //1) Query each rider in vector { if (abs(toFloor->getLocation() - location) > abs( r[i].getDestination().getLocation() - location)) { setDestination(&(r[i].getDestination())); } } }
size_t seqElements(const af_seq &seq) { size_t out = 0; if (seq.step > DBL_MIN) { out = ((seq.end - seq.begin) / abs(seq.step)) + 1; } else if (seq.step < -DBL_MIN) { out = ((seq.begin - seq.end) / abs(seq.step)) + 1; } else { out = numeric_limits<size_t>::max(); } return out; }
//##################################################################### // Function Line_Search_Quadratic_Golden_Section //##################################################################### template<class T> bool LINE_SEARCH<T>:: Line_Search_Golden_Section(NONLINEAR_FUNCTION<T(T)>& F,T a,T b,T& x,int max_iterations,T interval_tolerance) const { PHYSBAM_ASSERT(a<=b); T tau=(T).5*(sqrt((T)5)-1),m=a+tau*(b-a),t; BRACKET s={a,m,b,F(a),F(m),F(b)}; int i; interval_tolerance*=abs(s.a)+abs(s.b); for(i=1;i<=max_iterations;i++){ if(abs(s.b-s.a)<interval_tolerance) break; t=s.a+s.b-s.m; Update_Interval(s,t,F(t));} x=Best_Value(s); return i<=max_iterations; }
vector<uint> matrix_utils::remove_linear_dependence_rows(Matrix &matrix) { vector<uint> removed_rows; //need to prevent swap whole columns, just swap indexes vector<uint> columns(matrix[0].size()); for (uint i = 0; i != columns.size(); i++) { columns[i] = i; } Matrix temp_matrix; temp_matrix.reserve(matrix.size()); for (uint i = 0; i != matrix.size(); i++) { temp_matrix.push_back(vector<double>(matrix[i].begin(), matrix[i].end())); } for (uint i = 0; i != temp_matrix.size(); i++) { uint index_max = i; for (uint j = i + 1; j != temp_matrix[0].size(); j++) { if (abs(temp_matrix[i][columns[index_max]]) < abs(temp_matrix[i][columns[j]])) { index_max = j; } } if (index_max != i) { uint tmp = columns[i]; columns[i] = columns[index_max]; columns[index_max] = tmp; } index_max = columns[i]; if (abs(temp_matrix[i][index_max]) < 1e-7) { temp_matrix.erase(temp_matrix.begin() + i); matrix.erase(matrix.begin() + i); removed_rows.push_back(i); i--; continue; } double divisor = temp_matrix[i][index_max]; for (uint k = 0; k != temp_matrix[0].size(); k++) { temp_matrix[i][k] /= divisor; } for (uint j = i + 1; j != temp_matrix.size(); j++) { double multiplier = -temp_matrix[j][index_max]; for (uint k = 0; k != temp_matrix[0].size(); k++) { temp_matrix[j][k] += temp_matrix[i][k] * multiplier; } } } return removed_rows; }
int test_cp( const std::string& species_name, unsigned int species, Scalar cp_exact, Scalar T, const Antioch::CEAEvaluator<Scalar>& thermo ) { using std::abs; int return_flag = 0; const Scalar tol = std::numeric_limits<Scalar>::epsilon() * 5; typedef typename Antioch::template TempCache<Scalar> Cache; const Scalar cp = thermo.cp(Cache(T), species); if( abs( (cp_exact - cp)/cp_exact ) > tol ) { std::cerr << "Error: Mismatch in species specific heat." << "\nspecies = " << species_name << "\ncp = " << cp << "\ncp_exact = " << cp_exact << "\ndifference = " << (cp_exact - cp) << "\ntolerance = " << tol << "\nT = " << T << std::endl; return_flag = 1; } return return_flag; }
void run_test(int dim, int num_elements) { using std::abs; typedef typename internal::traits<MatrixType>::Scalar Scalar; typedef Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixX; typedef Matrix<Scalar, Eigen::Dynamic, 1> VectorX; // MUST be positive because in any other case det(cR_t) may become negative for // odd dimensions! const Scalar c = abs(internal::random<Scalar>()); MatrixX R = randMatrixSpecialUnitary<Scalar>(dim); VectorX t = Scalar(50)*VectorX::Random(dim,1); MatrixX cR_t = MatrixX::Identity(dim+1,dim+1); cR_t.block(0,0,dim,dim) = c*R; cR_t.block(0,dim,dim,1) = t; MatrixX src = MatrixX::Random(dim+1, num_elements); src.row(dim) = Matrix<Scalar, 1, Dynamic>::Constant(num_elements, Scalar(1)); MatrixX dst = cR_t*src; MatrixX cR_t_umeyama = umeyama(src.block(0,0,dim,num_elements), dst.block(0,0,dim,num_elements)); const Scalar error = ( cR_t_umeyama*src - dst ).norm() / dst.norm(); VERIFY(error < Scalar(40)*std::numeric_limits<Scalar>::epsilon()); }
void run_fixed_size_test(int num_elements) { using std::abs; typedef Matrix<Scalar, Dimension+1, Dynamic> MatrixX; typedef Matrix<Scalar, Dimension+1, Dimension+1> HomMatrix; typedef Matrix<Scalar, Dimension, Dimension> FixedMatrix; typedef Matrix<Scalar, Dimension, 1> FixedVector; const int dim = Dimension; // MUST be positive because in any other case det(cR_t) may become negative for // odd dimensions! const Scalar c = abs(internal::random<Scalar>()); FixedMatrix R = randMatrixSpecialUnitary<Scalar>(dim); FixedVector t = Scalar(50)*FixedVector::Random(dim,1); HomMatrix cR_t = HomMatrix::Identity(dim+1,dim+1); cR_t.block(0,0,dim,dim) = c*R; cR_t.block(0,dim,dim,1) = t; MatrixX src = MatrixX::Random(dim+1, num_elements); src.row(dim) = Matrix<Scalar, 1, Dynamic>::Constant(num_elements, Scalar(1)); MatrixX dst = cR_t*src; Block<MatrixX, Dimension, Dynamic> src_block(src,0,0,dim,num_elements); Block<MatrixX, Dimension, Dynamic> dst_block(dst,0,0,dim,num_elements); HomMatrix cR_t_umeyama = umeyama(src_block, dst_block); const Scalar error = ( cR_t_umeyama*src - dst ).array().square().sum(); VERIFY(error < Scalar(10)*std::numeric_limits<Scalar>::epsilon()); }
inline double rng_hcauchy(double sigma, bool& throw_warning) { if (ISNAN(sigma) || sigma <= 0.0) { throw_warning = true; return NA_REAL; } return abs(R::rcauchy(0.0, sigma)); }
// Sets the initial step size automatically. The function and initial // y data must be set for this to work. f, t0 and y0 must be set // before you can call this method. Also sets the max dt to the same // value. void RKF45::set_dt0() { // locals double yprime = norm(f(t0,y0)); double y = norm(y0); double length_scale; if ( debug_level >= 3) { cout << "y = " << y << "\n" << "yprime = " << yprime << endl; } // y/y' = <change in t> * y/<change in y>. A good approximation of dt0. length_scale = y/yprime; if ( debug_level >= 3 ) { cout << "length scale = " << length_scale << endl; } dt0 = abs(get_relative_error_factor() * length_scale); if ( debug_level >= 1 ) { cout << "dt0 = " << dt0 << endl; // cout << "Max step size: " << get_max_dt() << endl; } // dt0 must be a finite, positive number. If it's zero or NaN, make // it sqrt(machine epsilon). if ( !(dt0 > 0) ) { if ( debug_level >= 1 ) { cout << "WARNING: dt0 non-finite. Setting it to the default minimum dt" << endl; } set_dt0(default_min_dt()); } else { set_dt0(dt0); } }
static typename Function::value_type derivative( const Function &f, const typename Function::value_type &x) { typedef typename Function::value_type value_type; typedef typename ValueType<value_type>::value_type T; // Find minimum value for h const std::size_t digits = std::numeric_limits<T>::digits; const std::size_t bits = CHAR_BIT * sizeof(std::size_t); const std::size_t N = std::min(digits, bits-1); assert(1ul << N); typename Function::value_type x_min_h, x_plus_h, deriv; for (std::size_t i = 0; i < x.size(); ++i) { using std::abs; const T h = (x[i] != 0) ? abs(x[i]) / T(1ul << (1ul+N/2)) : T(1) / T(1ul << (1ul+N/2)); assert(h > 0); x_min_h = x; x_min_h[i] -= h; x_plus_h = x; x_plus_h[i] += h; deriv[i] = (f(x_plus_h) - f(x_min_h)) / (h+h); } return deriv; }
AntennaId User::get_smoothed_antenna(time_duration time) { unsigned next_event_minute = to_minutes(time); float smoothed_lat = 0; float smoothed_lon = 0; float weight_sum = 0; for(unsigned i = 0; i < events.size(); i++) { Event* event = events.at(i); unsigned event_minute = to_minutes(event->time.time_of_day()); Antenna* antenna = AntennaModel::find_antenna_by_id(event->antenna_id); int diff = abs(event_minute - next_event_minute); if (diff > 12 * 60) { diff = 24 * 60 - diff; } float weight = pdf(normal(0, AntennaModel::timestep), diff); weight_sum += weight; smoothed_lat += weight * antenna->get_latitude(); smoothed_lon += weight * antenna->get_longitude(); } smoothed_lat /= weight_sum; smoothed_lon /= weight_sum; return AntennaModel::find_nearest_antenna(smoothed_lat, smoothed_lon)->get_id(); }
array mandelbrot(const array &in, int iter, float maxval) { array C = in; array Z = C; array mag = constant(0, C.dims()); for (int ii = 1; ii < iter; ii++) { // Do the calculation Z = Z * Z + C; // Get indices where abs(Z) crosses maxval array cond = (abs(Z) > maxval).as(f32); mag = af::max(mag, cond * ii); // If abs(Z) cross maxval, turn off those locations C = C * (1 - cond); Z = Z * (1 - cond); // Ensuring the JIT does not become too large af::eval(C, Z); mag.eval(); } // Normalize return mag / maxval; }
int tester() { using std::abs; int return_flag = 0; const Scalar tol = (std::numeric_limits<Scalar>::epsilon() * 10 < 5e-17)?5e-17: std::numeric_limits<Scalar>::epsilon() * 10; const Scalar eps_kb = 97.53L; // N2 value const Scalar z_298 = 4.0L; // N2 value Antioch::RotationalRelaxation<Scalar> rot(z_298,eps_kb); for(Scalar T = 300.1; T <= 2500.1; T += 10.) { Scalar z = rot(T); Scalar z_exact = Z(T,eps_kb,z_298); if( abs( (z - z_exact)/z_exact) > tol ) { std::cout << std::scientific << std::setprecision(16) << "Error: Mismatch in rotational relaxation values." << std::endl << " T = " << T << std::endl << " z = " << z << std::endl << " z_exact = " << z_exact << std::endl << " relative error = " << std::abs(z - z_exact)/z_exact << std::endl << " tolerance = " << tol << std::endl; return_flag = 1; } } return return_flag; }
int main( int argc , char *argv[] ) { using namespace std; cout.precision( 14 ); auto f = []( auto x ) { return exp( - x * x ) - 0.5; }; auto df = []( auto x ) { return -2.0 * x * exp( -x * x ); }; { // example 1 without ranges double x = 1.0; double root = newton( x , f , df ); cout << "Solution: " << root << " " << f( root ) << endl; } { // example 2 with ranges double x = 1.0; auto r = make_newton_range( x , f , df ); auto r2 = ranges::view::take_while( r , [f]( auto x ) { using std::abs; return abs( f(x) ) > 1.0e-12; } ); ranges::for_each( r2 , [f]( auto x ) { cout << x << " " << f(x) << "\n"; } ); cout << "Solution: " << r.x() << " " << r.y() << endl; } return 0; }
bool FinderPatternFinder::haveMultiplyConfirmedCenters() { int confirmedCount = 0; float totalModuleSize = 0.0f; size_t max = possibleCenters_.size(); for (size_t i = 0; i < max; i++) { Ref<FinderPattern> pattern = possibleCenters_[i]; if (pattern->getCount() >= CENTER_QUORUM) { confirmedCount++; totalModuleSize += pattern->getEstimatedModuleSize(); } } if (confirmedCount < 3) { return false; } // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" // and that we need to keep looking. We detect this by asking if the estimated module sizes // vary too much. We arbitrarily say that when the total deviation from average exceeds // 5% of the total module size estimates, it's too much. float average = totalModuleSize / max; float totalDeviation = 0.0f; for (size_t i = 0; i < max; i++) { Ref<FinderPattern> pattern = possibleCenters_[i]; totalDeviation += abs(pattern->getEstimatedModuleSize() - average); } return totalDeviation <= 0.05f * totalModuleSize; }
int test_h( const std::string& species_name, unsigned int species, Scalar h_exact, Scalar T, const Antioch::CEAEvaluator<Scalar>& thermo ) { using std::abs; int return_flag = 0; const Scalar tol = std::numeric_limits<Scalar>::epsilon() * 5; typedef typename Antioch::template TempCache<Scalar> Cache; const Scalar h = thermo.h(Cache(T), species); if( abs( (h_exact - h)/h_exact ) > tol ) { std::cerr << std::scientific << std::setprecision(16) << "Error: Mismatch in species total enthalpy." << "\nspecies = " << species_name << "\nh = " << h << "\nh_exact = " << h_exact << "\ndifference = " << (h_exact - h) << "\ntolerance = " << tol << "\nT = " << T << std::endl; return_flag = 1; } return return_flag; }
/** * The GARS precision required to meet a given geographic resolution. * * @param[in] res the minimum of resolution in latitude and longitude * (degrees). * @return GARS precision. * * The returned length is in the range [0, 2]. **********************************************************************/ static int Precision(real res) { using std::abs; res = abs(res); for (int prec = 0; prec < maxprec_; ++prec) if (Resolution(prec) <= res) return prec; return maxprec_; }
T log1p_imp(T const & x, const Policy& pol, const mpl::int_<0>&) { // The function returns the natural logarithm of 1 + x. typedef typename tools::promote_args<T>::type result_type; BOOST_MATH_STD_USING using std::abs; static const char* function = "boost::math::log1p<%1%>(%1%)"; if(x < -1) return policies::raise_domain_error<T>( function, "log1p(x) requires x > -1, but got x = %1%.", x, pol); if(x == -1) return -policies::raise_overflow_error<T>( function, 0, pol); result_type a = abs(result_type(x)); if(a > result_type(0.5L)) return log(1 + result_type(x)); // Note that without numeric_limits specialisation support, // epsilon just returns zero, and our "optimisation" will always fail: if(a < tools::epsilon<result_type>()) return x; detail::log1p_series<result_type> s(x); boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>(); #if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582)) result_type result = tools::sum_series(s, policies::digits<result_type, Policy>(), max_iter); #else result_type zero = 0; result_type result = tools::sum_series(s, policies::digits<result_type, Policy>(), max_iter, zero); #endif policies::check_series_iterations(function, max_iter, pol); return result; }
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { int lena = 0; int lenb = 0; ListNode* tempa = headA; ListNode* tempb = headB; while (tempa) { lena++; tempa = tempa->next; } while (tempb) { lenb++; tempb = tempb->next; } int diff = abs(lena - lenb); while (diff--) { if (lena > lenb) { headA = headA->next; } else { headB = headB->next; } } while (headA and headB) { if (headA == headB) return headA; headA = headA->next; headB = headB->next; } return NULL; }