Example #1
0
    void alpha2sd (double alpha,
            double &mu_sd, double &lambda_sd, double &weight_sd) const
    {
        using std::sqrt;

        alpha = alpha < 0.05 ? 0.05 : alpha;
        mu_sd     = 0.15 / alpha;
        lambda_sd = (1 + sqrt(1.0 / alpha)) * 0.15;
        weight_sd = (1 + sqrt(1.0 / alpha)) * 0.2;
    }
Example #2
0
int main()
{
  using std::sqrt;
  MatrixXd A(3,3);
  A << 0.5*sqrt(2), -0.5*sqrt(2), 0,
       0.5*sqrt(2),  0.5*sqrt(2), 0,
       0,            0,           1;
  std::cout << "The matrix A is:\n" << A << "\n\n";
  std::cout << "The matrix logarithm of A is:\n" << A.log() << "\n";
}
    result_type operator()()
    {
#ifndef BOOST_NO_STDC_NAMESPACE
        using std::sqrt;
#endif
        result_type u = _rng();
        if( u <= q1 )
            return _a + p1*sqrt(u);
        else
            return _c - d3*sqrt(d2*u-d1);
    }
void DeviceCollector::onOrientationData(myo::Myo* myo, uint64_t timestamp, const myo::Quaternion<float>& quat)
{
    Device * device = findDevice(myo);
    if ( device ) {
        using std::atan2;
        using std::asin;
        using std::sqrt;
        
        // Calculate Euler angles (roll, pitch, and yaw) from the unit quaternion.
        float roll = atan2(2.0f * (quat.w() * quat.x() + quat.y() * quat.z()),
                           1.0f - 2.0f * (quat.x() * quat.x() + quat.y() * quat.y()));
        float pitch = asin(2.0f * (quat.w() * quat.y() - quat.z() * quat.x()));
        float yaw = atan2(2.0f * (quat.w() * quat.z() + quat.x() * quat.y()),
                          1.0f - 2.0f * (quat.y() * quat.y() + quat.z() * quat.z()));
        
        device->q = quat;//set(quat.x(), quat.y(), quat.z(), quat.w());
        
        
        device->roll = roll;
        device->pitch = pitch;
        device->yaw = yaw;
        
        
        // Convert the floating point angles in radians to a scale from 0 to 20.
        device->roll_w = static_cast<int>((roll + (float)M_PI)/(M_PI * 2.0f) * 18);
        device->pitch_w = static_cast<int>((pitch + (float)M_PI/2.0f)/M_PI * 18);
        device->yaw_w = static_cast<int>((yaw + (float)M_PI)/(M_PI * 2.0f) * 18);
        
        float gyoro_g = sqrt(device->gyro.x()*device->gyro.x() + device->gyro.y()*device->gyro.y() + device->gyro.z()*device->gyro.z());
        float g = sqrt(device->accel.x()*device->accel.x() + device->accel.y()*device->accel.y() + device->accel.z()*device->accel.z());
        //            cout << gyoro_g << endl;
        //            cout << g << endl;
        if ( gyoro_g <= 0.2 ) device->gravity = g;
        
//        Quaternion4f q;
//        q = quat;
//        //.set(quat.x(), quat.z(), quat.y(), quat.w());
//        Vector3f linear_accel;
//        ofMatrix4x4 mat;
//        mat.translate(ofVec3f(0,device->gravity,0));
//        mat.rotate(q);
//        ofVec3f trans = mat.getTranslation();
//        
//        linear_accel = device->getAccel();
//        linear_accel.x = linear_accel.x - trans.x;
//        linear_accel.y = linear_accel.y - trans.z;
//        linear_accel.z = linear_accel.z - trans.y;
//
//        device->linear_accel.set(linear_accel);
        //            cout << device->getAccel() << endl;
        //            cout << mat.getTranslation() << endl;
        //            cout << linear_accel << endl;
    }
}
float cpp_schafferf7(double* vals, long sz){
  //The schafferf7 function! It does other things!
  double tot = 0.0, norm = 1.0/sz, si, adjusted_val, adjusted_next = vals[0] / 512.0 * 100.0;
  for(long i = 0; i < (sz - 1); ++i){
    adjusted_val = adjusted_next;
    adjusted_next = vals[i + 1] / 512.0 * 100.0;
    si = sqrt(pow(adjusted_val, 2) + pow(adjusted_next, 2));
    tot += pow(norm * sqrt(si) * (sin(50 * pow(si, 0.20)) + 1), 2);
  }
  return tot;
}
Example #6
0
//! Compute Prandtl-Meyer function.
double computePrandtlMeyerFunction( double machNumber, double ratioOfSpecificHeats )
{
    // Declare local variables.
    // Declare Mach number squared.
    double machNumberSquared_ = pow( machNumber, 2.0 );

    // Return value of Prandtl-Meyer function.
    return sqrt ( ( ratioOfSpecificHeats + 1.0 ) / ( ratioOfSpecificHeats - 1.0 ) )
            * atan ( sqrt ( ( ratioOfSpecificHeats - 1.0 ) / ( ratioOfSpecificHeats + 1.0 )
                            * ( machNumberSquared_ - 1.0 ) ) )
            - atan( sqrt ( machNumberSquared_ - 1.0 ) );
}
void test_integrals()
{
  // Integral of the Lambert W function:
  // https://en.wikipedia.org/wiki/Lambert_W_function
  using boost::math::quadrature::tanh_sinh;
  using boost::math::quadrature::exp_sinh;
  // file:///I:/modular-boost/libs/math/doc/html/math_toolkit/quadrature/double_exponential/de_tanh_sinh.html
  using std::sqrt;

  std::cout << "Integration of type " << typeid(Real).name()  << std::endl;

  Real tol = std::numeric_limits<Real>::epsilon();
  { //  // Integrate for function lambert_W0(z);
    tanh_sinh<Real> ts;
    Real a = 0;
    Real b = boost::math::constants::e<Real>();
    auto f = [](Real z)->Real
    {
      return lambert_w0<Real>(z);
    };
    Real z = ts.integrate(f, a, b); // OK without any decltype(f)
    BOOST_CHECK_CLOSE_FRACTION(z, boost::math::constants::e<Real>() - 1, tol);
  }
  {
    // Integrate for function lambert_W0(z/(z sqrt(z)).
    exp_sinh<Real> es;
    auto f = [](Real z)->Real
    {
      return lambert_w0<Real>(z)/(z * sqrt(z));
    };
    Real z = es.integrate(f); // OK
    BOOST_CHECK_CLOSE_FRACTION(z, 2 * boost::math::constants::root_two_pi<Real>(), tol);
  }
  {
    // Integrate for function lambert_W0(1/z^2).
    exp_sinh<Real> es;
    //const Real sqrt_min = sqrt(boost::math::tools::min_value<Real>()); // 1.08420217e-19 fo 32-bit float.
    // error C3493: 'sqrt_min' cannot be implicitly captured because no default capture mode has been specified
    auto f = [](Real z)->Real
    {
      if (z <= sqrt(boost::math::tools::min_value<Real>()) )
      { // Too small would underflow z * z and divide by zero to overflow 1/z^2 for lambert_w0 z parameter.
        return static_cast<Real>(0);
      }
      else
      {
        return lambert_w0<Real>(1 / (z * z)); // warning C4756: overflow in constant arithmetic, even though cannot happen.
      }
    };
    Real z = es.integrate(f);
    BOOST_CHECK_CLOSE_FRACTION(z, boost::math::constants::root_two_pi<Real>(), tol);
  }
} // template<class Real> void test_integrals()
Example #8
0
//! Compute pressure coefficient using the van Dyke unified method.
double computeVanDykeUnifiedPressureCoefficient(
    double inclinationAngle, double machNumber,
    double ratioOfSpecificHeats, int type )
{
    // Declare and initialize local variables and pre-compute for efficiency.
    double ratioOfSpecificHeatsTerm_ = ( ratioOfSpecificHeats + 1.0 ) / 2.0;
    double machNumberTerm_ = sqrt( pow( machNumber , 2.0 ) - 1.0 );
    double exponent_ = 2.0 * ratioOfSpecificHeats / ( ratioOfSpecificHeats - 1.0 );

    // Declare and initialize value.
    double pressureCoefficient_ = 0.0;

    // Calculate compression pressure coefficient.
    if ( inclinationAngle >= 0.0 && type == 1 )
    {
        pressureCoefficient_ = pow( inclinationAngle, 2.0 )
                * ( ratioOfSpecificHeatsTerm_
                    + sqrt( pow( ratioOfSpecificHeatsTerm_, 2.0 )
                            + 4.0 / ( pow(  inclinationAngle * machNumberTerm_, 2.0 ) ) ) );
    }

    // Calculate expansion pressure coefficient.
    else if ( inclinationAngle < 0.0 && type == -1 )
    {
        // Calculate vacuum pressure coefficient.
        double vacuumPressureCoefficient_ = computeVacuumPressureCoefficient(
                    machNumber, ratioOfSpecificHeats );

        // Check to see if pressure coefficient will be lower than vacuum case,
        // set to vacuum if so.
        if ( -1.0 * inclinationAngle * machNumberTerm_
             > 2.0 / ( ratioOfSpecificHeats - 1.0 ) )
        {
            pressureCoefficient_ = vacuumPressureCoefficient_;
        }
        else
        {
            pressureCoefficient_
                    = 2.0 / ( ratioOfSpecificHeats * pow( machNumberTerm_, 2.0 ) )
                    * ( pow( 1.0 - ( ratioOfSpecificHeats - 1.0 ) / 2.0
                             * - 1.0 * inclinationAngle * machNumberTerm_, exponent_ ) - 1.0 );

            if ( pressureCoefficient_ < vacuumPressureCoefficient_ )
            {
                pressureCoefficient_ = vacuumPressureCoefficient_;
            }
        }
    }

    // Return pressure coefficient.
    return pressureCoefficient_;
}
Example #9
0
TEST(AgradFwdSqrt, FvarVar_2ndDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using std::sqrt;

  fvar<var> x(1.5,1.3);
  fvar<var> a = sqrt(x);

  AVEC y = createAVEC(x.val_);
  VEC g;
  a.d_.grad(y,g);
  EXPECT_FLOAT_EQ(0.5 * -0.5 * 1.3 / sqrt(1.5) / 1.5, g[0]);
}
// ---------------------------------------------------------------------------
//	giveMeN (STATIC)
// ---------------------------------------------------------------------------
//  Compute the (fractional) channel number for a frequency given a 
//  reference frequency (corresponding to channel 1, the fundamental)
//  and a stretch factor.
//
static double giveMeN( double fn, double fref, double stretch )
{
    using std::sqrt;
    using std::pow;
    
    if ( 0 == stretch )
    {
        return fn / fref;
    }
    const double frefsqrd = fref*fref;
    double num = sqrt( (frefsqrd*frefsqrd) + (4*stretch*frefsqrd*fn*fn) ) - (frefsqrd);
    double denom = 2*stretch*frefsqrd;
    return sqrt( num / denom );
}
Example #11
0
TEST(AgradFwdAsinh,FvarVar_1stDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using boost::math::asinh;

  fvar<var> x(1.5,1.3);
  fvar<var> a = asinh(x);

  EXPECT_FLOAT_EQ(asinh(1.5), a.val_.val());
  EXPECT_FLOAT_EQ(1.3 / sqrt(1.0 + 1.5 * 1.5), a.d_.val());

  AVEC y = createAVEC(x.val_);
  VEC g;
  a.val_.grad(y,g);
  EXPECT_FLOAT_EQ(1.0 / sqrt(1.0 + 1.5 * 1.5), g[0]);
}
float inverted_index_storage::calc_l2norm(const sfv_t& sfv) {
  float ret = 0.f;
  for (size_t i = 0; i < sfv.size(); ++i) {
    ret += sfv[i].second * sfv[i].second;
  }
  return sqrt(ret);
}
Example #13
0
   Real finite_difference_derivative(const F f, Real x, Real* error, const fd_tag<1>&)
   {
      using std::sqrt;
      using std::pow;
      using std::abs;
      using std::numeric_limits;

      const Real eps = (numeric_limits<Real>::epsilon)();
      // Error bound ~eps^1/2
      // Note that this estimate of h differs from the best estimate by a factor of sqrt((|f(x)| + |f(x+h)|)/|f''(x)|).
      // Since this factor is invariant under the scaling f -> kf, then we are somewhat justified in approximating it by 1.
      // This approximation will get better as we move to higher orders of accuracy.
      Real h = 2 * sqrt(eps);
      h = detail::make_xph_representable(x, h);

      Real yh = f(x + h);
      Real y0 = f(x);
      Real diff = yh - y0;
      if (error)
      {
         Real ym = f(x - h);
         Real ypph = abs(yh - 2 * y0 + ym) / h;
         // h*|f''(x)|*0.5 + (|f(x+h)+|f(x)|)*eps/h
         *error = ypph / 2 + (abs(yh) + abs(y0))*eps / h;
      }
      return diff / h;
   }
/**
 * Generate an initial tof from this distribution:
 * 1-(0.5*X**2/T0**2+X/T0+1)*EXP(-X/T0), where x is the time and t0
 * is the src-sample time.
 * @param dtof Error in time resolution (us)
 * @param en0 Value of the incident energy
 * @param dl1 S.d of moderator to sample distance
 * @return tof Guass TOF modified for asymmetric pulse
 */
double VesuvioCalculateMS::generateTOF(const double en0, const double dtof,
                                       const double dl1) const {
  const double vel1 = sqrt(en0 / MASS_TO_MEV);
  const double dt1 = (dl1 / vel1) * 1e6;
  const double xmin(0.0), xmax(15.0 * dt1);
  double dx = 0.5 * (xmax - xmin);
  // Generate a random y position in th distribution
  const double yv = m_randgen->flat();

  double xt(xmin);
  double tof = m_randgen->gaussian(0.0, dtof);
  while (true) {
    xt += dx;
    // Y=1-(0.5*X**2/T0**2+X/T0+1)*EXP(-X/T0)
    double y =
        1.0 - (0.5 * xt * xt / (dt1 * dt1) + xt / dt1 + 1) * exp(-xt / dt1);
    if (fabs(y - yv) < 1e-4) {
      tof += xt - 3 * dt1;
      break;
    }
    if (y > yv) {
      dx = -fabs(0.5 * dx);
    } else {
      dx = fabs(0.5 * dx);
    }
  }
  return tof;
}
float cpp_rana(double* vals, long sz, double* weights){
  //The rana function! It does more things! Wow!
  double tot = 512.0, x, y;
  for(long i = 0; i < sz; ++i){
    x = vals[i];
    if(i == (sz - 1)){
      y = vals[0];
    }
    else{
      y = vals[i + 1];
    }
    tot += weights[i] * (x * sin(sqrt(abs(y + 1 - x))) * cos(sqrt(abs(x + y + 1)))
			 + (y + 1) * cos(sqrt(abs(y + 1 - x))) * sin(sqrt(abs(x + y + 1))));
  }
  return tot;
}
Example #16
0
TEST(AgradFvar, acosh) {
  using stan::agrad::fvar;
  using boost::math::acosh;
  using std::sqrt;
  using std::isnan;

  fvar<double> x(1.5);
  x.d_ = 1.0;

  fvar<double> a = acosh(x);
  EXPECT_FLOAT_EQ(acosh(1.5), a.val_);
  EXPECT_FLOAT_EQ(1 / sqrt(-1 + (1.5) * (1.5)), a.d_);

  fvar<double> y(-1.2);
  y.d_ = 1.0;

  fvar<double> b = acosh(y);
  isnan(b.val_);
  isnan(b.d_);

  fvar<double> z(0.5);
  z.d_ = 1.0;

  fvar<double> c = acosh(z);
  isnan(c.val_);
  isnan(c.d_);
}
Example #17
0
//----------------------------------------------------------------------------
double PrThreshold::weightedL2Norm()
//-----------------------------------------------------------------------------
{
  int jlast = t_->getFinestLevel();
  int powerOfTwo = 1 << jlast; // 2 to the power jlast.

  int npts = t_->getNumNodes(jlast);
  vector<int> nghbrs;

  int i,j,deg;
  double sum = 0.0;

  for(i=0; i< npts; i++)
  {
    t_->getNeighbours(i,jlast,nghbrs); 
    deg = (int)nghbrs.size();
    for(j=0; j<deg-1; j++)
    {
      if(i < nghbrs[j] && i < nghbrs[j+1])
      {
        sum += triangleNorm(i,nghbrs[j],nghbrs[j+1]);
      }
    }
    if(!t_->isBoundary(i))
    {
      if(i < nghbrs[deg-1] && i < nghbrs[0])
      {
        sum += triangleNorm(i,nghbrs[deg-1],nghbrs[0]);
      }
    }
  }

  return sqrt(sum / 6.0) / powerOfTwo;
}
Example #18
0
TEST(AgradFwdSqrt, FvarVar_1stDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using std::sqrt;

  fvar<var> x(1.5,1.3);
  fvar<var> a = sqrt(x);

  EXPECT_FLOAT_EQ(sqrt(1.5), a.val_.val());
  EXPECT_FLOAT_EQ(1.3 * 0.5 / sqrt(1.5), a.d_.val());

  AVEC y = createAVEC(x.val_);
  VEC g;
  a.val_.grad(y,g);
  EXPECT_FLOAT_EQ(0.5 / sqrt(1.5), g[0]);
}
Example #19
0
vector<int> find_repeated_sqrt(int num) {
    /* Return a vector in the form of [m, a0, a1, ... an]
     * where m is the first square less than sqrt(num) and
     * a_n is the sequence of repeated terms in the continued fraction
     * If num is square, return a single element vector containing num
     * E.g: sqrt(2) = 2 + 1
     *                    -----------
     *                    2 + 1
     *                        -------
     *                        2 + ...
     *
     * find_repeated_sqrt(2) -> [1, 2]
     */
    // initialize terms with the first number
    vector<int> terms{int(sqrt(num))};
    if (terms[0] * terms[0] == num)
        return terms;
    int d(1), m(0), a(terms[0]);
    while (a != 2*terms[0]) {
        m = d * a - m;
        d = (num - m * m) / d;
        a = (terms[0] + m) / d;
        terms.push_back(a);
    }
    return terms;
}
Example #20
0
File: kstest.cpp Project: th5th/cea
double ks_test::ks_cdf(double z)
{
    // CDF of the Kolmogorov-Smirnov distribution.
    using std::exp; using std::pow; using std::sqrt;
    if(z < 0.0)
    {
        throw("z must be non-negative in ks_cdf in ks_test.");
    }
    else if(z == 0.0)
    {
        return 0.0;
    }
    else if(z < 1.18)
    {
        double x = 1.23370055013616983/square(z);
        double y = exp(-x);
        return 2.25675833419102515*sqrt(x)*
            (y + pow(y,9) + pow(y,25) + pow(y,49));
    }
    else
    {
        double y = exp(-2.0*square(z));
        return 1.0 - 2.0*(y - pow(y,4) + pow(y,9));
    }
}
Example #21
0
 inline
 fvar<T>
 inv_sqrt(const fvar<T>& x) {
   using std::sqrt;
   T sqrt_x(sqrt(x.val_));
   return fvar<T>(1 / sqrt_x, -0.5 * x.d_ / (x.val_ * sqrt_x));
 }
Example #22
0
TEST(AgradRevMatrix, sdStdVector) {
    using stan::math::sd; // should use arg-dep lookup (and for sqrt)

    AVEC y1 = createAVEC(0.5,2.0,3.5);
    AVAR f1 = sd(y1);
    VEC grad1 = cgrad(f1, y1[0], y1[1], y1[2]);
    double f1_val = f1.val(); // save before cleaned out

    AVEC y2 = createAVEC(0.5,2.0,3.5);
    AVAR mean2 = (y2[0] + y2[1] + y2[2]) / 3.0;
    AVAR sum_sq_diff_2
        = (y2[0] - mean2) * (y2[0] - mean2)
          + (y2[1] - mean2) * (y2[1] - mean2)
          + (y2[2] - mean2) * (y2[2] - mean2);
    AVAR f2 = sqrt(sum_sq_diff_2 / (3 - 1));

    EXPECT_EQ(f2.val(), f1_val);

    VEC grad2 = cgrad(f2, y2[0], y2[1], y2[2]);

    EXPECT_EQ(3U, grad1.size());
    EXPECT_EQ(3U, grad2.size());
    for (size_t i = 0; i < 3; ++i)
        EXPECT_FLOAT_EQ(grad2[i], grad1[i]);
}
Example #23
0
    typename make_triangular_matrix<SymMatrix, boost::numeric::ublas::lower>::type
    cholesky_decomposition(SymMatrix const & A)
    {
        assert(A.size1() == A.size2());

        auto L = matrix_lower_trianle(A);

        for(size_t i = 0; i != A.size1(); ++ i)
        {
            for(size_t j = 0; j != i; ++ j)
            {
                for(size_t k = 0; k != j; ++ k)
                {
                    L(i, j) -= L(i, k) * L(j, k);
                }

                L(i, j) /= L(j, j);

                using ural::square;
                L(i, i) -= square(L(i, j));
            }

            assert(L(i, i) >= 0);

            using std::sqrt;
            L(i, i) = sqrt(L(i, i));
        }

        return L;
    }
Example #24
0
void Stippler::redistributeStipples() {
	using std::pow;
	using std::sqrt;
	using std::pair;
	using std::make_pair;
	using std::vector;

	vector< pair< Point< float >, EdgeList > > vectorized;
	for ( EdgeMap::iterator key_iter = edges.begin(); key_iter != edges.end(); ++key_iter ) {
		vectorized.push_back(make_pair(key_iter->first, key_iter->second));
	}

	float local_displacement = 0.0f;

	#pragma omp parallel for reduction(+:local_displacement)
	for (int i = 0; i < (int)vectorized.size(); i++) {
		pair< Point< float >, EdgeList > item = vectorized[i];
		pair< Point<float>, float > centroid = calculateCellCentroid( item.first, item.second );	// first : point, second: edge list

		radii[i] = centroid.second;
		vertsX[i] = centroid.first.x;
		vertsY[i] = centroid.first.y;

		local_displacement += sqrt( pow( item.first.x - centroid.first.x, 2.0f ) + pow( item.first.y - centroid.first.y, 2.0f ) );
	}

	displacement = local_displacement / vectorized.size(); // average out the displacement
}
typename boost::enable_if< 
  is_readable_matrix<Matrix>,
typename pp::topology_traits<StateSpace>::point_type >::type 
  sample_gaussian_point(const StateSpace& space, 
                        const typename pp::topology_traits<StateSpace>::point_type& mean, 
                        const Matrix& cov) {
  typedef typename pp::topology_traits<StateSpace>::point_difference_type DiffType;
  typedef typename mat_traits<Matrix>::value_type ValueType;
  typedef typename mat_traits<Matrix>::size_type SizeType;
  using std::sqrt;
  using ReaK::to_vect;
  using ReaK::from_vect;
  
  mat< ValueType, mat_structure::square> L;
  try {
    decompose_Cholesky(cov,L);
  } catch(singularity_error&) { 
    mat< ValueType, mat_structure::diagonal> E(cov.get_row_count());
    mat< ValueType, mat_structure::square> U(cov.get_row_count()), V(cov.get_row_count());
    decompose_SVD(cov,U,E,V);
    for(SizeType i = 0; i < cov.get_row_count(); ++i)
      E(i,i) = sqrt(E(i,i));
    L = U * E;
  };
  
  boost::variate_generator< global_rng_type&, boost::normal_distribution<ValueType> > var_rnd(get_global_rng(), boost::normal_distribution<ValueType>());
  
  vect_n<ValueType> z = to_vect<ValueType>(space.difference(mean, mean));
  for(SizeType i = 0; i < z.size(); ++i)
    z[i] = var_rnd();
  
  return space.adjust(mean, from_vect<DiffType>(L * z));
};
Example #26
0
T hypot_imp(T x, T y, const Policy& pol)
{
   //
   // Normalize x and y, so that both are positive and x >= y:
   //
   using std::fabs; using std::sqrt; // ADL of std names

   x = fabs(x);
   y = fabs(y);

#ifdef BOOST_MSVC
#pragma warning(push) 
#pragma warning(disable: 4127)
#endif
   // special case, see C99 Annex F:
   if(std::numeric_limits<T>::has_infinity
      && ((x == std::numeric_limits<T>::infinity())
      || (y == std::numeric_limits<T>::infinity())))
      return policies::raise_overflow_error<T>("boost::math::hypot<%1%>(%1%,%1%)", 0, pol);
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

   if(y > x)
      (std::swap)(x, y);

   if(x * tools::epsilon<T>() >= y)
      return x;

   T rat = y / x;
   return x * sqrt(1 + rat*rat);
} // template <class T> T hypot(T x, T y)
typename boost::enable_if< 
  boost::mpl::and_<
    is_writable_vector<Vector>,
    is_readable_matrix<Matrix>
  >,
Vector >::type sample_gaussian_point(const Vector& mean, const Matrix& cov) {
  typedef typename mat_traits<Matrix>::value_type ValueType;
  typedef typename mat_traits<Matrix>::size_type SizeType;
  using std::sqrt;
  
  mat< ValueType, mat_structure::square> L;
  try {
    decompose_Cholesky(cov,L);
  } catch(singularity_error&) { 
    mat< ValueType, mat_structure::diagonal> E(cov.get_row_count());
    mat< ValueType, mat_structure::square> U(cov.get_row_count()), V(cov.get_row_count());
    decompose_SVD(cov,U,E,V);
    for(SizeType i = 0; i < cov.get_row_count(); ++i)
      E(i,i) = sqrt(E(i,i));
    L = U * E;
  };
  
  boost::variate_generator< global_rng_type&, boost::normal_distribution<ValueType> > var_rnd(get_global_rng(), boost::normal_distribution<ValueType>());
  
  Vector z = mean;
  for(SizeType i = 0; i < z.size(); ++i)
    z[i] = var_rnd();
  
  return mean + L * z;
};
Example #28
0
static double dist(double pos1 [3], double pos2 [3]) {
        double sum = 0.;
        for (int i = 0; i < 3; i++) {
                sum += (pos2[i] - pos1[i]) * (pos2[i] - pos1[i]);
        }
        return sqrt(sum);
}
Example #29
0
int euler_solver<3>(string& solution) {

  constexpr long long test_val = 600851475143LL;

  long long curr_val = test_val;

  Prime my_prime;

  Cap<long long> capi([] (const long long &x) -> bool { return x <= sqrt(test_val); });

  auto term = capi.wrap(my_prime);

  for (const auto &i : term) {
    if (divisible(curr_val, i)) {
      curr_val /= i;
      if (curr_val == 1LL) {
        curr_val = i;
        break;
      }
    }
  }

  solution = to_string(curr_val);

  return EulerStatus::SUCCESS;

}
Example #30
0
    inline 
    typename boost::math::tools::promote_args<T>::type
    inv_sqrt(const T x) {
      using std::sqrt;

      return 1.0 / sqrt(x);
    }