int main(int argc, char *argv[]) { size_t ct_size = 4; ContextTree ctw(ct_size); //Runs a coinflip example if the agent guesses randomly and the coin is random for(int i = 0; i < 1000; i++) { int guess = rand01() < 0.5 ? 1 : 0; int coin = rand01() < 0.5 ? 1 : 0; ctw.update(guess); ctw.update(coin); ctw.update(coin==guess ? 1 : 0); } //Action and observation are 0, 1 so ctw_tree would predict reward 0 if it "understood" the game // std::cout << ctw->prettyPrint(); // std::cout << "Sequence: " << ctw->printHistory() << std::endl; // std::cout << "Next: "<< ctw->predictNext() << std::endl; std::cout << "Original:" << std::endl << ctw.prettyPrint(); ContextTree copy_tree(ctw); std::cout << "Copy:" << std::endl << copy_tree.prettyPrint(); ctw.update(0); copy_tree.update(1); std::cout << "Original + 0:" << std::endl << ctw.prettyPrint(); //std::cout << "Sequence: " << ctw.printHistory() << std::endl; std::cout << "Copy + 1:" << std::endl << copy_tree.prettyPrint(); //std::cout << "Sequence: " << copy_tree.printHistory() << std::endl; }
void Wander::action() { // get parameters const WanderParameters * params = dynamic_cast<const WanderParameters *>(params_); // make sure nothing went wrong MIRO_ASSERT(params != NULL); // set the arbiter message to random values double r = rand01(); if (r < params->thresholdChange) { r = rand01(); message_.velocity.translation = params->minTranslation + (long)(r * (params->maxTranslation - params->minTranslation)); r = rand01(); if (r > params->thresholdStraight) { r = rand01(); message_.velocity.rotation = - params->maxRotation + r * 2 * params->maxRotation; } else message_.velocity.rotation = 0.; } arbitrate(message_); }
void animer() { float l1pos[]={100,200,50,1}; float l2pos[]={-100,200,50,1}; float l3pos[]={100,-200,50,1}; rotate+=1; if(rotate>=360) { rotate=0; ax=rand01()-.5; ay=rand01()-.5; az=rand01()-.5; } l1pos[0]=100*sin(tid)+200*cos(tid); l1pos[1]=100*cos(tid)-200*sin(tid); l1pos[2]=50; l2pos[0]=100*sin(tid)+200*cos(tid); l2pos[1]=50; l2pos[2]=100*cos(tid)-200*sin(tid); l3pos[0]=50; l3pos[1]=100*sin(tid)+200*cos(tid); l3pos[2]=100*cos(tid)-200*sin(tid); glLightfv(GL_LIGHT1,GL_POSITION,l1pos); glLightfv(GL_LIGHT2,GL_POSITION,l2pos); glLightfv(GL_LIGHT3,GL_POSITION,l3pos); tid+=0.025; }
small_world_iterator& operator++() { target = (target + 1) % n; if (target == (source + k/2 + 1) % n) { ++source; if (allow_self_loops) target = source; else target = (source + 1) % n; } current.first = source; uniform_01<RandomGenerator, double> rand01(*gen); uniform_int<vertices_size_type> rand_vertex_gen(0, n-1); double x = rand01(); *gen = rand01.base(); // GRRRR if (x < prob) { vertices_size_type lower = (source + n - k/2) % n; vertices_size_type upper = (source + k/2) % n; do { current.second = rand_vertex_gen(*gen); } while ((current.second >= lower && current.second <= upper) || (upper < lower && (current.second >= lower || current.second <= upper))); } else { current.second = target; } return *this; }
Point rand(CGAL::Random& g) const { double r1 = sqrt(rand01(g)), r2 = rand01(g); return CGAL::ORIGIN + ((1 - r1) * (a-CGAL::ORIGIN) + (r1 * (1 - r2)) * (b-CGAL::ORIGIN) + (r1 * r2) * (c-CGAL::ORIGIN)); }
//render between 0-1.0f void render_doids(int _seed) { int old_seed = seed; seed = _seed; { int nboxes = 1 + randi(3); //random size float w = 0.1f + 0.5f*rand01(); float h = (0.7f - w) + 0.5f* rand01(); float hg = 0.01f + 0.2f*rand01(); //pos float x = (1.0f - w) * rand01(); float y = (1.0f - h*nboxes) * rand01(); while(nboxes--) { glPushMatrix(); glTranslatef(x, y + (h+ 0.01f)*nboxes, hg); glScalef(w, h, hg); cube_w(); glPopMatrix(); } } seed = old_seed; }
/* Perform a Monte Carlo sweep */ static TaskSignal monteCarloTaskTick(void *state) { assert(state != NULL); MonteCarloState *mcs = (MonteCarloState*) state; MonteCarloConfig *mcc = &mcs->conf; assert(mcc->delta > 0); for (int i = 0; i < world.numParticles; i++) { Particle *p = &world.particles[randIndex(world.numParticles)]; Vec3 oldPos = p->pos; p->pos.x += mcc->delta * (rand01() - 1/2.0); p->pos.y += mcc->delta * (rand01() - 1/2.0); if (!world.twoDimensional) p->pos.z += mcc->delta * (rand01() - 1/2.0); reboxParticle(p); if (collides(p)) { /* Back to old position! */ p->pos = oldPos; reboxParticle(p); } else { mcs->accepted++; } } mcs->attempted += world.numParticles; return TASK_OK; }
// 光源上の点をサンプリングして直接光を計算する Color direct_radiance_sample(const Vec &v0, const Vec &normal, const int id) { // 光源上の一点をサンプリングする const double r1 = 2 * PI * rand01(); const double r2 = 1.0 - 2.0 * rand01(); const Vec light_pos = spheres[LightID].position + ((spheres[LightID].radius + EPS) * Vec(sqrt(1.0 - r2*r2) * cos(r1), sqrt(1.0 - r2*r2) * sin(r1), r2)); return direct_radiance(v0, normal, id, light_pos); }
int main(int argc, char **argv) { int width = 640; int height = 480; int photon_num = 50000; double gather_photon_radius = 32.0; int gahter_max_photon_num = 64; int final_gather = 64; // final_gather個のサンプル int direct_light_samples = 64; // カメラ位置 Ray camera(Vec(50.0, 52.0, 295.6), Normalize(Vec(0.0, -0.042612, -1.0))); // シーン内でのスクリーンのx,y方向のベクトル Vec cx = Vec(width * 0.5135 / height); Vec cy = Normalize(Cross(cx, camera.dir)) * 0.5135; Color *image = new Color[width * height]; // フォトンマップ構築 PhotonMap photon_map; create_photon_map(photon_num, &photon_map); // イラディアンスキャッシュ // 事前構築(なにかと都合がよい) IrradianceCache cache; for (int i = 0; i < 10000; i ++) { if (i % 1000 == 0) std::cout << "*"; pre_build_irradiance_cache(camera, cx, cy, width, height, &photon_map, &cache, gather_photon_radius, gahter_max_photon_num, final_gather, direct_light_samples); } for (int y = 0; y < height; y ++) { std::cerr << "Rendering " << (100.0 * y / (height - 1)) << "%" << std::endl; srand(y * y * y); for (int x = 0; x < width; x ++) { int image_index = y * width + x; image[image_index] = Color(); // 2x2のサブピクセルサンプリング for (int sy = 0; sy < 2; sy ++) { for (int sx = 0; sx < 2; sx ++) { // テントフィルターによってサンプリング // ピクセル範囲で一様にサンプリングするのではなく、ピクセル中央付近にサンプルがたくさん集まるように偏りを生じさせる const double r1 = 2.0 * rand01(), dx = r1 < 1.0 ? sqrt(r1) - 1.0 : 1.0 - sqrt(2.0 - r1); const double r2 = 2.0 * rand01(), dy = r2 < 1.0 ? sqrt(r2) - 1.0 : 1.0 - sqrt(2.0 - r2); Vec dir = cx * (((sx + 0.5 + dx) / 2.0 + x) / width - 0.5) + cy * (((sy + 0.5 + dy) / 2.0 + y) / height- 0.5) + camera.dir; image[image_index] = image[image_index] + radiance(Ray(camera.org + dir * 130.0, Normalize(dir)), 0, &photon_map, &cache, gather_photon_radius, gahter_max_photon_num, final_gather, direct_light_samples); } } } } // .hdrフォーマットで出力 save_hdr_file(std::string("image.hdr"), image, width, height); }
static void gen_square(Square *sq, int w, int h) { sq->cx = rand() % w; sq->cy = rand() % h; sq->dx = 3.0 * rand11(); sq->dy = 3.0 * rand11(); sq->size = 10 + (rand() % 10); sq->dsize = rand11(); sq->rot = ALLEGRO_PI * rand01(); sq->drot = rand11() / 3.0; sq->life = 0.0; sq->dlife = (ALLEGRO_PI / 100.0) + (ALLEGRO_PI / 30.0) * rand01(); }
void NetworkSimulator::MaybeCorruptBufferToggleBits(void *buffer, size_t numBytes) const { // Should corrupt this data? if (rand01() < corruptToggleBitsRate) { int numBitsToCorrupt = corruptMinBits + (int)(rand01() * (corruptMaxBits - corruptMinBits + 1)); for(int i = 0; i < numBitsToCorrupt; ++i) { int byteIndex = (int)(rand01() * numBytes); int bitIndex = rand() % 8; int bitMask = (1 << bitIndex); ((char*)buffer)[byteIndex] ^= bitMask; } } }
Catalog mk_random_cat(int np) { ////// // Returns random catalog with np particles // (with normalized radii for angular corr) int ir; Catalog cat; print_info("*** Creating random catalog "); #ifdef _VERBOSE print_info("with %d objects",np); #endif print_info("\n"); //Allocate memory for catalog cat.np=np; cat.red=(double *)my_malloc(cat.np*sizeof(double)); cat.cth=(double *)my_malloc(cat.np*sizeof(double)); cat.phi=(double *)my_malloc(cat.np*sizeof(double)); #ifdef _WITH_WEIGHTS cat.weight=(double *)my_malloc(cat.np*sizeof(double)); #endif //_WITH_WEIGHTS //Generate positions ir=0; while(ir<np) { double cth,phi,zz; if(corr_type!=1) zz=rand_dndz_dist(); else zz=0.5*(red_max_mask+red_min_mask); cth=cth_min_mask+(cth_max_mask-cth_min_mask)*rand01(); phi=phi_min_mask+(phi_max_mask-phi_min_mask)*rand01(); if(in_mask(zz,cth,phi)) { cat.red[ir]=zz; cat.cth[ir]=cth; cat.phi[ir]=phi; #ifdef _WITH_WEIGHTS cat.weight[ir]=1.; #endif //_WITH_WEIGHTS ir++; } } return cat; }
// Execute agent's action. void ExtendedTiger::performAction(const action_t action) { assert(isValidAction(action)); m_action = action; // Unless explicitly accounted for, action is invalid. m_observation = oNull; // Some valid actions also have null observation. m_reward = rInvalid; if (action == aListen && m_sitting) { // Listen while sitting down. Observe door hiding tiger with probability // m_listen_accuracy otherwise observe other door. m_observation = rand01() < m_listen_accuracy ? m_tiger : m_gold; m_reward = rListen; } else if (action == aLeft && !m_sitting) { // Open left door while standing. Get reward based on what was behind // the door. Reseat agent and reallocate tiger and gold. m_reward = (m_tiger == oLeft ? rTiger : rGold); reset(); } else if (action == aRight && !m_sitting) { // Open right door while standing. Get reward based on what was behind // the door. Reseat agent and reallocate tiger and gold. m_reward = (m_tiger == oRight ? rTiger : rGold); reset(); } else if (action == aStand && m_sitting) { // Stand from a sitting position. Get reward for standing. m_reward = rStand; m_sitting = false; } }
int main(int argc, char ** argv){ loadData(data,true); loadTestData(); loadUserItemData(users, items, data); for(int i = 0; i < data.size(); ++i) nu[data[i].user]++; #define K 7 vector< vector< map<int,float> > > tests(K); vector< float > weight(K); int k = 0; loadResults("../ret2/results-knni-iuf.txt.0", tests[k]); weight[k] = 1; ++k; loadResults("../ret2/results-knnu-iif.txt.0", tests[k]); weight[k] = 1; ++k; loadResults("../ret2/results-knnui.txt.0", tests[k]); weight[k] = 1; ++k; loadResults("../ret2/results-language.txt.0", tests[k]); weight[k] = 0.4; ++k; loadResults("../ret2/results-repos.txt.0", tests[k]); weight[k] = 0.4; ++k; loadResults("../ret2/results-reponame.txt.0", tests[k]); weight[k] = 0.2; ++k; loadResults("../ret2/results-pop-nic.txt.0", tests[k]); weight[k] = 0.01; ++k; srand(time(0)); int j = 0; for(int step = 0; step < 20; ++step){ int i = j % K; ++j; float w0 = weight[i]; int r0 = bag(tests, weight); weight[i] *= (1 + 0.5 * (rand01() - 0.5)); int r1 = bag(tests, weight); if(r1 <= r0) weight[i] = w0; cout << step << "\t" << r0 << "\t" << r1 << endl; } for(int i = 0; i < weight.size(); ++i) cout << i << "\t" << weight[i] << endl; return 0; }
int main() { double m, stddev; int hist[n_bins], samples = 10; while (samples <= 10000) { m = avg(samples, &stddev, hist); printf("size %5d: %g %g\n", samples, m, stddev); samples *= 10; } printf("\nHistograph:\n"); hist_plot(hist); printf("\nMoving average:\n N Mean Sigma\n"); moving_rec rec = { 0, 0, 0, {0} }; double data[100]; for (int i = 0; i < 10000; i++) { for (int j = 0; j < 100; j++) data[j] = rand01(); moving_avg(&rec, data, 100); if ((i % 1000) == 999) { printf("%4lluk %f %f\n", rec.size/1000, rec.sum / rec.size, sqrt(rec.x2 * rec.size - rec.sum * rec.sum)/rec.size ); } } }
static double rand_dndz_dist(void) { ////// // Returns random redshift following // the redshift distribution double u,rsh; int accept=0; while(!accept) { u=rand01(); rsh=red_min_mask+rand01()*(red_max_mask-red_min_mask); if(u*dist_max<num_dens_z(rsh)) accept=1; } return rsh; }
// Use rhoUCT to search for next action. action_t Agent::search(void) { // Save the agent's current state ModelUndo undo = ModelUndo(*this); // Create a new search tree m_search_tree = new SearchNode(decision); // Main sampling loop for (int t = 0; t < m_mc_simulations; t++) { m_search_tree->sample(*this, m_horizon); modelRevert(undo); } // Determine best action using tree constructed during sampling // by choosing the action branch from this tree that provides the best expected reward. action_t best_action = genRandomAction(); double best_mean = -1; for (action_t a = 0; a <= maxAction(); a++) { if (!m_search_tree->child(a)) continue; double mean = m_search_tree->child(a)->expectation() + rand01() * 0.0001; if (mean > best_mean) { best_mean = mean; best_action = a; } } delete m_search_tree; return best_action; }
void power_up_launch(vec3f pos) { actor* a = ACTOR_get(actor_pool); a->pos[0] = pos[0]; a->pos[1] = pos[1]; a->pos[2] = 0.0f; float d = rand01()*2*PI; a->vel[0] = 6.0f*cosf(d);//randf()*4.0f; a->vel[1] = 6.0f*sinf(d); a->vel[2] = 0.0f; a->ang = 0.0; a->collide_size[0] = 1.0f; a->collide_size[1] = 1.0f; a->type = POWER_UP; a->update = power_up_update; a->render = power_up_render; }
void KuhnPoker::performAction(action_t action) { assert(isValidAction(action)); m_action = action; // If the agent did not call the environments bet then the agent loses if(m_action == aPass && m_env_action == aBet) { m_reward = rPassLoss; reset(); return; } // If the environment passed and the agent bet, then the environment has // a chance to change its mind. if(m_action == aBet && m_env_action == aPass) { if(m_env_card == oQueen && rand01() < cBetProbQueen) { m_env_action = aBet; // Bet with cBetProbQueen probability on queen } else if(m_env_card == oKing) { m_env_action = aBet; // Always bet on king } else { // Environment continues to pass, so agent wins m_reward = rPassWin; reset(); return; } } // Players have bet the same amount, winner has highest card bool agent_wins = m_env_card == oJack || (m_env_card == oQueen && m_agent_card == oKing); if(agent_wins) m_reward = (m_env_action == aBet ? rBetWin : rPassWin); else m_reward = (m_action == aBet ? rBetLoss : rPassLoss); reset(); }
void ParticleEmitter::createVelocity(GLfloat velocity[3]) { float speed; if(minSpeed != maxSpeed) speed = minSpeed + (rand01() * (maxSpeed - minSpeed)); else speed = minSpeed; Vector3 vel; if(angle == 0) { vel = Vector3(direction); vel *= speed; } else { Vector3 dir(direction); vel = randomDeviant(direction, rand01() * angle); vel *= speed; } vel.fillGL(velocity); }
// -------------------------------------------------- // Build Solutions Set void Individual::build_solution(int n){ num_functions = n; for (int s = 0; s < (2 * num_functions); s++) { solution_set.push_back(rand01()*0.1); // random number between 0 - 0.1 // TODO- fill with 0-.1, 0-1, 0-10, 0-100 random value solutions } }
void CParticle::step() { if (pos.size() < max_particle) if (rand01() < create_probability) { vec3 nextpos( randWithin(posx), randWithin(posy), randWithin(posz) ); vec3 nextvel = vel + vec3(rand01()*vnoise.x, rand01()*vnoise.y, rand01()*vnoise.z); // printf("%.3f %.3f %.3f\n", nextpos.x, nextpos.y, nextpos.z); pos.push_back(nextpos); velocity.push_back(nextvel); } for (int i = 0; i < pos.size(); ++i) { pos[i] += velocity[i]; // special judge if (pos[i].z < -5) { // on ground, reset pos[i] = vec3( randWithin(posx), randWithin(posy), randWithin(posz) ); velocity[i] = vel + vec3(rand01()*vnoise.x, rand01()*vnoise.y, rand01()*vnoise.z); } } render(); }
Vector3 ParticleEmitter::randomDeviant(Vector3 direction, float ang) { Vector3 up = direction.perpendicular(); Vector3 up2; Quat q; q.fromAxis(rand01() * M_PI * 2, direction); up2 = q * up; q.fromAxis(ang, up2); return (q * direction); }
glm::vec3 Mth::randInsideSphere(float radius) { float phi = randRange(0.0f, PI*2.0f); float costheta = randUnit(); float u = rand01(); float theta = acos(costheta); float r = radius * std::pow(u, 1.0f / 3.0f); return glm::vec3(sin(theta)*cos(phi), sin(theta)*sin(phi), cos(theta))*r; }
static void fillWorld(void) { double ws = world.worldSize; for (int i = 0; i < world.numParticles; i++) { Particle *p = &world.particles[i]; p->pos = (Vec3) {0, 0, 0}; addToGrid(p); do { p->pos.x = ws * (rand01() - 1/2.0); p->pos.y = ws * (rand01() - 1/2.0); if (!world.twoDimensional) p->pos.z = ws * (rand01() - 1/2.0); reboxParticle(p); } while (collides(p)); } }
//mu是数学期望,omg是方差 double normal(double mu,double omg) { double sum=0.0; int i; for(i=0;i<12;i++) sum+=rand01(); sum-=6.0; return sum*omg+mu; }
Catalog_f mk_random_cat_f(int np) { ////// // Returns random catalog with np particles // (with normalized radii for angular corr) int ir; Catalog_f cat; print_info("*** Creating random catalog "); #ifdef _VERBOSE print_info("with %d objects",np); #endif print_info("\n"); //Allocate memory for catalog cat.np=np; cat.pos=(float *)my_malloc(3*cat.np*sizeof(float)); //Generate positions ir=0; while(ir<np) { double cth,phi,zz; if(corr_type!=1) zz=rand_dndz_dist(); else zz=0.5*(red_max_mask+red_min_mask); cth=cth_min_mask+(cth_max_mask-cth_min_mask)*rand01(); phi=phi_min_mask+(phi_max_mask-phi_min_mask)*rand01(); if(in_mask(zz,cth,phi)) { double sth=sqrt(1-cth*cth); double rr; if(corr_type!=1) rr=z2r(zz); else rr=1; cat.pos[3*ir]=(float)(rr*sth*cos(phi)); cat.pos[3*ir+1]=(float)(rr*sth*sin(phi)); cat.pos[3*ir+2]=(float)(rr*cth); ir++; } } return cat; }
void final_boss_update(struct actor_t* a, float) { a->ang += 40.0f*dt; a->pos[0] = 10.0f*perlin2d(a->time*0.001f, a->time*0.001f)*sinf(a->time*0.4f); a->pos[1] = 14.0f + 3.0f*sinf(a->time*0.4f); a->ang = 5.0f*sinf(a->time); MADD(a->pos, a->pos, dt, a->vel); SHIP_update(a); a->count++; if(a->life > 0.0f) { a->pos[2] -= a->pos[2]*0.07f; final_boss_fire(a); } else { //falling and exploding if(a->count%40) { vec3f p; p[0] = linear(-0.5f*a->collide_size[0], 0.5f*a->collide_size[0], rand01()); p[1] = linear(-0.5f*a->collide_size[1], 0.5f*a->collide_size[1], rand01()); p[2] = 0; VADD(p, a->pos, p); PART_explosion(p, 8); EFFECTS_medium_explosion(); } float dead_time = a->time-a->aux[2]; a->pos[2] -= dead_time*0.5f; //aux[2] contains dead time if(a->pos[2] < -90.0f) { ACTOR_kill(a); final_boss = 0; } } }
int pickparent() { double r=rand01(); int lo=0,hi=POP,mid; /* find individual with lowest cumul satisfying cumul>=r */ while(lo<hi) { mid=lo+(hi-lo)/2; if(pop[mid].cumul>=r) hi=mid; else lo=mid+1; } if(lo==POP) lo--; return lo; }
// generates a random number between num1 and num2 inclusive double PixelBufferClass::RandomRange(double num1, double num2) { double hi,lo; if (num1 < num2) { lo = num1; hi = num2; } else { lo = num2; hi = num1; } return rand01()*(hi-lo)+ lo; }