Example #1
0
const Key& CountDictionary<Key>::sample(){

   //put that somewhere else...
   if(!sampling_allowed){
     std::vector<double> w(this->dict.size());
     arg_vec.resize(this->dict.size());
     int idx = 0;
     for(typename std::unordered_map<Key,unsigned>::iterator it = this->dict.begin();it != this->dict.end();++it){
       arg_vec[idx] = it->first;
       w[idx] = it->second;
       ++idx;
     }
     std::discrete_distribution<int> dtmp(w.begin(),w.end());
     distrib.param(dtmp.param()); 
     /*
       std::vector<double> p = distrib.probabilities();
     for(int i = 0; i < p.size();++i){
       std::cout << arg_vec[i] <<  p[i] << endl;
     }
     */

     sampling_allowed = true;
   } 
   //distrib.reset() ?;
   return arg_vec[distrib(rd_generator)];
}
Example #2
0
/** Solves a cubic equation: ax^3 + bx^2 + cx + d = 0 using "Cardan's formula" 
  * (see: Bronstein, S.131f)
  */
double Action_Vector::solve_cubic_eq(double a, double b, double c, double d) {
  const double one3 = 1.0 / 3.0;
  const double one27 = 1.0 / 27.0;
  double droot = 0;

  double r, s, t;
  double p, q, rho, phi;
  double D, u, v;
  std::vector<double> dtmp(3);

  /* Coeff. for normal form x^3 + rx^2 + sx + t = 0 */
  r = b / a;
  s = c / a;
  t = d / a;

  /* Coeff. for red. eq. y^3 + py + q = 0 with y = x + r/3 bzw. (x = y - r/3) */
  p = s - r * r * one3;
  q = 2.0 * r * r * r * one27 - r * s * one3 + t;

  /* Dummy variables */
  rho = sqrt(-p * p * p * one27);
  phi = acos(-q / (2.0 * rho));

  /* Discriminante(?) */
  D = pow((p * one3),3) + q * q * 0.25;

  if(D > 0){ /* x real -> one real solution */
    u = pow(-q * 0.5 + sqrt(D), one3);
    v = -p / u * one3;
    droot = (u + v) - r * one3;
  } else if(D <= 0){
  /* three real solutions (d < 0) | one real solution + one real double solution or 
                                                     one real triple solution (d = 0) */
    dtmp[0] = 2.0 * pow(rho, one3) * cos(phi * one3) - r * one3;
    dtmp[1] = 2.0 * pow(rho, one3) * cos((phi + Constants::TWOPI ) * one3) - r * one3;
    dtmp[2] = 2.0 * pow(rho, one3) * cos((phi + Constants::FOURPI) * one3) - r * one3;

    sort(dtmp.begin(), dtmp.end());

    //qsort((void *) dtmp, (size_t) 3, sizeof(double), cmpdouble);
    droot = dtmp[0];
  }
  return droot;
}