void BlackScholes::prep_memory() { /* Initialization */ t_mem.start(); srand(time(NULL)); /* Allocate host memory */ call = new float[optNum]; put = new float[optNum]; stockPrice = new float[optNum]; optionStrike = new float[optNum]; optionYears = new float[optNum]; ERROR_HANDLER((optionYears != NULL || optionStrike != NULL || stockPrice != NULL || put != NULL || call != NULL), "Error in allocation memory for parameters"); /* Initialize variables */ for (int i = 0; i < optNum; i++) { call[i] = 0.0f; put[i] = 0.0f; stockPrice[i] = rand_float(10.0f, 100.0f); optionStrike[i] = rand_float(1.0f, 100.0f); optionYears[i] = rand_float(0.25f, 5.0f); } t_mem.stop(); }
void MultiJittered::generateSamples(void) { int n = (int)sqrt((float)n_samples); float subcell_width = 1.0 / ((float) n_samples); Point2D fill_point; for (int j = 0; j < n_samples * n_sets; j++) samples.push_back(fill_point); for (int p = 0; p < n_sets; p++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { samples[i * n + j + p * n_samples].x = (i * n + j) * subcell_width + rand_float(0, subcell_width); samples[i * n + j + p * n_samples].y = (j * n + i) * subcell_width + rand_float(0, subcell_width); } for (int p = 0; p < n_sets; p++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { int k = rand_int(j, n - 1); float t = samples[i * n + j + p * n_samples].x; samples[i * n + j + p * n_samples].x = samples[i * n + k + p * n_samples].x; samples[i * n + k + p * n_samples].x = t; } for (int p = 0; p < n_sets; p++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { int k = rand_int(j, n - 1); float t = samples[j * n + i + p * n_samples].y; samples[j * n + i + p * n_samples].y = samples[k * n + i + p * n_samples].y; samples[k * n + i + p * n_samples].y = t; } }
float Sniper::Shot(Game_Manager* gm_, Unit* User_, int team_, const coord_def& start_, const coord_def& pos_, float focus_) { float angle_ = GetAngleToTarget(start_, pos_); if(UseBullet(1)) { for(int i = 0;i<bunch;i++) { float focus2_ = rand_float(-focus_, focus_,"Sniper::Shot focus"); if(User_->GetSniper()) focus2_ = 0; float speed2_ = shot_speed*GetShotSpeedApply()*rand_float(0.8f, 1.2f, "Sniper::Shot speed"); float damage_ = damage*GetDamegeApply()*(User_?User_->GetAtkApply():1.0f); gm_->shot_list.push_back(new Shot_sniper(&tex_gun, User_, damage_, sniper, GetPower(), GetMaxPower(), team_, start_, angle_+focus2_, GetDistance(), 50)); } if (gm_->isPlayerCanHear(GetPos())) { if(GetType() == WT_SILENCE || User_->GetSilencer() != 1.0f) PlaySE(se_silencesnipergun); else PlaySE(se_snipergun); } gm_->Noise(team_,start_,GetNoise() * User_->GetSilencer()); return burst_speed*(1.0f/(GetBurstSpeedApply()*(User_?User_->GetAtkSpdApply():1.0f))); } return -1; }
// generate a random Vector3f of size 1 Vector3f rand_vec3f(void) { Vector3f v = Vector3f(rand_float(), rand_float(), rand_float()); if (v.length() != 0.0) { v.normalize(); } return v; }
/** \brief Constructs a new Arrow. \param points The number of points the arrow will have along the center line. Cannot be less than 2. \param radius The radius of the arrow, where 1.0f will have the arrow touch the edge of the screen. */ Arrow::Arrow(int points, float radius) { if (points < 2) { throw std::bad_exception(); } // Off-by-one adjustment points--; // The x position of the "interior" vertex float mid = -radius + 0.6f; // Set the rand seed so we get unique values srand(static_cast <unsigned> (time(0))); // The top left vertex Vertex2D top; top.p.x = -radius; top.p.y = radius; // The bottom left vertex Vertex2D bottom; bottom.p.x = -radius; bottom.p.y = -radius; for (int i = 0; i < points; i++) { // The x position of the first vertex along the middle line float prog = mid + ((static_cast <float> (i) / points) * (radius - mid)); // The x position of the second vertex along the middle line float next = mid + ((static_cast <float> (i + 1) / points) * (radius - mid)); // Each section needs 2 triangles, each with 3 vertices. Vertex2D varr[6]; // These are always the same varr[0] = top; varr[3] = bottom; // And the two tris always meet in the middle so we can use the same values for both varr[1].p.x = varr[4].p.x = prog; varr[2].p.x = varr[5].p.x = next; for (int i = 0; i < 6; i++) { // Assign 3 random color values varr[i].c.r = rand_float(); varr[i].c.g = rand_float(); varr[i].c.b = rand_float(); } verts.insert(std::end(verts), std::begin(varr), std::end(varr)); } }
Weapon weapon_create_rand(unsigned level) { static float table_weapon[] = { 1.f, 1.2f, 1.5f, 1.8f, 1.9f, 2.3f, 3.2f }; static int table_damage[] = { 10, 2, 30, 20 }; static float table_penArmor[] = { 5.0, 3.0, 7.0, 15.0 }; static float table_castTime[] = { 1.0f, 0.1f, 3.0f, 2.0f }; Weapon w; WeaponType wt = rand_born(0, W_LAST - 1); int mark = rand_born(0, MAXMARK(level)); float offset = table_weapon[mark]; float critic = rand_float(5.f, 21.f); w.damage = (int)(table_damage[wt] * offset + rand_born(0, 4 + (offset / 1.5))); w.penArmor = table_penArmor[wt] * offset; w.criticalChance = critic + (9 * offset); w.castTime = table_castTime[wt] / (offset); w.isVisible = true; w.type = wt; w.price = rand_float(1, 10) * ((mark + 1) * 1000); strcpy(w.name, gTable_markName[mark]); return w; }
void Jittered::generate_samples(void) { int n = (int) sqrt((float)num_samples); for (int p = 0; p < num_sets; p++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) { Point2D sp((k + rand_float()) / n, (j + rand_float()) / n); samples.push_back(sp); } }
void NRooks::generate_samples(void) { for (int p = 0; p < num_sets; p++) for (int j = 0; j < num_samples; j++) { Point2D sp((j + rand_float()) / num_samples, (j + rand_float()) / num_samples); samples.push_back(sp); } shuffle_x_coordinates(); shuffle_y_coordinates(); }
Particule::Particule(sf::Vector2i window_size, GameConfiguration * gameConfig, AudioConfiguration * audio) : shape(1, rand_int(3, 5)) { _radius_base = rand_float(0.05, 0.3); _window_size = window_size; _gameConfig = gameConfig; _audio = audio; speed = sf::Vector2f(rand_float(-0.5, 0.5),rand_float(-0.5, 0.1)); shape.setPosition(sf::Vector2f(rand_float(0.0f, (float) (window_size.x)),rand_float(0.0f, (float) (window_size.y)))); //shape.setPosition(sf::Vector2f(10,100)); shape.setFillColor(sf::Color(rand_int(0, 96), rand_int(0, 96), rand_int(0, 96))); }
void NRooks2D::generate_samples(void) { for (int j = 0; j < bundleSize_; j++) { Point2D sp( (j + rand_float()) / bundleSize_, (j + rand_float()) / bundleSize_ ); samples_.push_back(sp); } shuffle_x_coords(samples_); shuffle_y_coords(samples_); }
//---------------------------------------------------------------------- int main(int argc, char** argv) { printf("Hello, OpenCL\n"); //Setup our GLUT window and OpenGL related things //glut callback functions are setup here too init_gl(argc, argv); //initialize our CL object, this sets up the context example = new CL(); //load and build our CL program from the file #include "part2.cl" //std::string kernel_source is defined in this file example->loadProgram(kernel_source); //initialize our particle system with positions, velocities and color int num = NUM_PARTICLES; std::vector<Vec4> pos(num); std::vector<Vec4> vel(num); std::vector<Vec4> color(num); //fill our vectors with initial data for(int i = 0; i < num; i++) { //distribute the particles in a random circle around z axis float rad = rand_float(.2, .5); float x = rad*sin(2*3.14 * i/num); float z = 0.0f;// -.1 + .2f * i/num; float y = rad*cos(2*3.14 * i/num); pos[i] = Vec4(x, y, z, 1.0f); //give some initial velocity //float xr = rand_float(-.1, .1); //float yr = rand_float(1.f, 3.f); //the life is the lifetime of the particle: 1 = alive 0 = dead //as you will see in part2.cl we reset the particle when it dies float life_r = rand_float(0.f, 1.f); vel[i] = Vec4(0.0, 0.0, 3.0f, life_r); //just make them red and full alpha color[i] = Vec4(1.0f, 0.0f,0.0f, 1.0f); } //our load data function sends our initial values to the GPU example->loadData(pos, vel, color); //initialize the kernel example->popCorn(); //this starts the GLUT program, from here on out everything we want //to do needs to be done in glut callback functions glutMainLoop(); }
void Model::addNoise() { // Initialize random number generator std::uniform_real_distribution<float> rand_float(-0.05f, 0.05f); // Iterate all vertices and translate them randomly along their normal for(unsigned int i = 0; i < getAmountOfVertices(); i++) { auto vertex = getVertex(i); auto coeff = rand_float(m_random); auto newCoords = vertex.coords + coeff * vertex.normal; setVertex(vertex.id, newCoords, vertex.normal); } }
void stars_init(void) { int x; register_event("draw ortho", draw_stars); register_event("timer delta", update_stars); for(x=0; x<NUM_STARS; x++) { stars[x].v[0] = rand_int(640); stars[x].v[1] = rand_int(480); stars[x].v[2] = rand_float(); stars[x].v[3] = rand_float(); } }
int main(int argc, char const* argv[]) { srand((unsigned)time(NULL)); int i; for ( int i = 0; i < 1000; i++ ) { if ( !check_float( rand_float(), rand_float() ) ) { printf( "失敗\n" ); return 0; } } printf( "成功\n" ); return 0; }
void Jittered::generateSamples() { int n = (int) sqrt((float)numSamples); for(uint p=0;p<numSets;p++) for(uint j=0;j<n;j++) for(uint k=0;k<n;k++) { glm::vec2 sp((k + rand_float()) / n, (j + rand_float()) /n); samples.push_back(sp); } }
static void random_floats (argb_t *argb, int width) { int i; for (i = 0; i < width; ++i) { argb_t *p = argb + i; p->a = rand_float(); p->r = rand_float(); p->g = rand_float(); p->b = rand_float(); } }
Engine engine_create_rand(unsigned level) { static int table_evasion[] = { 10, 15, 25, 40, 50, 60, 70 }; Engine e; //EngineType et = rand_born(0, A_LAST); int mark = rand_born(0, MAXMARK(level)); e.evasionChance = table_evasion[mark]; e.isVisible = true; e.speed = 0; e.type = 0; e.price = rand_float(2, 11) * ((mark + 1) * 10000);; strcpy(e.name, gTable_markName[mark]); return e; }
int AcIndex::Open(std::string path) { Watch watch; ItemReader ir; int n = ir.Open(path); if (n <= 0) { return n; } int ram = 0, items = 0; while (ir.Hasremaing()) { AcItem ai = ir.Next(); ram += ai.show.Len() + 1; for (auto it = ai.indexes.begin(); it != ai.indexes.end(); ++it) { ram += it->index.Len() + 1; items += 1 + it->offs.Len(); if (it->check.Len() > 0) { ram += it->check.Len() + 1; } } } // skip 4 bytes this->data = Buffer((char *) malloc(ram + 4), 4, ram); this->indexes.reserve(items); this->name = base_name(path.data()); ir.Reset(); while (ir.Hasremaing()) { AcItem ai = ir.Next(); AcIndexItem ii; ii.show = data.Copy(ai.show); for (auto it = ai.indexes.begin(); it != ai.indexes.end(); ++it) { ii.index = data.Copy(it->index); ii.check = ii.show; if (it->check.Hasremaing()) { ii.check = data.Copy(it->check); } ii.score = it->score + rand_float(); indexes.push_back(ii); int idx = ii.index; for (int i = 0; i < it->offs.Len(); i++) { ii.score *= 0.95; ii.index = idx + it->offs[i]; indexes.push_back(ii); } } } ir.Close(); std::sort(indexes.begin(), indexes.end(), ByAlphabet(this->data)); if (ram > 1024 * 1024) { log_info("%s, %d items, %.2fm RAM, in %.1fms", this->name.c_str(), items, (items * sizeof(AcIndexItem) + ram) / 1024.0 / 1024, watch.Tick()); } return 1; }
float float_between(float min, float max) { float rnd_f = rand_float(); float scalar = max - min; rnd_f = rnd_f * scalar; rnd_f = rnd_f + min; return rnd_f; }
float *get_random(int nums) { int i; float *arr = malloc(sizeof(float) * nums * NARGS); for (i = 0; i < nums * NARGS; i++) { arr[i] = rand_float(); } return arr; }
//---------------------------------------------------------------------- int main(int argc, char** argv) { printf("Hello\n"); //Setup our GLUT window and OpenGL related things //glut callback functions are setup here too init_gl(argc, argv); //initialize our particle system with positions, velocities and color int num = NUM_PARTICLES; //create VBOs //fill our vectors with initial data for(int i = 0; i < num; i++) { //distribute the particles in a random circle around z axis float rad = rand_float(.2, .5); float x = rad*sin(2*3.14 * i/num); float z = 0.0f;// -.1 + .2f * i/num; float y = rad*cos(2*3.14 * i/num); pos[i] = Vec4(x, y, z, 1.0f); pos_gen[i]=pos[i]; //give some initial velocity //float xr = rand_float(-.1, .1); //float yr = rand_float(1.f, 3.f); //the life is the lifetime of the particle: 1 = alive 0 = dead //as you will see in part2.cl we reset the particle when it dies float life_r = rand_float(0.f, 1.f); vel[i] = Vec4(0.0, 0.0, 3.0f, life_r); vel_gen[i]=vel[i]; //just make them red and full alpha color[i] = Vec4(1.0f, 0.0f,0.0f, 1.0f); } p_vbo = createVBO(&pos[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW); c_vbo = createVBO(&color[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW); //this starts the GLUT program, from here on out everything we want //to do needs to be done in glut callback functions glutMainLoop(); }
void MultiJittered::generate_samples(void) { // num_samples needs to be a perfect square int n = (int)sqrt((float)num_samples); float subcell_width = 1.0 / ((float) num_samples); // fill the samples array with dummy points to allow us to use the [ ] notation when we set the // initial patterns Point2D fill_point; for (int j = 0; j < num_samples * num_sets; j++) samples.push_back(fill_point); // distribute points in the initial patterns for (int p = 0; p < num_sets; p++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { samples[i * n + j + p * num_samples].x = (i * n + j) * subcell_width + rand_float(0, subcell_width); samples[i * n + j + p * num_samples].y = (j * n + i) * subcell_width + rand_float(0, subcell_width); } // shuffle x coordinates for (int p = 0; p < num_sets; p++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { int k = rand_int(j, n - 1); float t = samples[i * n + j + p * num_samples].x; samples[i * n + j + p * num_samples].x = samples[i * n + k + p * num_samples].x; samples[i * n + k + p * num_samples].x = t; } // shuffle y coordinates for (int p = 0; p < num_sets; p++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { int k = rand_int(j, n - 1); float t = samples[j * n + i + p * num_samples].y; samples[j * n + i + p * num_samples].y = samples[k * n + i + p * num_samples].y; samples[k * n + i + p * num_samples].y = t; } }
glm::vec3 CRayTracer::sampleRandom(unsigned int a, unsigned int b, SRay &ray, float zw, const CScene &scene) const { // Start color of a pixel is black glm::vec3 color(0.f); // Random sampling for (unsigned int p = 0; p < m_viewPlane.samples * m_viewPlane.samples; ++p) { float x = m_viewPlane.pSize * (b - 0.5f * m_viewPlane.hRes + rand_float()); float y = m_viewPlane.pSize * (a - 0.5f * m_viewPlane.vRes + rand_float()); ray.origin = glm::vec3(x, y, zw); // Accumulate color color += traceRay(ray, scene); } color /= m_viewPlane.samples * m_viewPlane.samples; return color; }
int main(int argc, char** argv) { parse_args(argc, argv); /* printf("Running simulation for IR size(%d), outputbuffer size (%d): %d times using %d threads...\n", hSize, framesToOutput, nRuns, nThreads ); */ srand(1234); // Create Random impulse response double *h = new double[hSize]; for (int i = 0; i < hSize; i++) h[i] = rand_float(0, 1); // Create input stream int inputSize = framesToOutput * nRuns; double *input = new double[inputSize]; for (int i = 0; i < inputSize / 2; i++) input[i] = rand_float(0, 1); // Allocate output buffer double *output = new double[framesToOutput]; // Create convolver UniformConvolver uc(h, hSize, framesToOutput, nThreads); // Run simulation for all of the input and measure computation time double total = 0.0; for (int i = 0; i < inputSize / framesToOutput; i++) { double startTime = CycleTimer::currentSeconds(); uc.process(input+(i*framesToOutput), output); double endTime = CycleTimer::currentSeconds(); total += endTime - startTime; } double avg = 1000 * total / (inputSize / framesToOutput); /* printf("Avg Processing per period: %.4fms\n", avg); printf("Rate: %.4fms\n", avg / framesToOutput); */ printf("%.4f", avg / framesToOutput); return 0; }
void drop_fuel(Player *player) { if (CHANCE(3)) { if (player->hull.fuel.actual < player->hull.fuel.max) { float fuel = rand_float(10.f, 30.f); printf("\t- Vous recuperez %.1f fuel\n", fuel); player_setFuel(player, player->hull.fuel.actual + fuel, player->hull.fuel.max); } } }
void GameTrack::addSimpleDecal(DResource* resource,DUserClientObjectRenderFlags render_flag, dvect pos,dvect size,float rot) { DResource* color=0; DResource* normal=0; DResource* height=0; DResource* specular=0; if(render_flag & RENDER_FLAG_COLOR) color=resource; if(render_flag & RENDER_FLAG_NORMAL) normal=resource; if(render_flag & RENDER_FLAG_HEIGHT) height=resource; if(render_flag & RENDER_FLAG_SPECULAR) specular=resource; //DUserClientObject* obj=manager->client->createCar(color,normal,height,size); DUserClientObject* obj=manager->client->createObject(size); { DUserClientFreeGlutObject* fg_obj=(DUserClientFreeGlutObject*)obj; fg_obj->addTexture(resource); static DGLShader* shader=0; if(!shader) { shader=new DGLShader(); if(!shader->compileFullFromFile( "shader/base_vert.glsl", "shader/texture_frag.glsl")) { printf("Decal shader failed\n"); } } fg_obj->shader=shader; fg_obj->setFloat4(shader->getUniform("color"), rand_float(0,1), rand_float(0,1), rand_float(0,1),1); } obj->render_flags=render_flag; addDecal(obj,pos,rot); }
void Renderer::render_scene() { // Create QImage. *img = new QImage(scene->vp.hres, scene->vp.vres, QImage::Format_ARGB32); // Ray origin components... fixed Z for now. double x; double y; double z = 100.0; int num_samples = static_cast<int>(::sqrt(static_cast<float>(scene->vp.num_samples))); Ray ray(0.0, Vector3D(0.0, 0.0, -1.0)); RGBColor pixel_color; int final_pixel_color[3]; for (int r = 0; r < scene->vp.vres; ++r) { for (int c = 0; c < scene->vp.hres; ++c) { pixel_color = BLACK; // Right now, some simple jittered sampling for antialiasing. for (int p = 0; p < num_samples; ++p) { for (int q = 0; q < num_samples; ++q) { x = scene->vp.s * (c - 0.5 * scene->vp.hres + (q + rand_float()) / num_samples); y = scene->vp.s * (r - 0.5 * scene->vp.vres + (p + rand_float()) / num_samples); ray.o = Point3D(x, y, z); pixel_color += tracer->trace_ray(ray); } } // Average colors. pixel_color /= static_cast<float>(scene->vp.num_samples); // Prepare color for display and set it in the image. // TODO: setPixel is expensive... we need to move to direct access via scanLine. map_and_correct(pixel_color, final_pixel_color); int adj_row = scene->vp.vres - 1 - r; // QImage's origin is top left. Our origin is bottom left. (*img)->setPixel(c, adj_row, qRgba(final_pixel_color[0], final_pixel_color[1], final_pixel_color[2], 255)); } } }
float *loadSamples() { int i; float *samples; samples = (float*) malloc(SAMPLES * DIMENSION * sizeof(float)); for(i = 0; i < SAMPLES * DIMENSION; i++){ samples[i] = rand_float(-F_BOUNDING_BOX_RADIUS, F_BOUNDING_BOX_RADIUS); } return samples; }
int main(void) { point a, b, c; triangle t; int i; float sum=0.0; srand(time(NULL)); for (i = 0; i < N; i++) { a.x = rand_float(); a.y = rand_float(); b.x = rand_float(); b.y = rand_float(); c.x = rand_float(); c.y = rand_float(); if (!collinear(a, b, c)) { t.a = a; t.b = b; t.c = c; sum += area(t); } } printf("Average area: %f\n", sum/N); return 0; }
static void test_random_edits() { // This string should always have the same content as the rope. _string *str = str_create(); rope *r = rope_new(); const size_t max_stringsize = 1000; uint8_t strbuffer[max_stringsize + 1]; for (int i = 0; i < 1000; i++) { // First, some sanity checks. check(r, (char *)str->mem); rope *r2 = rope_copy(r); check(r2, (char *)str->mem); rope_free(r2); // printf("String contains '%s'\n", str->mem); test(rope_byte_count(r) == str->len); size_t len = strlen_utf8(str->mem); test(rope_char_count(r) == len); test(str_num_chars(str) == len); if (len == 0 || rand_float() < 0.5f) { // Insert. //uint8_t *text = random_ascii_string(11); random_unicode_string(strbuffer, 1 + random() % max_stringsize); size_t pos = random() % (len + 1); // printf("inserting %s at %zd\n", strbuffer, pos); rope_insert(r, pos, strbuffer); str_insert(str, pos, strbuffer); } else { // Delete size_t pos = random() % len; size_t dellen = random() % 10; dellen = MIN(len - pos, dellen); // printf("deleting %zd chars at %zd\n", dellen, pos); //deletedText = str[pos...pos + length] //test.strictEqual deletedText, r.substring pos, length rope_del(r, pos, dellen); str_del(str, pos, dellen); } } rope_free(r); str_destroy(str); }