Vector3 Vector3::randomInSphere(double radius, bool only_surface, RandomGenerator &random) { // TODO More uniform spatial repartition // The current randomization clusters result near the center and at the poles VectorSpherical vec = {only_surface ? radius : random.genDouble() * radius, (random.genDouble() - 0.5) * Maths::PI, random.genDouble() * Maths::TWOPI}; return Vector3(vec); }
void AnalyticGeometry::computeOrthonormalFrameForPlane3(const double* p, const double* n, double** frame) { RandomGenerator rgen; double q[3], x[3], y[3], proj[3]; do { // Get a random point "around" the plane point 'p' q[0] = rgen.getRandomNumberInInterval(-1.0, 1.0) + p[0]; q[1] = rgen.getRandomNumberInInterval(-1.0, 1.0) + p[1]; q[2] = rgen.getRandomNumberInInterval(-1.0, 1.0) + p[2]; // Project it on the plane AnalyticGeometry::projectOnPlane3(q, p, n, proj); // Get the connecting vector Vector::diff(proj, p, x); } while ( Vector::length3(x) < 0.0001 ); // Normalize 'x': this will be the x-axis Vector::normalize3(x); // Compute the y-axis Vector::cross3(n, x, y); // Save the frame frame[0][0] = x[0]; frame[0][1] = y[0]; frame[0][2] = n[0]; frame[1][0] = x[1]; frame[1][1] = y[1]; frame[1][2] = n[1]; frame[2][0] = x[2]; frame[2][1] = y[2]; frame[2][2] = n[2]; }
void Rain::update(float dt) { //const int count = m_materials.size(); for (int m=0; m<RAIN_RING_COUNT; m++) { m_x[m] = m_x[m] + dt*RAIN_DX; m_y[m] = m_y[m] + dt*RAIN_DY; if (m_x[m] > 1.0f) m_x[m] = fmod(m_x[m], 1.0f); if (m_y[m] > 1.0f) m_y[m] = fmod(m_y[m], 1.0f); core::matrix4& matrix = m_node[m]->getChild()->getMaterial(0).getTextureMatrix(0); matrix.setTextureTranslate(m_x[m], m_y[m]); } if (m_lightning) { m_next_lightning -= dt; if (m_next_lightning < 0.0f) { RaceGUIBase* gui_base = World::getWorld()->getRaceGUI(); if (gui_base != NULL) { gui_base->doLightning(); if (m_thunder_sound) m_thunder_sound->play(); } RandomGenerator g; m_next_lightning = 35 + (float)g.get(35); } } } // update
int main() { RandomGenerator r; int f[5] = {0}; int f2[12] = {0}; double num; for(unsigned int i = 0; i < 3000000; i++) { num = r.uniform_0_1(); if (num == 0.0) f2[11]++; else if (num == 1.0) f2[10]++; else if (num < 0.1) f2[0]++; else if (num < 0.2) f2[1]++; else if (num < 0.3) f2[2]++; else if (num < 0.4) f2[3]++; else if (num < 0.5) f2[4]++; else if (num < 0.6) f2[5]++; else if (num < 0.7) f2[6]++; else if (num < 0.8) f2[7]++; else if (num < 0.9) f2[8]++; else if (num < 1) f2[9]++; } cout << "0-1" << endl; for(int i = 0; i < 12; i++) { cout << i << ": " << f2[i] << endl; } for(int i = 0; i < 1000; i++) { f[r.uniform_n(4)]++; } cout << "n" << endl; for(int i = 0; i < 5; i++) { cout << i << ": " << f[i] << endl; } return 0; }
Vehicle *VehicleFactory::createRandomVehicle() { Vehicle * vehicle; // RandomGenerator * ranGen = new RandomGenerator(1,3); // int randomNumber =0; // randomNumber = ranGen->createRandomNumber(); RandomGenerator * ranGen; int randomNumber =0; randomNumber = ranGen->createRandomNumber(1,3); qDebug()<< "result" << randomNumber ; //trying to minimise if statments switch(randomNumber == 1) { case 1: // vehicle = new RegularCar(asubject,0,0,0.0,0,0);//this has to be changed (0,0,0); return vehicle; break; case 2: // vehicle = new PoliceCar(asubject,0,0,0.0,0,0);//this has to be changed (0,0,0); return vehicle; break; case 3: // vehicle = new PoliceCar(asubject,0,0,0.0,0,0);//this has to be changed (0,0,0); return vehicle; break; } }
void RandomData(PEER_ADDRESS& addr) { RandomGenerator rnd; addr.IP = rnd.NextDWord(); addr.TcpPort = rnd.NextWord(); addr.UdpPort = rnd.NextWord(); }
int main() { for (int i = 0; i < 20; ++i) { std::cout << mainRandomGenerator.getRandom(0, 1) << " "; } std::cout << std::endl; for (int i = 0; i < 20; ++i) { std::cout << mainRandomGenerator.getRandom(0.2f, 0.2f) << " "; } std::cout << std::endl; for (int i = 0; i < 20; ++i) { std::cout << getInt(0, 10) << " "; } std::cout << std::endl; for (int i = 0; i < 20; ++i) { std::cout << getFloat(0.0f, 1.0f) << " "; } std::cout << std::endl; std::cout << getString(100) << std::endl; }
// ---------------------------------------------------------------------------- void TrackObjectPresentationMesh::reset() { if (m_node->getType()==scene::ESNT_ANIMATED_MESH) { scene::IAnimatedMeshSceneNode *a_node = (scene::IAnimatedMeshSceneNode*)m_node; a_node->setPosition(m_init_xyz); a_node->setRotation(m_init_hpr); a_node->setScale(m_init_scale); a_node->setLoopMode(m_is_looped); a_node->setAnimationEndCallback(NULL); a_node->setCurrentFrame((float)(a_node->getStartFrame())); // trick to reset the animation AND also the timer inside it a_node->OnAnimate(0); a_node->OnAnimate(0); // irrlicht's "setFrameLoop" is a misnomer, it just sets the first and // last frame, even if looping is disabled RandomGenerator rg; int animation_set = 0; if (a_node->getAnimationSetNum() > 0) animation_set = rg.get(a_node->getAnimationSetNum()); a_node->useAnimationSet(animation_set); } } // reset
/* * Generating samples * */ void DataGenerator::t_sink(void) { RandomGenerator randomGenerator; int packetCounter = 1; int currentSample = 1; //1021 samples per TimeWindow, 10 bit per sample int currentTimeWindow = 0; //Produce samples for given number of time windows while(currentTimeWindow < constants::NUMBER_TIME_WINDOWS_TO_SIMULATE) { //foreach channel for every SAMPA chip for(int i = 0; i < (constants::NUMBER_OF_SAMPA_CHIPS * constants::SAMPA_NUMBER_INPUT_PORTS); i++) { //decide whether sending a sample to the particular channel or not //Her er det plass for å implemenetere gauss fordeling //Et godt alternativ er å hente data fra en Excel fil, Excel kan generere normaldistribusjon //Her kan ogsa injisere real data if(randomGenerator.generate(0, 100) < constants::DG_OCCUPANCY) { //Create a new sample Sample sample(currentTimeWindow, packetCounter, 0); //Send a sample to appropriate SAMPA and SAMPAs channel porter_DG_to_SAMPA[i]->nb_write(sample); //Save event to the logfile write_log_to_file_sink(packetCounter, i, currentTimeWindow); } //bypass Data Generator with 100% occupancy else if (false) //else if((currentTimeWindow == 0 || currentTimeWindow == 1) && (i < 30)) //else if((currentTimeWindow == 0 || currentTimeWindow == 1) && (i==0 || i==1 || i==2)) //else if(i == 12) { //Create a new sample Sample sample(currentTimeWindow, packetCounter, 0); //Send a sample to appropriate SAMPA and SAMPAs channel porter_DG_to_SAMPA[i]->nb_write(sample); //Save event to the logfile write_log_to_file_sink(packetCounter, i, currentTimeWindow); } //Go to the next sample packetCounter++; //sample id } //If this time window is done, go to next time window if(currentSample == constants::NUMBER_OF_SAMPLES_IN_EACH_TIME_WINDOW )//1021 samples { currentTimeWindow++; currentSample = 0; std::cout << "currrent time window: " << currentTimeWindow << ", TimeStamp: " << sc_time_stamp() << std::endl; } //Each sample gets its own unique id (currentSample) //Can be used to identify samples and to track path of the sample in logfile //or in the code std::cout << "currrent timebin: " << currentSample << ", TimeStamp: " << sc_time_stamp() << std::endl; currentSample++; //SAMPA receives 10-bit data on 10 MHz wait(constants::DG_WAIT_TIME, SC_NS); } }
SubMediaPiecePtr Storage::GetSubPiece(UINT64 inTS) const { SubMediaPiecePtr subPiece; if (m_dataPieces.size() > 2) { MediaDataPiecePtr minPiece = m_dataPieces.begin()->second.GetPiece(); MediaDataPiecePtr maxPiece = m_dataPieces.rbegin()->second.GetPiece(); if (inTS >= minPiece->GetTimeStamp() && inTS <= maxPiece->GetTimeStamp()) { double indexDurationOf1s = (double)(maxPiece->GetPieceIndex() - minPiece->GetPieceIndex()) / (double)(maxPiece->GetTimeStamp() - minPiece->GetTimeStamp()) ; UINT32 iterIndex = minPiece->GetPieceIndex() + indexDurationOf1s * (inTS - minPiece->GetTimeStamp()); LIMIT_MIN_MAX(iterIndex, minPiece->GetPieceIndex(), maxPiece->GetPieceIndex()); PieceInfoCollection::const_iterator iter = m_dataPieces.lower_bound(iterIndex); LIVE_ASSERT( iter != m_dataPieces.end() ); while (iter != m_dataPieces.begin() && inTS < iter->second.GetPiece()->GetTimeStamp()) { iter--; } while (iter != m_dataPieces.end() && inTS > iter->second.GetPiece()->GetTimeStamp()) { iter++; } if (iter != m_dataPieces.end()) { RandomGenerator random; subPiece = iter->second.GetSubPiece(random.Next() % iter->second.GetSubPieceCount()); } } } return subPiece; }
//--------------------------------------------------------------------------------------- wxString IdfyScalesCtrol::set_new_problem() { //This method must prepare the problem score and set variables: // m_pProblemScore - The score with the problem to propose // m_pSolutionScore - The score with the solution or NULL if it is the // same score than the problem score. // m_sAnswer - the message to present when displaying the solution // m_nRespIndex - the number of the button for the right answer // m_nPlayMM - the speed to play the score // //It must return the message to display to introduce the problem. //select a random mode m_fAscending = m_pConstrains->GetRandomPlayMode(); // generate a random scale EScaleType nScaleType = m_pConstrains->GetRandomScaleType(); // select a key signature RandomGenerator oGenerator; m_nKey = oGenerator.generate_key( m_pConstrains->GetKeyConstrains() ); // for minor scales use minor key signature and for major scales use a major key if (Scale::is_minor(nScaleType) && is_major_key(m_nKey)) m_nKey = get_relative_minor_key(m_nKey); else if (!Scale::is_minor(nScaleType) && is_minor_key(m_nKey)) m_nKey = get_relative_major_key(m_nKey); //Generate a random root note EClef nClef = k_clef_G2; m_fpRootNote = oGenerator.get_best_root_note(nClef, m_nKey); //hide key signature if requested or not tonal scale bool fDisplayKey = m_pConstrains->DisplayKey() && Scale::is_tonal(nScaleType); if (!fDisplayKey) m_nKey = k_key_C; //create the score m_sAnswer = prepare_score(nClef, nScaleType, &m_pProblemScore); //compute the index for the button that corresponds to the right answer int i; for (i = 0; i < k_num_buttons; i++) { if (m_nRealScale[i] == nScaleType) break; } m_nRespIndex = i; //if two solutions (minor/major or Gregorian mode) disable answer buttons //for the not valid answer DisableGregorianMajorMinor(nScaleType); //return string to introduce the problem if (m_pConstrains->is_theory_mode()) return _("Identify the next scale:"); else return ""; // return _("Press 'Play' to hear it again"); }
Enemy::Enemy(int lvl) : EnemyBase() { level = lvl; RandomGenerator rg = RandomGenerator(); name = EnemyName[rg.getRandom(0,5)]; state = EnemyState[rg.getRandom(0, 5)]; health = rg.getRandom(2, 6); alive = true; }
RandomVariable::RandomVariable(Distribution * distribution) { static RandomGenerator gen; this->distribution = distribution; std::stringstream idStream; idStream << gen.nextDouble() + clock(); this->randomVariableID = idStream.str(); graph.addRandomVariable(*this, idStream.str()); }
/// /// add() : Add a ColorSeries with "levels" levels to the stack. /// void ColorSeriesStack::add(unsigned levels){ // 2015.09.15.ET: "levels" here is the number of NON-MISSING levels and it is possible // and in fact likely to only have one NON-MISSING level ColorSeries *pCS; unsigned n = _colorSeriesStack.size(); if(n<DrawingMetrics::monochromat.size()){ // // Use predefined color series based on DrawingMetrics colors: // switch(_type){ case BLACKANDWHITE: pCS = new ColorSeries(levels,DrawingColor("black","#000")); break; case MONOCHROMATIC: pCS = new ColorSeries(levels,DrawingMetrics::monochromat[n]); break; case BICHROMATIC: pCS = new ColorSeries(levels,DrawingMetrics::monochromat[n],DrawingMetrics::bichromat[n]); break; } }else{ if( _type==BLACKANDWHITE ){ pCS = new ColorSeries(levels,DrawingColor("black","#000")); }else{ // // Use random colors: // RandomGenerator r; DrawingColor color1; // // Randomly choose a color with at least 50% saturation and 50% value: // i.e., we choose relatively brighter and more saturated colors ... // color1.setFromHSV(r.getIntegerInRange(0,360),r.getIntegerInRange(50,100),r.getIntegerInRange(50,100)); if(_type==BICHROMATIC){ // Set color2 to the complement of color1: DrawingColor color2; color2.set(color1.getComplement()); pCS = new ColorSeries(levels,color1,color2); }else{ pCS = new ColorSeries(levels,color1); } } } _colorSeriesStack.push_back(pCS); }
/** Picks a random message to be displayed when a kart is hit by a plunger. * \param The kart that was hit (ignored here). * \returns The string to display. */ const core::stringw Plunger::getHitString(const AbstractKart *kart) const { const int PLUNGER_IN_FACE_STRINGS_AMOUNT = 2; RandomGenerator r; switch (r.get(PLUNGER_IN_FACE_STRINGS_AMOUNT)) { //I18N: shown when a player receives a plunger in his face case 0: return _LTR("%0 gets a fancy mask from %1"); //I18N: shown when a player receives a plunger in his face case 1: return _LTR("%1 merges %0's face with a plunger"); default:assert(false); return L""; // avoid compiler warning } } // getHitString
void RandomPeer(CANDIDATE_PEER_INFO& info) { RandomGenerator rnd; info.Address.IP = rnd.NextDWord(); info.Address.TcpPort = rnd.NextWord(); info.Address.UdpPort = rnd.NextWord(); info.CoreInfo.PeerType = rnd.NextByte(); info.CoreInfo.Reserved = rnd.NextByte(); for (int i = 0; i < 7; ++i) { info.CoreInfo.Reserved1[i] = rnd.NextByte(); } }
//--------------------------------------------------------------------------------------- bool ScalesConstrains::GetRandomPlayMode() { //return 'true' for ascending and 'false' for descending if (m_nPlayMode == 0) //ascending return true; else if (m_nPlayMode == 1) //descending return false; else { // both modes allowed. Choose one at random RandomGenerator oGenerator; return oGenerator.flip_coin(); } }
/*TODO: this only works if all actions can be performed from all states, which is not the case for generic MDPs.*/ void Policy::initializeRandomly() { RandomGenerator *generator = RandomGenerator::getRandomGenerator(); /*FIXME: this might mess the generator used to generate tasks, and therefore the comparison with other freqGovernors be invalid.*/ ActionSpace *actionSpace = ActionSpace::getActionSpace(); for (int i = 0; i < nbOfStates; i++) { std::vector<double> vector = generator->drawDistribution(actionSpace->size()); update(i, vector); } }
Warp::Warp(int width, int height, float persistence, int scale, RandomGenerator& rng) { _width = width; _height = height; _persistence = persistence; _scale = scale; for(int i = 0; i < 256; i += 1) { _rnd[i] = rng.getRandom() % 255; } for(int i = 0; i < 256; i += 1) { _grads[i] = Vec2(rng.getUniform(), rng.getUniform()).normalize(); } }
/** Picks a random message to be displayed when a kart is hit by the * rubber ball. * \param The kart that was hit (ignored here). * \returns The string to display. */ const core::stringw RubberBall::getHitString(const AbstractKart *kart) const { const int COUNT = 2; RandomGenerator r; switch (r.get(COUNT)) { //I18N: shown when a player is hit by a rubber ball. %1 is the // attacker, %0 is the victim. case 0: return _LTR("%s is being bounced around."); //I18N: shown when a player is hit by a rubber ball. %1 is the // attacker, %0 is the victim. case 1: return _LTR("Fetch the ball, %0!"); default:assert(false); return L""; // avoid compiler warning } } // getHitString
const wchar_t* getPlungerInFaceString() { const int PLUNGER_IN_FACE_STRINGS_AMOUNT = 2; RandomGenerator r; const int id = r.get(PLUNGER_IN_FACE_STRINGS_AMOUNT); switch (id) { //I18N: shown when a player receives a plunger in his face case 0: return _("%0 gets a fancy mask from %1"); //I18N: shown when a player receives a plunger in his face case 1: return _("%1 merges %0's face with a plunger"); default:assert(false); return L""; // avoid compiler warning } }
/** Returns a random hue when colorized. */ float getRandomHue() { if (m_hue_settings.empty()) return 0.0f; const unsigned int hue = m_random_hue.get(m_hue_settings.size()); assert(hue < m_hue_settings.size()); return m_hue_settings[hue]; }
int getInt(int min, int max) { #ifdef HYDRA_FAKE_RANDOM_INT return HYDRA_FAKE_RANDOM_INT; #else return mainRandomGenerator.getRandom(min, max); #endif }
void LatinHypercube(const RandomGenerator &rng, float *samples, u_int nSamples, u_int nDim) { // Generate LHS samples along diagonal float delta = 1.f / nSamples; for (u_int i = 0; i < nSamples; ++i) for (u_int j = 0; j < nDim; ++j) samples[nDim * i + j] = (i + rng.floatValue()) * delta; // Permute LHS samples in each dimension for (u_int i = 0; i < nDim; ++i) { for (u_int j = 0; j < nSamples; ++j) { u_int other = rng.uintValue() % nSamples; swap(samples[nDim * j + i], samples[nDim * other + i]); } } }
Path<VertexType, RandomGenerator> makeLightPath( const Scene& scene, const PowerBasedLightSampler& sampler, const RandomGenerator& rng) { const Light* pLight = nullptr; float lightPdf, positionPdfGivenLight; auto lightSample = rng.getFloat(); auto positionSample = rng.getFloat2(); auto dirSample = rng.getFloat2(); return { scene, samplePrimaryLightVertex(scene, sampler, lightSample, positionSample, dirSample, pLight, lightPdf, positionPdfGivenLight), rng }; }
void Shuffle(const RandomGenerator &rng, u_int *samp, u_int count, u_int dims) { for (u_int i = 0; i < count; ++i) { u_int other = rng.uintValue() % count; for (u_int j = 0; j < dims; ++j) swap(samp[dims*i + j], samp[dims*other + j]); } }
// Sampling Function Definitions void StratifiedSample1D(const RandomGenerator &rng, float *samp, u_int nSamples, bool jitter) { float invTot = 1.f / nSamples; for (u_int i = 0; i < nSamples; ++i) { float delta = jitter ? rng.floatValue() : 0.5f; *samp++ = (i + delta) * invTot; } }
const Production& Definition::getRandomProduction() const { int low = 0; int high = possibleExpansions.size () - 1; // Convert from count to index. int returnIndex = rg.getRandomInteger (low, high); assert (returnIndex >= low && returnIndex <= high); return possibleExpansions.at (returnIndex); }
namespace kurento { class RandomGenerator { boost::uuids::basic_random_generator<boost::mt19937> gen; boost::mt19937 ran; pid_t pid; public: RandomGenerator () : gen (&ran) { init (); } void init () { std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now(); std::chrono::nanoseconds time = std::chrono::duration_cast<std::chrono::nanoseconds> (now.time_since_epoch () ); ran.seed (time.count() ); pid = getpid(); } void reinit () { if (pid != getpid() ) { init(); } } std::string getUUID () { reinit(); std::stringstream ss; boost::uuids::uuid uuid = gen (); ss << uuid; return ss.str(); } }; static RandomGenerator gen; std::string generateUUID () { return gen.getUUID (); } }
//--------------------------------------------------------------------------------------- wxString IdfyTonalityCtrol::set_new_problem() { //This method must prepare the problem score and set variables: // m_pProblemScore, m_pSolutionScore, m_sAnswer, m_nRespIndex and m_nPlayMM // select a key signature RandomGenerator oGenerator; m_nKey = oGenerator.generate_key( m_pConstrains->GetKeyConstrains() ); //create the score EClef nClef = k_clef_G2; m_sAnswer = prepare_score(nClef, m_nKey, &m_pProblemScore); //compute the index for the button that corresponds to the right answer ComputeRightAnswerButtons(); //return string to introduce the problem return _("Press 'Play' to hear the problem again."); }