void tst_substitution() { memory::initialize(0); smt_params params; params.m_model = true; enable_trace("subst_bug"); ast_manager m; reg_decl_plugins(m); var_ref v1(m.mk_var(0, m.mk_bool_sort()), m); var_ref v2(m.mk_var(1, m.mk_bool_sort()), m); var_ref v3(m.mk_var(2, m.mk_bool_sort()), m); var_ref v4(m.mk_var(3, m.mk_bool_sort()), m); substitution subst(m); subst.reserve(1,4); unifier unif(m); bool ok1 = unif(v1.get(), v2.get(), subst, false); bool ok2 = unif(v2.get(), v1.get(), subst, false); expr_ref res(m); TRACE("substitution", subst.display(tout););
// sum = 1 void randinit_w(std::vector<std::vector<double> > &points, int dimension, double lower_bound, double upper_bound) { std::uniform_real_distribution<double> unif(lower_bound, upper_bound); std::random_device rand_dev; // Use random_device to get a random seed. std::mt19937 rand_engine(rand_dev()); // mt19937 is a good pseudo-random number // generator. for(int i = 0; i < points.size();i++){ std::vector<double> v(dimension); double sum = 0.0; for(int j = 0; j < dimension; j++){ v[j] = (unif(rand_engine)); sum += v[j]; } double unit = 1.0 / sum; sum = 0; for(int j = 0; j < dimension; j++){ v[j] *= unit; sum += v[j]; } points[i] = v; } }
color_generator(double s, double v) : s(s), v(v) { std::uniform_real_distribution<double> unif(0., 1.); std::random_device rand_dev; std::mt19937 rand_engine(rand_dev()); h = unif(rand_engine); }
/*get a rand double value*/ double get_rand(double lower_bound, double upper_bound) { std::uniform_real_distribution<double> unif(lower_bound, upper_bound); std::random_device rand_dev; // Use random_device to get a random seed. std::mt19937 rand_engine(rand_dev()); // mt19937 is a good pseudo-random number // generator. return unif(rand_engine); }
void randomize(RandomGen& random) { boost::uniform_real<> unif; for (std::size_t i = 0; i < n_; ++i) { xs_[i] = unif(random); ys_[i] = unif(random); } }
double gen_random() { double lower_bound = 0; double upper_bound = 1000; std::uniform_real_distribution<double> unif(lower_bound, upper_bound); std::default_random_engine re; double d = unif(re); return d; }
double GeometricRandomPlayout::eval(board b){ int steps =1; std::uniform_real_distribution<double> unif(0, 1); while(!b.is_ended() && unif(rng)<(1.0/steps++) ){ zet z= select_random_move(b); b=b+z; } return state_value(b); }
std::vector<int> make_keys<int>(size_t n) { std::tr1::mt19937 eng; // a core engine class£ºMersenne Twister generator //std::tr1::normal_distribution<double> dist; std::tr1::uniform_int<int> unif(0, n * 20); std::set<int> r; do { r.insert(static_cast<int>(unif(eng))); } while (r.size()<n); return std::vector<int>(r.begin(),r.end()); }
VectorBase<scalar,index,SizeAtCompileTime> VectorBase<scalar,index,SizeAtCompileTime>::random( const index s ) { std::uniform_real_distribution<typename get_pod_type<scalar>::type> unif(0.0,1.0); VectorBase<scalar,index,Dynamic> result(s); for ( int i = 0 ; i < s; ++ i ) { if(is_real<scalar>::value) ForceAssignment(unif(copt_rand_eng),result(i)); else ForceAssignment(std::complex<typename get_pod_type<scalar>::type>(unif(copt_rand_eng),unif(copt_rand_eng)),result(i)); } return result; }
double normal(double mu, double sigma) { // Box-Muller method, x=r*cos(theta), y=r*sin(theta) const double epsilon = numeric_limits<double>::min(); const double two_pi = 2.0*3.14159265358979323846; static double z0, z1; static bool generate; generate = !generate; if (!generate) return z1 * sigma + mu; double u1, u2; do { u1 = unif(); u2 = unif(); } while (u1 <= epsilon); // ensure u1 is not too small for log(u1) z0 = sqrt(-2.0 * log(u1)) * cos(two_pi * u2); z1 = sqrt(-2.0 * log(u1)) * sin(two_pi * u2); return z0 * sigma + mu; }
/*Uniform distribution data*/ void randinit(std::vector<std::vector<double> > &points, int dimension, double lower_bound, double upper_bound) { std::uniform_real_distribution<double> unif(lower_bound, upper_bound); std::random_device rand_dev; // Use random_device to get a random seed. std::mt19937 rand_engine(rand_dev()); // mt19937 is a good pseudo-random number // generator. for(int i = 0; i < points.size();i++){ std::vector<double> v; for(int j = 0; j < dimension; j++) v.push_back(unif(rand_engine)); points[i] = v; } }
vector<double> gen_random_vec() { vector<double> v; double lower_bound = 0; double upper_bound = 1000; std::uniform_real_distribution<double> unif(lower_bound, upper_bound); std::default_random_engine re; for (int i = 0; i < 30; i++) { double d = unif(re); v.push_back(d); } return v; }
//------------------------------------------------------------------------------ double RNG::ltgamma(double shape, double rate, double trunc) { double a = shape; double b = rate * trunc; if (trunc <=0) { fprintf(stderr, "ltgamma: trunc = %g < 0\n", trunc); return 0; } if (shape < 1) { fprintf(stderr, "ltgamma: shape = %g < 1\n", shape); return 0; } if (shape ==1) return expon_rate(1) / rate + trunc; double d1 = b-a; double d3 = a-1; double c0 = 0.5 * (d1 + sqrt(d1*d1 + 4 * b)) / b; double x = 0.0; bool accept = false; while (!accept) { x = b + expon_rate(1) / c0; double u = unif(); double l_rho = d3 * log(x) - x * (1-c0); double l_M = d3 * log(d3 / (1-c0)) - d3; accept = log(u) <= (l_rho - l_M); } return trunc * (x/b); }
double RNG::tnorm(double left) { double rho, ppsl; int count = 1; if (left < 0) { // Accept/Reject Normal while (true) { ppsl = norm(0.0, 1.0); if (ppsl > left) return ppsl; check_R_interupt(count++); #ifndef NDEBUG if (count > RCHECK * 1000) fprintf(stderr, "left < 0; count: %i\n", count); #endif } } else { // Accept/Reject Exponential // return tnorm_tail(left); // Use Devroye. double astar = alphastar(left); while (true) { ppsl = texpon_rate(left, astar); rho = exp( -0.5 * (ppsl - astar) * (ppsl - astar) ); if (unif() < rho) return ppsl; check_R_interupt(count++); #ifndef NDEBUG if (count > RCHECK * 1000) fprintf(stderr, "left > 0; count: %i\n", count); #endif } } } // tnorm
void ReArr::processReplacing(float** inputs, float** outputs, VstInt32 sampleFrames) { // mod the sample position to make sure it's within range of unsigned long unsigned long seed = static_cast<unsigned long>(fmod(getTimeInfo(0)->samplePos, ULONG_MAX)); std::tr1::mt19937 eng(seed); std::tr1::uniform_real<float> unif(0, 1); // start by copying the input for (int i = std::min(kNumInputs, kNumOutputs); i--;) memcpy(outputs[i], inputs[i], sampleFrames * sizeof(float)); // get the block size int block_size = std::max(static_cast<int>(sampleFrames * params_[kBlockSize]), 1); // now shuffle a certain number // decide how many samples to rearrange based on the dry-wet control int rearr = static_cast<int>(params_[kBlockSwaps] * (sampleFrames - block_size)); // need a scratch buffer to copy into float* scr = new float[block_size]; // do this across all channels for (int j = 0; j < rearr; ++j) { // choose two random block starts int blk1 = static_cast<int>(unif(eng) * (sampleFrames - block_size)); int blk2 = static_cast<int>(unif(eng) * (sampleFrames - block_size)); for (int i = std::min(kNumInputs, kNumOutputs); i--;) { // swap the blocks memcpy(scr, &outputs[i][blk1], block_size * sizeof(float)); memcpy(&outputs[i][blk1], &outputs[i][blk2], block_size * sizeof(float)); memcpy(&outputs[i][blk2], scr, block_size * sizeof(float)); } } delete[] scr; // set random output //for (int i = 0; i < kNumOutputs; ++i) // for (VstInt32 j = 0; j < sampleFrames; ++j) // outputs[i][j] = unif(eng); }
double RNG::texpon_rate(double left, double right, double rate) { if (left == right) return left; if (left > right) TREOR("texpon_rate: left > right, return 0.\n", 0.0); if (rate < 0) TREOR("texpon_rate: rate < 0, return 0\n", 0.0); double b = 1 - exp(rate * (left - right)); double y = 1 - b * unif(); return left - log(y) / rate; }
void operator()(address& addr) { // We hash the generated sample into a 128-bit digest to spread out the // bits over the entire domain of an IPv6 address. auto x = sample(); uint32_t bytes[4]; util::detail::murmur3<128>(&x, sizeof(x), 0, bytes); // P[ip == v6] = 0.5 std::uniform_int_distribution<uint8_t> unif{0, 1}; auto version = unif(gen_) ? address::ipv4 : address::ipv6; addr = {bytes, version, address::network}; }
std::vector<size_t> resample(const std::vector<ParticleType> &particles) { size_t index = size_t(unif(rng) * N); std::vector<size_t> indices(N); RealType beta = 0.0; auto max_particle = std::max_element(particles.begin(), particles.end(), [](ParticleType a, ParticleType b) { return a.weight < b.weight; }); RealType max_weight = (*max_particle).weight; for (size_t i = 0; i < N; i++) { beta += unif(rng) * 2.0 * max_weight; while (beta > particles[index].weight) { beta -= particles[index].weight; index = (index + 1) % N; } indices[i] = index; } return indices; }
double myrand() { /*Adaptation of myrand*/ if (seed == -1) seed = time(NULL) % 1000000000; /* cannot be larger than 1e9 */ seed ++; if (seed > 1e9) seed = 1; unif(uniftmp, 1, seed); return uniftmp[0]; }
void computeXopt(int seed, int _DIM) { int i; unif(tmpvect, _DIM, seed); for (i = 0; i < _DIM; i++) { Xopt[i] = 8 * floor(1e4 * tmpvect[i])/1e4 - 4; if (Xopt[i] == 0.0) Xopt[i] = -1e-5; } }
//------------------------------------------------------------------------------ double RNG::igauss(double mu, double lambda) { // See R code for specifics. double mu2 = mu * mu; double Y = norm(0.0, 1.0); Y *= Y; double W = mu + 0.5 * mu2 * Y / lambda; double X = W - sqrt(W*W - mu2); if (unif() > mu / (mu + X)) X = mu2 / X; return X; }
void pdf::generate_sample(int size, long double theta) { static unsigned int calls = 0; // use as seed for generator calls++; // ensures unique seed in every call sample.clear(); boost::uniform_real<> unif(theta, theta * theta); boost::random::mt19937 gen(calls); boost::variate_generator< boost::random::mt19937&, boost::uniform_real<> > sampler(gen, unif); for(int i=0;i<size;i++) { sample.push_back(sampler()); } }
/** * Update variance of the tower selected and the two adjacents towers **/ void change_var(vector<tower>* towers, int index, float taux_var) { float var = unif(-taux_var, taux_var); if ((*towers)[index].var_est == 0) { (*towers)[index].var_est = 1 + var; if (var > 0) { if (index + 1 < (int) towers->size() && (*towers)[index + 1].var_est == 0) { (*towers)[index + 1].var_est = 1 + unif(-taux_var, 0); } if (index - 1 >= 0 && (*towers)[index - 1].var_est == 0) { (*towers)[index - 1].var_est = 1 + unif(-taux_var, 0); } } else { if (index + 1 < (int) towers->size() && (*towers)[index + 1].var_est == 0) { (*towers)[index + 1].var_est = 1 + unif(0, taux_var); } if (index - 1 >= 0 && (*towers)[index - 1].var_est == 0) { (*towers)[index - 1].var_est = 1 + unif(0, taux_var); } } } }
// construct an approximating Gaussian model // Note the difference to previous versions, the convergence is assessed only // by checking the changes in mode, not the actual function values. This is // slightly faster and sufficient as the approximation doesn't need to be accurate. // Using function values would be safer though, as we could use line search etc // in case of potential divergence etc... ugg_ssm ung_ssm::approximate(arma::vec& mode_estimate, const unsigned int max_iter, const double conv_tol) { //Construct y and H for the Gaussian model arma::vec approx_y(n, arma::fill::zeros); arma::vec approx_H(n, arma::fill::zeros); // RNG of approximate model is only used in basic IS sampling // set seed for new RNG stream based on the original model std::uniform_int_distribution<> unif(0, std::numeric_limits<int>::max()); const unsigned int new_seed = unif(engine); ugg_ssm approx_model(approx_y, Z, approx_H, T, R, a1, P1, xreg, beta, D, C, new_seed); unsigned int i = 0; double diff = conv_tol + 1; while(i < max_iter && diff > conv_tol) { i++; //Construct y and H for the Gaussian model laplace_iter(mode_estimate, approx_model.y, approx_model.H); approx_model.compute_HH(); // compute new guess of mode arma::vec mode_estimate_new(n); if (distribution == 0) { mode_estimate_new = arma::vectorise(approx_model.fast_smoother().head_cols(n)); } else { arma::mat alpha = approx_model.fast_smoother().head_cols(n); for (unsigned int t = 0; t < n; t++) { mode_estimate_new(t) = arma::as_scalar(Z.col(Ztv * t).t() * alpha.col(t)); } } diff = arma::mean(arma::square(mode_estimate_new - mode_estimate)); mode_estimate = mode_estimate_new; } return approx_model; }
void gauss(double * g, int N, int seed) { /* samples N standard normally distributed numbers being the same for a given seed.*/ int i; unif(uniftmp, 2*N, seed); for (i = 0; i < N; i++) { g[i] = sqrt(-2*log(uniftmp[i])) * cos(2*M_PI*uniftmp[N+i]); if (g[i] == 0.) g[i] = 1e-99; } return; }
void generate(int k, int n, int *r, double *ranvec, double **b) { double unif(), cum; int i, l, nleft; for (i=1; i<=k-1; i++) ranvec[i] = unif(); nleft = n; for (l=1; l<k; l++) { cum = 0.0; for (i=1; i<=nleft; i++) { cum += b[k-l][nleft-i] / (i * b[k-l+1][nleft]); if (cum >= ranvec[l]) break; } r[l] = i; nleft -= i; } r[k] = nleft; }
/* * creates normally distributed tryouts * the number of iterations is given by iter. The programme terminatse as * soon as iter reaches zero. Iter has to be large to generate good * approximations. * eps is a positive parameter that helps to create deviations each cycle. * if eps is negative or zero then the programme terminates with a zero result * */ double methastings_normal(int iter, double eps){ double x=0,test; double oldlp=lnormal(x,0.0lf,1.0lf),logp; if(eps<=0){ goto endof; } while(iter>0){ test=x+unifab(-eps,eps); logp=lnormal(test,x,1.0f); if(ln(unif())<logp-oldlp){ x=test; oldlp=logp; } iter--; } endof: return x; }
// Truncation at t = 1. double RNG::right_tgamma_beta(double shape, double rate) { double a = shape; double b = rate; double u = unif(); int k = 1; double cdf = omega_k(1, a, b); while (u > cdf) { cdf += omega_k(++k, a, b); if (k % 100000 == 0) { printf("right_tgamma_beta (itr k=%i): a=%g, b=%g, u=%g, cdf=%g\n", k, a, b, u, cdf); #ifdef USE_R R_CheckUserInterrupt(); #endif } } return beta(a, k); }
// compilation d'un type // [name] -> 0 int Compiler::parsetype() { int k; // PRINTF(m)(LOG_DEVCORE,"type %s\n",STRSTART(VALTOPNT(STACKGET(m,0)))); char* name=STRSTART(VALTOPNT(STACKGET(m,0))); // création des variables de travail if (k=STACKPUSH(m,NIL)) return k; // LOCALS locals=STACKREF(m); newref=searchemptytype(PNTTOVAL(newpackage),name); int mergetype=1; if (newref) { if (k=createnodetypecore(TABGET(VALTOPNT(TABGET(newref,REF_TYPE)),TYPEHEADER_LENGTH+1))) return k; } else { mergetype=0; if (k=createnodetypecore(STACKGET(m,1))) return k; newref=MALLOCCLEAR(m,REF_LENGTH); if (!newref) return MTLERR_OM; TABSET(m,newref,REF_CODE,INTTOVAL(CODE_EMPTYTYPE)); TABSET(m,newref,REF_TYPE,STACKGET(m,0)); if (k=STACKPUSH(m,PNTTOVAL(newref))) return MTLERR_OM; // [newtyp local name] addreftopackage(newref,newpackage); STACKDROP(m); } int narg=0; if (parser->next(0)) { if (strcmp(parser->token,"(")) parser->giveback(); else { do { if (!parser->next(0)) { PRINTF(m)(LOG_COMPILER,"Compiler : parameter or ')' expected (found EOF)\n"); return MTLERR_SN; } if (islabel(parser->token)) { if (k=createnodetype(TYPENAME_UNDEF)) return k; if (k=addlabel(locals,parser->token,STACKGET(m,0),INTTOVAL(narg++))) return k; } else if (strcmp(parser->token,")")) { PRINTF(m)(LOG_COMPILER,"Compiler : parameter or ')' expected (found '%s')\n",parser->token); return MTLERR_SN; } } while(strcmp(parser->token,")")); if (k=DEFTAB(m,narg)) return k; TABSET(m,VALTOPNT(STACKGET(m,1)),TYPEHEADER_LENGTH,STACKGET(m,0)); STACKDROP(m); } } if (!mergetype) STACKDROP(m); else if (k=unif(VALTOPNT(STACKPULL(m)),VALTOPNT(TABGET(newref,REF_TYPE)))) return k; if (!parser->next(0)) { PRINTF(m)(LOG_COMPILER,"Compiler : '=' or ';;' expected (found EOF)\n"); return MTLERR_SN; } if (!strcmp(parser->token,"=")) { if (!parser->next(0)) { PRINTF(m)(LOG_COMPILER,"Compiler : uncomplete type definition (found EOF)\n"); return MTLERR_SN; } if (!strcmp(parser->token,"[")) return parsestruct(); parser->giveback(); return parsesum(); } else if (!strcmp(parser->token,";;")) { STACKDROPN(m,2); outputbuf->reinit(); outputbuf->printf("Compiler : uncompleted type : "); echograph(outputbuf,VALTOPNT(TABGET(newref,REF_TYPE))); PRINTF(m)(LOG_COMPILER,"%s\n",outputbuf->getstart()); return 0; } PRINTF(m)(LOG_COMPILER,"Compiler : '=' or ';;' expected (found '%s')\n",parser->token); return MTLERR_SN; }
// compilation d'une fonction // [name] -> 0 int Compiler::parsefun() { int k; int* type_result; // PRINTF(m)(LOG_DEVCORE,"fonction %s\n",STRSTART(VALTOPNT(STACKGET(m,0)))); char* name=STRSTART(VALTOPNT(STACKGET(m,0))); // création des variables de travail if (k=STACKPUSH(m,NIL)) return k; // LOCALS locals=STACKREF(m); if (k=createnodetype(TYPENAME_FUN)) return k; // recherche des arguments int narg=0; do { if (!parser->next(0)) { PRINTF(m)(LOG_COMPILER,"Compiler : argument or '=' expected (found EOF)\n"); return MTLERR_SN; } if (islabel(parser->token)) { if (k=createnodetype(TYPENAME_UNDEF)) return k; if (k=addlabel(locals,parser->token,INTTOVAL(narg++),STACKGET(m,0))) return k; } else if (strcmp(parser->token,"=")) { PRINTF(m)(LOG_COMPILER,"Compiler : argument or '=' expected (found '%s')\n",parser->token); return MTLERR_SN; } } while(strcmp(parser->token,"=")); // construction du type initial de la fonction if (k=createnodetuple(narg)) return k; TABSET(m,VALTOPNT(STACKGET(m,1)),TYPEHEADER_LENGTH,STACKGET(m,0)); // attachement du noeud tuple au noeud fun STACKDROP(m); if (k=createnodetype(TYPENAME_UNDEF)) return k; // noeud résultat TABSET(m,VALTOPNT(STACKGET(m,1)),TYPEHEADER_LENGTH+1,STACKGET(m,0)); // attachement du noeud resultat au noeud fun type_result=VALTOPNT(STACKPULL(m)); // on garde en mémoire le type du résultat // ici : [type local global name] // on crée le bloc fonction newref=MALLOCCLEAR(m,REF_LENGTH); if (!newref) return MTLERR_OM; TABSET(m,newref,REF_TYPE,STACKPULL(m)); TABSET(m,newref,REF_NAME,STACKGET(m,1)); TABSET(m,newref,REF_CODE,INTTOVAL(narg)); // vient d'être déclarée, pas encore utilisée TABSET(m,newref,REF_USED,INTTOVAL(0)); k=findproto(PNTTOVAL(newpackage),newref); TABSET(m,newref,REF_PACKAGE,(k!=NIL)?k:INTTOVAL(ifuns++)); if (k=STACKPUSH(m,PNTTOVAL(newref))) return MTLERR_OM; // [newref local global name] addreftopackage(newref,newpackage); STACKDROP(m); // [local global name] // on poursuit la compilation vers le corps de la fonction nblocals=narg; bc->reinit(); // initialisation de la production de bytecode // [locals globals] // parsing if (k=parseprogram()) return k; // [type locals globals] // la pile contient le type du résultat de la fonction if (k=parser->parsekeyword(";;")) return k; // unifier le type résultat if (k=unif(type_result,VALTOPNT(STACKGET(m,0)))) return k; STACKDROP(m); // [locals globals name] // créer le bloc programme int* fun=MALLOCCLEAR(m,FUN_LENGTH); if (!fun) return MTLERR_OM; TABSET(m,newref,REF_VAL,PNTTOVAL(fun)); TABSET(m,fun,FUN_NBARGS,INTTOVAL(narg)); TABSET(m,fun,FUN_NBLOCALS,INTTOVAL(nblocals)); // stocker le bytecode bc->addchar(OPret); if (k=STRPUSHBINARY(m,bc->getstart(),bc->getsize())) return k; TABSET(m,fun,FUN_BC,STACKPULL(m)); if (!strcmp(name,"awcConnect")) displaybc(m,STRSTART(VALTOPNT(TABGET(fun,FUN_BC)))); // construire le tuple des références globales // int* globalstuple=tuplefromlabels(globals); // if (!globalstuple) return MTLERR_OM; // TABSET(m,fun,FUN_REF,PNTTOVAL(globalstuple)); TABSET(m,fun,FUN_REFERENCE,PNTTOVAL(newref)); STACKDROPN(m,2); // [] // chercher d'éventuels prototypes if (k=fillproto(PNTTOVAL(newpackage),newref)) return k; outputbuf->reinit(); outputbuf->printf("Compiler : %s : ",STRSTART(VALTOPNT(TABGET(newref,REF_NAME)))); echograph(outputbuf,VALTOPNT(TABGET(newref,REF_TYPE))); PRINTF(m)(LOG_COMPILER,"%s\n",outputbuf->getstart()); return 0; }