// Stochastic universal resampling void resample() { double variance = ras::variance(particle_weight); std::copy(particle_state.begin(), particle_state.end(), particle_state_aux.begin()); std::copy(particle_weight.begin(), particle_weight.end(), particle_weight_aux.begin()); // TODO normalize goes here?? ras::normalize(particle_weight); // TODO what is resample_variance if (variance >= resample_variance) { ras::cumsum(particle_weight, cdf_aux); std::uniform_real_distribution<double> distribution(0.0, 1.0 / (double) P); double r0 = distribution(generator); for (int m = 0; m < P; m++) { double cdf_thre = r0 + (double) m / P; //Resampling condition int j; for (j = 0; cdf_aux[j] < cdf_thre && j < P; j++); particle_state[m].x = particle_state_aux[j].x; particle_state[m].y = particle_state_aux[j].y; particle_state[m].theta = particle_state_aux[j].theta; particle_weight[m] = particle_weight_aux[j]; } } }
void AnimalAIView::update(int timeStep) { Vector<double> position = controllingAnimal.getPosition(); target.x += distribution(generator)*30; target.y += distribution(generator)*30; target.normalize(); target.x *= radius; target.y *= radius; Vector<double> targetLocal = target; Vector<double> worldLocation; worldLocation.x = position.x + targetLocal.x; worldLocation.y = position.y + targetLocal.y; Vector<double> direction(worldLocation); direction.x -= position.x; direction.y -= position.y; controllingAnimal.setSpeed(50); controllingAnimal.setDirection(direction); }
AudioMixerClientData::AudioMixerClientData(const QUuid& nodeID, Node::LocalID nodeLocalID) : NodeData(nodeID, nodeLocalID), audioLimiter(AudioConstants::SAMPLE_RATE, AudioConstants::STEREO), _outgoingMixedAudioSequenceNumber(0), _downstreamAudioStreamStats() { // of the ~94 blocks in a second of audio sent from the AudioMixer, pick a random one to send out a stats packet on // this ensures we send out stats to this client around every second // but do not send all of the stats packets out at the same time std::random_device randomDevice; std::mt19937 numberGenerator { randomDevice() }; std::uniform_int_distribution<> distribution { 1, (int) ceil(1.0f / AudioConstants::NETWORK_FRAME_SECS) }; _frameToSendStats = distribution(numberGenerator); }
void KinematicEngine::fillTreeWithValues(KinematicTree &tree, kinematics::MotorValuesMap values, kinematics::MotorValuesMap speeds, bool addNoise) { std::uniform_real_distribution<double> distribution(-m_valueNoise, m_valueNoise); for (std::pair<const MotorID, double>& value : values) { double noise = 0.; if (addNoise) { noise = distribution(generator); } value.second += noise; } for (std::pair<const kinematics::NodeID, KinematicNode*> nodeP : tree.getNodes()) { KinematicNode * node = nodeP.second; kinematics::MotorIDs const& motors = node->getMotors(); kinematics::MotorValuesMap valuesForNode; kinematics::MotorValuesMap valueDerivativesForNode; for (MotorID const& id : motors) { if (values.find(id) != values.end()) { // this motor is accessible for inverse kinematics valuesForNode[id] = values.at(id); } if (speeds.find(id) != speeds.end()) { valueDerivativesForNode[id] = speeds.at(id); } } node->setValues(valuesForNode); node->setValueDerivatives(valueDerivativesForNode); } }
void GenerateMacAddress(const MACConsumer type, u8* mac) { memset(mac, 0, MAC_ADDRESS_SIZE); u8 const oui_bba[] = {0x00, 0x09, 0xbf}; u8 const oui_ios[] = {0x00, 0x17, 0xab}; switch (type) { case MACConsumer::BBA: memcpy(mac, oui_bba, 3); break; case MACConsumer::IOS: memcpy(mac, oui_ios, 3); break; } // Generate the 24-bit NIC-specific portion of the MAC address. std::default_random_engine generator(Common::Timer::GetTimeMs()); std::uniform_int_distribution<int> distribution(0x00, 0xFF); mac[3] = static_cast<u8>(distribution(generator)); mac[4] = static_cast<u8>(distribution(generator)); mac[5] = static_cast<u8>(distribution(generator)); }
void Chromosome<T>::gaussianMutation(double mutation_rate) { double probability; std::normal_distribution<double> distribution = std::normal_distribution<double>((lower_boundary + upper_boundary) / 2, lower_boundary / 2 + upper_boundary); for (unsigned int i = 0; i < size; i++) { probability = std::generate_canonical<double, std::numeric_limits<double>::digits>(generator); if (probability < mutation_rate) { chromosome_values[i] += distribution(generator); if (chromosome_values[i] > upper_boundary) chromosome_values[i] = upper_boundary; else if (chromosome_values[i] < lower_boundary) chromosome_values[i] = lower_boundary; } } }
void DifferentialEvolution::initialize_vector(Parameters &ctl_pars) { std::uniform_real_distribution<double> distribution(0.0, 1.0); for (const auto &i : parameter_info) { double p_val; const string &p_name = i.first; double rnum = rand_engine(); // use uniform distribution to initialize parameters if (i.second.log_transform) { double r_num = distribution(rand_engine); p_val = log10(i.second.lower_bnd) + r_num * (log10(i.second.upper_bnd) - log10(i.second.lower_bnd)); p_val = pow(10.0, p_val); ctl_pars.insert(p_name, p_val); } else { p_val = i.second.lower_bnd + distribution(rand_engine) * (i.second.upper_bnd - i.second.lower_bnd); ctl_pars.insert(p_name, p_val); } } }
static Image addRandomNoiseToImage(const Image& image, float noiseMagnitude, std::default_random_engine& engine) { Image copy = image; size_t xPixels = image.x(); size_t yPixels = image.y(); size_t colors = image.colorComponents(); std::uniform_real_distribution<float> distribution(-noiseMagnitude, noiseMagnitude); for(size_t y = 0; y != yPixels; ++y) { for(size_t x = 0; x != xPixels; ++x) { for(size_t c = 0; c != colors; ++c) { float value = distribution(engine) + image.getStandardizedComponentAt(x, y, c); if(value < -1.0f) { value = -1.0f; } if(value > 1.0f) { value = 1.0f; } copy.setStandardizedComponentAt(x, y, c, value); } } } return copy; }
int main() { async_task<int(int)> async_d6{[&](std::size_t seed) -> int { std::mt19937 generator{seed}; std::uniform_int_distribution<int> distribution{1, 6}; auto r = distribution(generator); std::this_thread::sleep_for(std::chrono::seconds(r)); std::cout << "Slept for " << r << " seconds.\n"; // race on purpose return r; }}; std::random_device rng; auto die1 = async_d6(rng()); auto die2 = async_d6(rng()); std::cout << "Total is: " << die1.get() + die2.get(); }
void randomGenWithSeed( const Vector2 range, const int limit, VectorLong& output, const int seed ) { // generator type defined and initialized by a seed value generator_type generator( seed ); // define uniform random number distribution which produces type double values // between [min,max) for each orbital element. For more details please refer to // the following web link: // http://www.boost.org/doc/libs/1_60_0/libs/random/example/random_demo.cpp boost::uniform_real<> distribution( range[ 0 ], range[ 1 ] ); boost::variate_generator<generator_type&, boost::uniform_real<> > uniform(generator, distribution); for(int i = 0; i < limit; i++) { output[ i ] = uniform(); } }
// ----------------------------------------------------------------------------- //Function to generate a randomized list from a given input list // ----------------------------------------------------------------------------- VoxelUpdateList::Pointer BFReconstructionEngine::GenRandList(VoxelUpdateList::Pointer InpList) { VoxelUpdateList::Pointer OpList; const uint32_t rangeMin = 0; const uint32_t rangeMax = std::numeric_limits<uint32_t>::max(); typedef boost::uniform_int<uint32_t> NumberDistribution; typedef boost::mt19937 RandomNumberGenerator; typedef boost::variate_generator<RandomNumberGenerator&, NumberDistribution> Generator; NumberDistribution distribution(rangeMin, rangeMax); RandomNumberGenerator generator; Generator numberGenerator(generator, distribution); boost::uint32_t arg = static_cast<boost::uint32_t>(EIMTOMO_getMilliSeconds()); generator.seed(arg); // seed with the current time int32_t ArraySize = InpList.NumElts; OpList.NumElts = ArraySize; OpList.Array = (struct ImgIdx*)(malloc(ArraySize * sizeof(struct ImgIdx))); size_t dims[3] = { ArraySize, 0, 0}; Int32ArrayType::Pointer Counter = Int32ArrayType::New(dims, "Counter"); for (int32_t j_new = 0; j_new < ArraySize; j_new++) { Counter->d[j_new] = j_new; } for(int32_t test_iter = 0; test_iter < InpList.NumElts; test_iter++) { int32_t Index = numberGenerator() % ArraySize; OpList.Array[test_iter] = InpList.Array[Counter->d[Index]]; Counter->d[Index] = Counter->d[ArraySize - 1]; ArraySize--; } #ifdef DEBUG if(getVerbose()) { std::cout << "Input" << std::endl; } maxList(InpList); if(getVerbose()) { std::cout << "Output" << std::endl; } maxList(OpList); #endif //Debug return OpList; }
QList<glm::vec2> StratifiedPixelSampler::GetSamples(int x, int y) { QList<glm::vec2> result; float a( x - .5f ); float b( y - .5f ); float c( 1.f / samples_sqrt ); for( int i = 0; i < samples_sqrt; ++i ){ for( int j = 0; j < samples_sqrt; ++j ){ result.push_back( glm::vec2( a + c * i + c * distribution( generator ), b + c * i + c * distribution( generator ) ) ); } } return result; }
Die::Die(int nFaces) { #if defined(_WIN32) static unsigned seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); ++seed; std::mt19937 generator{seed}; #else std::random_device rdev{}; std::mt19937 generator{rdev()}; #endif // defined std::uniform_int_distribution<int> distribution(1, nFaces); rollDie = std::bind(distribution, generator); m_nFaces = nFaces; m_pnDieRollValues = new int[m_nFaces](); }
void NormalMutationOperatorCPU::doMutation(Population& _population) { vector<IndividualPtr> individuals = _population.getIndividuals(); int representation_size = _population.getRepresentationSize(); for(IndividualPtr ind: individuals) { RepresentationPtr representation = ind->getRepresentation(); for(int i = 0; i < representation_size; ++i) { if(prob_distribution(generator) <= probability) representation->at(i) += distribution(generator); } } }
T uniformRandomInteger() { // setup generator and distribution typedef boost::mt19937 GeneratorType; typedef boost::uniform_int<T> DistributionType; GeneratorType generator(std::time(NULL)); DistributionType distribution(std::numeric_limits<T>::min(), std::numeric_limits<T>::max()); // create variate generator boost::variate_generator<GeneratorType, DistributionType> vg(generator, distribution); // return random number return vg(); }
distribution load_distribution( JsonObject &jo ) { if( jo.has_float( "constant" ) ) { return distribution::constant( jo.get_float( "constant" ) ); } if( jo.has_float( "one_in" ) ) { return distribution::one_in( jo.get_float( "one_in" ) ); } if( jo.has_array( "dice" ) ) { JsonArray jarr = jo.get_array( "dice" ); return distribution::dice_roll( jarr.get_int( 0 ), jarr.get_int( 1 ) ); } if( jo.has_array( "rng" ) ) { JsonArray jarr = jo.get_array( "rng" ); return distribution::rng_roll( jarr.get_int( 0 ), jarr.get_int( 1 ) ); } if( jo.has_array( "sum" ) ) { JsonArray jarr = jo.get_array( "sum" ); JsonObject obj = jarr.next_object(); distribution ret = load_distribution( obj ); while( jarr.has_more() ) { obj = jarr.next_object(); ret = ret + load_distribution( obj ); } return ret; } if( jo.has_array( "mul" ) ) { JsonArray jarr = jo.get_array( "mul" ); JsonObject obj = jarr.next_object(); distribution ret = load_distribution( obj ); while( jarr.has_more() ) { obj = jarr.next_object(); ret = ret * load_distribution( obj ); } return ret; } jo.throw_error( "Invalid distribution" ); return distribution(); }
void Game::update(sf::Time time) { if (currentCell.x < 0) currentCell.x = 0; if (currentCell.y < 0) currentCell.y = 0; if (currentCell.x >= 10) currentCell.x = 9; if (currentCell.y >= 10) currentCell.y = 9; timeLeft = (int) ceilf(gameTime - clock.getElapsedTime().asSeconds()); if (timeLeft == 0) { lastScore = score; score = 0; clock.restart(); } if (calculate) { int result = 0; for (auto cell : selectedCells) { result += grid[cell.y][cell.x]; } if (result == 10) { score += pow(2, selectedCells.size()); for (auto cell : selectedCells) { grid[cell.y][cell.x] = (short) distribution(generator); } soundMatch.play(); } calculate = false; selectedCells.clear(); } if (selection) { auto found = false; for (auto cell : selectedCells) { if (cell.x == currentCell.x && cell.y == currentCell.y) { found = true; break; } } if (!found) { selectedCells.push_back(sf::Vector2i(currentCell.x, currentCell.y)); } } }
IPC::IPC() : globalMemory{"qtox-" IPC_PROTOCOL_VERSION} { qRegisterMetaType<IPCEventHandler>("IPCEventHandler"); timer.setInterval(EVENT_TIMER_MS); timer.setSingleShot(true); connect(&timer, &QTimer::timeout, this, &IPC::processEvents); // The first started instance gets to manage the shared memory by taking ownership // Every time it processes events it updates the global shared timestamp "lastProcessed" // If the timestamp isn't updated, that's a timeout and someone else can take ownership // This is a safety measure, in case one of the clients crashes // If the owner exits normally, it can set the timestamp to 0 first to immediately give ownership std::default_random_engine randEngine((std::random_device())()); std::uniform_int_distribution<uint64_t> distribution; globalId = distribution(randEngine); qDebug() << "Our global IPC ID is " << globalId; if (globalMemory.create(sizeof(IPCMemory))) { if (globalMemory.lock()) { IPCMemory* mem = global(); memset(mem, 0, sizeof(IPCMemory)); mem->globalId = globalId; mem->lastProcessed = time(0); globalMemory.unlock(); } else { qWarning() << "Couldn't lock to take ownership"; } } else if (globalMemory.attach()) { qDebug() << "Attaching to the global shared memory"; } else { qDebug() << "Failed to attach to the global shared memory, giving up"; return; // We won't be able to do any IPC without being attached, let's get outta here } processEvents(); }
double * spline_transform(short *dcts, int bits, int *pnpoints) { static double output[HOWMANY*4]; double *p; int i; p = output; for (i = 0; i < HOWMANY; i++) { distribution(i, dcts, bits, p); p += 4; } *pnpoints = HOWMANY*4; return (output); }
void randomTest(dbi::LockManager* lm, int thread) { std::default_random_engine generator; std::uniform_int_distribution<int> distribution(1,100); auto rnd = std::bind(distribution, generator); for (uint64_t i=1; i <= 10000; i++) { try { lm->lock(dbi::TupleId(rnd()), thread); } catch (dbi::AlreadyLockedException e) { } catch (dbi::DeadlockException e) { lm->unlockAll(thread); } if (i%10 == 0) lm->unlockAll(thread); } lm->unlockAll(thread); }
// return it, even rbm mk_rbm(unsigned int nv, unsigned int nh) { // get the randomly initialized weights size_t elements = get_number_of_weights(nv, nh); std::vector<double> weights(elements); //std::uniform_real_distribution<double> distribution(-1.0f, 1.0f); //Values between -1 and 1 std::normal_distribution<double> distribution(0.0, 1.0); std::random_device rd; //seed std::mt19937 engine(rd()); auto generator = std::bind(distribution, engine); std::generate_n(weights.begin(), elements, generator); std::vector<int> visible = std::vector<int>(nv, 0); std::vector<int> hidden = std::vector<int>(nh, 0); rbm res = { nv, nh, visible, hidden, weights }; return res; }
std::vector<person> generate(const unsigned & n) { std::vector<person> people; unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator(seed); std::uniform_real_distribution<double> distribution(0.0, 1.0); auto rand = std::bind(distribution, generator); for (int i = 0; i < n; ++i) { person p(i); for (int j = 0; j < n; ++j) { p.set_preference(j, rand()); } people.push_back(p); } return people; }
void *create_randomness(uint64_t n, std::vector<T> &rand) { // Prepare n bits of randomness using a pseudo-random number generator. // A vector instead of a raw array is used to store the data because // this way, it's easier for the caller to keep track of the allocation. std::uniform_int_distribution<T> distribution(0, std::numeric_limits<T>::max()); std::mt19937 mt_engine(42); auto generator = std::bind(distribution, mt_engine); uint64_t num_chunks = n/sizeof(rand[0])+1; rand.reserve(num_chunks); for (auto i = 0; i < num_chunks; i++) { rand[i] = generator(); } return (&rand[0]); }
fcppt::random::uniform<T, Generator>::uniform( range_type const &_range ) : variate_( typename boost::remove_reference<Generator>::type( static_cast< typename boost::remove_reference<Generator>::type::result_type >( fcppt::chrono::high_resolution_clock::now().time_since_epoch().count() ) ), distribution( _range.first(), _range.last() ) ) {}
void RandomProbabilities::assign_random_value(RandomNumberEngine& rne) { /// @todo Creating the variate every time from scratch is slow. typedef uniform_real<float> Distribution; Distribution distribution(0.0f, 1.0f); variate_generator<RandomNumberEngine&, Distribution> variate(rne, distribution); float sum = 0.0; for (iterator i = pt_.begin(); i != pt_.end(); ++i) { i->second = variate(); sum += i->second; } for (iterator i = pt_.begin(); i != pt_.end(); ++i) i->second /= sum; }
void Terrain::GenerateTerrain() { std::default_random_engine rand; std::uniform_int_distribution<int> distribution(1, 2); tiles.reserve(WIDTH*HEIGHT); // see http://libnoise.sourceforge.net/docs/index.html noise::module::Perlin perlinHigh; noise::module::Perlin perlinLow; noise::module::Perlin perlinControl; noise::module::Blend blend; // This isnt really doing much but could be extended to create better terrain // with biomes etc blend.SetSourceModule(0, perlinHigh); blend.SetSourceModule(1, perlinLow); blend.SetControlModule(perlinControl); perlinHigh.SetFrequency(0.5); perlinHigh.SetOctaveCount(2); perlinLow.SetFrequency(2); perlinLow.SetOctaveCount(2); for (int i = 0; i < WIDTH; ++i) { int h = GenHeight(i, blend); //printf("h: %d \n", h); for (int j = 0; j < h; ++j) { //tiles.push_back(distribution(rand)); tiles.push_back(1); } for (int j = h; j < HEIGHT; ++j) { tiles.push_back(0); } } }
Point SpaceParam::get_rnd() { Point p; for (size_t i = 0; i < names.size(); ++i) { Number n = space.at(i).max() - space.at(i).min(); Number del = (space.at(i).max().delta() < space.at(i).min().delta()) ? space.at(i).max().delta(): space.at(i).min().delta(); double number = distribution(generator); Number nn(number * (n / del).to_float()); n = space.at(i).min() + nn * del; p.add(n); } return p; }
void AnalyzeImage(cv::Mat input, AnalyzeResult& value) { value = AnalyzeResult(); DominantColorsExtractor colorsExtractor; colorsExtractor.process(input); value.frameSize = input.size(); value.aspectRatio = ComputeImageAspectRatio(input.size()); value.intensity = distribution(input); value.rmsContrast = ComputeRmsContrast(input); value.dominantColors = colorsExtractor.mainColors; value.uniqieColors = colorsExtractor.getUniqueColors(); value.reducedColors = colorsExtractor.getRedicedColors(); value.colorDeviation = colorsExtractor.getColorDeviation(); }
int main(int argc, char* argv[]) { size_t numberOfPeople = std::stoi(argv[1]); size_t numberOfSamples = std::stoi(argv[2]); std::atomic<size_t> countPointingPairs(0); std::uniform_int_distribution<int> distribution(0, numberOfPeople - 1); std::mt19937 engine; auto rand = std::bind(distribution,engine); tbb::task_group tg; for ( size_t i=0; i<numberOfSamples; ++i ) { tg.run([&]{ std::vector<Person> people(numberOfPeople); for ( auto& person : people ) { auto targetPerson = &people[rand()]; while( targetPerson == &person ) { targetPerson = &people[rand()]; } person.pointsTo = targetPerson; } for ( auto& person : people ) { if ( person.pointsTo->pointsTo == &person ) { ++countPointingPairs; break; } } });}; tg.wait(); std::cout << (double)countPointingPairs / (double)numberOfSamples << std::endl; return 0; }
void EncodingTest::test() { std::default_random_engine engine; std::uniform_int_distribution<uint8_t> distribution(0, 255); // Test all three cases of padding. const size_t sizes[6] = { 1, 2, 3, 1023, 1024, 1025 }; for (uint_fast8_t s = 0; s < 6; ++s) { std::vector<uint8_t> original(sizes[s]); for (uint_fast8_t run = 0; run < 10; ++run) { std::generate(original.begin(), original.end(), std::bind(distribution, engine)); const std::string encoded = Util::encodeBase64(original); const std::vector<uint8_t> decoded = Util::decodeBase64(encoded); CPPUNIT_ASSERT(decoded == original); } } }