• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ std::mt19937类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中std::mt19937的典型用法代码示例。如果您正苦于以下问题:C++ mt19937类的具体用法?C++ mt19937怎么用?C++ mt19937使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了mt19937类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: printf

void SeedFeatureFactory::train( const std::vector< std::shared_ptr<ImageOverSegmentation> > &ios, const std::vector<VectorXs> & lbl ) {
	printf("  * Training SeedFeature\n");
	static std::mt19937 rand;
	const int N_SAMPLES = 5000;
	int n_pos=0, n_neg=0;
	for( VectorXs l: lbl ) {
		n_pos += (l.array()>=0).cast<int>().sum();
		n_neg += (l.array()==-1).cast<int>().sum();
	}
	
	// Collect training examples
	float sampling_freq[] = {0.5f*N_SAMPLES / n_neg, 0.5f*N_SAMPLES / n_pos};
	std::vector<RowVectorXf> f;
	std::vector<float> l;
#pragma omp parallel for
	for( int i=0; i<ios.size(); i++ ) {
		RMatrixXf ftr = SeedFeature::computeObjFeatures( *ios[i] );
		for( int j=0; j<ios[i]->Ns(); j++ )
			if( lbl[i][j] >= -1 && rand() < rand.max()*sampling_freq[ lbl[i][j]>=0 ] ) {
#pragma omp critical
				{
					l.push_back( lbl[i][j]>=0 );
					f.push_back( ftr.row(j) );
				}
			}
	}
	
	printf("    - Computing parameters\n");
	// Fit the ranking functions
	RMatrixXf A( f.size(), f[0].size() );
	VectorXf b( l.size() );
	for( int i=0; i<f.size(); i++ ) {
		A.row(i) = f[i];
		b[i] = l[i];
	}
	
	// Solve A*x = b
	param_ = A.colPivHouseholderQr().solve(b);
	printf("    - done %f\n",(A*param_-b).array().abs().mean());
}
开发者ID:ClarkWang12,项目名称:object-proposals,代码行数:40,代码来源:seedfeature.cpp


示例2: if

		namespace random {

			static std::mt19937 __random_generator;
			static bool __random_initialized = false;
			static std::recursive_mutex __random_lock;

			void 
			initialize(
				uint32_t seed
				)
			{
				TRACE_MESSAGE(TRACE_LEVEL_VERBOSE, "+sola::component::random::initialize");

				SERIALIZE_CALL(std::recursive_mutex, __random_lock);

				std::srand((uint32_t) std::time(NULL));

				if(seed == GENERATE_RANDOM_SEED) {
					__random_generator.seed(rand());
				} else {
					__random_generator.seed(seed);
				}
				__random_initialized = true;

				TRACE_MESSAGE(TRACE_LEVEL_VERBOSE, "-sola::component::random::initialize");
			}

			double 
			generate_normalized(
				double mean,
				double sigma,
				double crop_min,
				double crop_max
				)
			{
				TRACE_MESSAGE(TRACE_LEVEL_VERBOSE, "+sola::component::random::generate_normalized");

				SERIALIZE_CALL(std::recursive_mutex, __random_lock);

				double result;
				std::normal_distribution<double> normal_dist(mean, sigma);

				if(!__random_initialized) {
					THROW_RANDOM_EXCEPTION(RANDOM_EXCEPTION_UNINITIALIZED);
				}

				if(sigma < 0.0) {
					THROW_RANDOM_EXCEPTION_MESSAGE(
						RANDOM_EXCEPTION_INVALID_PARAMETER,
						"spread < 0.0"
						);
				}

				if(crop_min > crop_max) {
					THROW_RANDOM_EXCEPTION_MESSAGE(
						RANDOM_EXCEPTION_INVALID_PARAMETER,
						"crop_min > crop_max"
						);
				}
				result = normal_dist(__random_generator);

				if(result < crop_min) {
					result = crop_min;
				} else if(result > crop_max) {
					result = crop_max;
				}

				TRACE_MESSAGE(TRACE_LEVEL_VERBOSE, "-sola::component::random::generate_normalized, result. " << result);

				return result;
			}

			double 
			generate_uniform(
				double min,
				double max
				)
			{
				TRACE_MESSAGE(TRACE_LEVEL_VERBOSE, "+sola::component::random::generate_uniform");

				SERIALIZE_CALL(std::recursive_mutex, __random_lock);

				double result;
				std::uniform_real_distribution<double> uniform_dist;

				if(!__random_initialized) {
					THROW_RANDOM_EXCEPTION(RANDOM_EXCEPTION_UNINITIALIZED);
				}

				if(min > max) {
					THROW_RANDOM_EXCEPTION_MESSAGE(
						RANDOM_EXCEPTION_INVALID_PARAMETER,
						"min > max"
						);
				}
				result = ((max - min) * uniform_dist(__random_generator)) + min;

				TRACE_MESSAGE(TRACE_LEVEL_VERBOSE, "-sola::component::random::generate_uniform, result. " << result);

				return result;
//.........这里部分代码省略.........
开发者ID:AlekNS,项目名称:skironscrapper,代码行数:101,代码来源:random.cpp


示例3: init

namespace rng
{
	std::mt19937 r;

	void init() {
		r.seed((unsigned)std::chrono::system_clock::now().time_since_epoch().count());
	}
	
	int d6(std::mt19937& urng) {
		return d6Gen(urng);
	}
	
	int degrees(std::mt19937& urng) {
		return degreesGen(urng);
	}
	
	double radians(std::mt19937& urng) {
		return radiansGen(urng);
	}
	
	bool boolean(std::mt19937& urng) {
		return booleanGen(urng);
	}

	int getInt(int lo, int hi, std::mt19937& urng) {
		return std::uniform_int_distribution<int>(lo, hi)(urng);
	}

	int getInt(int hi, std::mt19937& urng) {
		return std::uniform_int_distribution<int>(0, hi)(urng);
	}

	bool oneInX(double x, std::mt19937& urng) {
		return std::bernoulli_distribution(1.0 / x)(urng);
	}

	bool xInY(double x, double y, std::mt19937& urng) {
		return std::bernoulli_distribution(x / y)(urng);
	}
}
开发者ID:Gatleos,项目名称:hexmap,代码行数:40,代码来源:rng.cpp


示例4: RandomSeed

namespace math /** Miscellaneous math routines. */ {

// Global random object.
extern std::mt19937 randGen;
// Global uniform distribution.
extern std::uniform_real_distribution<> randUniformDist;
// Global normal distribution.
extern std::normal_distribution<> randNormalDist;

/**
 * Set the random seed used by the random functions (Random() and RandInt()).
 * The seed is casted to a 32-bit integer before being given to the random
 * number generator, but a size_t is taken as a parameter for API consistency.
 *
 * @param seed Seed for the random number generator.
 */
inline void RandomSeed(const size_t seed)
{
  randGen.seed((uint32_t) seed);
  srand((unsigned int) seed);
#if ARMA_VERSION_MAJOR > 3 || \
    (ARMA_VERSION_MAJOR == 3 && ARMA_VERSION_MINOR >= 930)
  // Armadillo >= 3.930 has its own random number generator internally that we
  // need to set the seed for also.
  arma::arma_rng::set_seed(seed);
#endif
}

/**
 * Generates a uniform random number between 0 and 1.
 */
inline double Random()
{
  return randUniformDist(randGen);
}

/**
 * Generates a uniform random number in the specified range.
 */
inline double Random(const double lo, const double hi)
{
  return lo + (hi - lo) * randUniformDist(randGen);
}

/**
 * Generates a uniform random integer.
 */
inline int RandInt(const int hiExclusive)
{
  return (int) std::floor((double) hiExclusive * randUniformDist(randGen));
}

/**
 * Generates a uniform random integer.
 */
inline int RandInt(const int lo, const int hiExclusive)
{
  return lo + (int) std::floor((double) (hiExclusive - lo)
                               * randUniformDist(randGen));
}

/**
 * Generates a normally distributed random number with mean 0 and variance 1.
 */
inline double RandNormal()
{
  return randNormalDist(randGen);
}

/**
 * Generates a normally distributed random number with specified mean and
 * variance.
 *
 * @param mean Mean of distribution.
 * @param variance Variance of distribution.
 */
inline double RandNormal(const double mean, const double variance)
{
  return variance * randNormalDist(randGen) + mean;
}

} // namespace math
开发者ID:Andrew-He,项目名称:mlpack,代码行数:82,代码来源:random.hpp


示例5: initializeOGDF

namespace ogdf {

#ifdef OGDF_DEBUG
bool debugMode = true;
#else
bool debugMode = false;
#endif

Initialization::Initialization()
{
	initializeOGDF();
}

Initialization::~Initialization()
{
	deinitializeOGDF();
}

inline bool charCompareIgnoreCase(char a, char b)
{
	return toupper(a) == toupper(b);
}

void removeTrailingWhitespace(std::string &str)
{
	std::size_t found = str.find_last_not_of(" \t\v\f\n\r");
	if (found != std::string::npos) {
		str.erase(found+1);
	} else { // string consists only of whitespacae
		str.clear();
	}
}

bool equalIgnoreCase(const string &str1, const string &str2)
{
	return str1.size() == str2.size()
	    && std::equal(str1.begin(), str1.end(), str2.begin(), charCompareIgnoreCase);
}

bool prefixIgnoreCase(const string &prefix, const string &str)
{
	string::size_type len = prefix.length();
	return str.size() >= len
	    && std::equal(prefix.begin(), prefix.end(), str.begin(), charCompareIgnoreCase);
}

static std::mt19937 s_random;

#ifndef OGDF_MEMORY_POOL_NTS
static std::mutex s_randomMutex;
#endif

long unsigned int randomSeed()
{
#ifndef OGDF_MEMORY_POOL_NTS
	std::lock_guard<std::mutex> guard(s_randomMutex);
#endif
	return 7*s_random()+3;  // do not directly return seed, add a bit of variation
}

void setSeed(int val)
{
	s_random.seed(val);
}

int randomNumber(int low, int high)
{
	OGDF_ASSERT(low <= high);

	std::uniform_int_distribution<> dist(low,high);

#ifndef OGDF_MEMORY_POOL_NTS
	std::lock_guard<std::mutex> guard(s_randomMutex);
#endif
	return dist(s_random);
}

double randomDouble(double low, double high)
{
	OGDF_ASSERT(low <= high);

	std::uniform_real_distribution<> dist(low,high);

#ifndef OGDF_MEMORY_POOL_NTS
	std::lock_guard<std::mutex> guard(s_randomMutex);
#endif
	return dist(s_random);
}

double usedTime(double& T)
{
	double t = T;

#ifdef OGDF_SYSTEM_WINDOWS
	FILETIME creationTime;
	FILETIME exitTime;
	FILETIME kernelTime;
	FILETIME userTime;

	GetProcessTimes(GetCurrentProcess(), &creationTime, &exitTime, &kernelTime, &userTime);
//.........这里部分代码省略.........
开发者ID:ogdf,项目名称:ogdf,代码行数:101,代码来源:basic.cpp


示例6: GameMain

int GameMain()
{
	s_rng.seed(1729);

	TestConstructors();
	TestMagnAndNorm();
	TestMembers();
	TestNonMembers();
	TestOperators();

	Sleep(1000);
	return 0;
}
开发者ID:Innabus,项目名称:Innabus,代码行数:13,代码来源:Vec3_Basic.cpp


示例7: init

void init(dynamo::Simulation& Sim, const double density)
{
  RNG.seed(std::random_device()());
  Sim.ranGenerator.seed(std::random_device()());

  const double elasticity = 1.0;
  const size_t cells = 7;
  const double wallkT = 1.0;

  std::unique_ptr<dynamo::UCell> packptr(new dynamo::CUFCC(std::array<long, 3>{{cells, cells, cells}}, dynamo::Vector(1,1,1), new dynamo::UParticle()));
  packptr->initialise();
  std::vector<dynamo::Vector> latticeSites(packptr->placeObjects(dynamo::Vector(0,0,0)));
  const size_t N = latticeSites.size();
  const double boxL = std::cbrt(N / density);
  Sim.primaryCellSize = dynamo::Vector(boxL, boxL, boxL);

  dynamo::shared_ptr<dynamo::ParticleProperty> D(new dynamo::ParticleProperty(N, dynamo::Property::Units::Length(), "D", 1.0));
  dynamo::shared_ptr<dynamo::ParticleProperty> M(new dynamo::ParticleProperty(N, dynamo::Property::Units::Mass(), "M", 1.0));
  Sim._properties.push(D);
  Sim._properties.push(M);

  Sim.dynamics = dynamo::shared_ptr<dynamo::Dynamics>(new dynamo::DynGravity(&Sim, dynamo::Vector(0, -1, 0)));
  Sim.BCs = dynamo::shared_ptr<dynamo::BoundaryCondition>(new dynamo::BCNone(&Sim));
  Sim.ptrScheduler = dynamo::shared_ptr<dynamo::SNeighbourList>(new dynamo::SNeighbourList(&Sim, new dynamo::FELBoundedPQ<dynamo::PELMinMax<3> >()));

  Sim.interactions.push_back(dynamo::shared_ptr<dynamo::Interaction>(new dynamo::IHardSphere(&Sim, "D", elasticity, new dynamo::IDPairRangeAll(), "Bulk")));
  Sim.addSpecies(dynamo::shared_ptr<dynamo::Species>(new dynamo::SpPoint(&Sim, new dynamo::IDRangeAll(&Sim), "M", "Bulk", 0)));

  Sim.locals.push_back(dynamo::shared_ptr<dynamo::Local>(new dynamo::LWall(&Sim, elasticity, "D", dynamo::Vector(1, 0, 0), dynamo::Vector(-0.5 * Sim.primaryCellSize[0] - 1, 0, 0), "XwallLow", new dynamo::IDRangeAll(&Sim))));
  Sim.locals.push_back(dynamo::shared_ptr<dynamo::Local>(new dynamo::LWall(&Sim, elasticity, "D", dynamo::Vector(-1, 0, 0), dynamo::Vector(0.5 * Sim.primaryCellSize[0] + 1, 0, 0), "XwallHigh", new dynamo::IDRangeAll(&Sim))));

  Sim.locals.push_back(dynamo::shared_ptr<dynamo::Local>(new dynamo::LWall(&Sim, elasticity, "D", dynamo::Vector(0, 0, 1), dynamo::Vector(0, 0, -0.5 * Sim.primaryCellSize[2] - 1), "ZwallLow", new dynamo::IDRangeAll(&Sim))));
  Sim.locals.push_back(dynamo::shared_ptr<dynamo::Local>(new dynamo::LWall(&Sim, elasticity, "D", dynamo::Vector(0, 0, -1), dynamo::Vector(0, 0, 0.5 * Sim.primaryCellSize[2] + 1), "ZwallHigh", new dynamo::IDRangeAll(&Sim))));

  Sim.locals.push_back(dynamo::shared_ptr<dynamo::Local>(new dynamo::LWall(&Sim, elasticity, "D", dynamo::Vector(0, 1, 0), dynamo::Vector(0, - 0.5 * Sim.primaryCellSize[1] - 1, 0), "GroundPlate", new dynamo::IDRangeAll(&Sim), wallkT)));
  
  for (size_t i(0); i < latticeSites.size(); ++i)
    {
      Sim.particles.push_back(dynamo::Particle(boxL * latticeSites[i], getRandVelVec(), Sim.particles.size()));
      D->getProperty(i) = (i < 100) ? 1 : 0.5;
      M->getProperty(i) = (i < 100) ? 1 : 0.5 * 0.5 * 0.5;
    }

  Sim.ensemble = dynamo::Ensemble::loadEnsemble(Sim);

  dynamo::InputPlugin(&Sim, "Rescaler").zeroMomentum();
  dynamo::InputPlugin(&Sim, "Rescaler").rescaleVels(1.0);

  BOOST_CHECK_EQUAL(Sim.N(), 1372);
  BOOST_CHECK_CLOSE(Sim.getNumberDensity() * Sim.units.unitVolume(), density, 0.000000001);
}
开发者ID:luyao1986,项目名称:DynamO,代码行数:51,代码来源:thermalisedwalls_test.cpp


示例8: init

void init(dynamo::Simulation& Sim, const double density)
{
  RNG.seed(std::random_device()());
  Sim.ranGenerator.seed(std::random_device()());

  Sim.dynamics = dynamo::shared_ptr<dynamo::Dynamics>(new dynamo::DynNewtonian(&Sim));
  Sim.BCs = dynamo::shared_ptr<dynamo::BoundaryCondition>(new dynamo::BCPeriodic(&Sim));
  Sim.ptrScheduler = dynamo::shared_ptr<dynamo::SNeighbourList>(new dynamo::SNeighbourList(&Sim, new DefaultSorter()));

  std::unique_ptr<dynamo::UCell> packptr(new dynamo::CUSC(std::array<long, 3>{{128, 128, 1}}, dynamo::Vector{1,1,1}, new dynamo::UParticle()));
  packptr->initialise();
  std::vector<dynamo::Vector> latticeSites(packptr->placeObjects(dynamo::Vector{0,0,0}));
  
  //As we're in 2D we need to take the square root
  double particleDiam = std::sqrt(density / latticeSites.size());
  Sim.units.setUnitLength(particleDiam);
  Sim.units.setUnitTime(particleDiam); 

  Sim.primaryCellSize = dynamo::Vector{1, 1, 4 * particleDiam};
  
  typedef std::pair<double,double> Step;
  std::vector<Step> steps;
  steps.push_back(Step{1.0,0.1});
  steps.push_back(Step{0.9,0.2});
  steps.push_back(Step{0.8,0.3});
  steps.push_back(Step{0.7,0.4});
  steps.push_back(Step{0.6,0.5});
  steps.push_back(Step{0.5,0.6});
  steps.push_back(Step{0.4,0.7});
  steps.push_back(Step{0.3,0.8});
  steps.push_back(Step{0.2,0.9});
  steps.push_back(Step{0.1,1.0});
  Sim.interactions.push_back(dynamo::shared_ptr<dynamo::Interaction>(new dynamo::IStepped(&Sim, dynamo::shared_ptr<dynamo::Potential>(new dynamo::PotentialStepped(steps, false)), new dynamo::IDPairRangeAll(), "Bulk", particleDiam, 1.0)));
    
  Sim.addSpecies(dynamo::shared_ptr<dynamo::Species>(new dynamo::SpPoint(&Sim, new dynamo::IDRangeAll(&Sim), 1.0, "Bulk", 0)));

  unsigned long nParticles = 0;
  Sim.particles.reserve(latticeSites.size());
  for (const dynamo::Vector & position : latticeSites)
    Sim.particles.push_back(dynamo::Particle(position, getRandVelVec() * Sim.units.unitVelocity(), nParticles++));

  for (auto& particle : Sim.particles)
    particle.getVelocity()[2] = 0;

  dynamo::InputPlugin(&Sim, "Rescaler").zeroMomentum();
  dynamo::InputPlugin(&Sim, "Rescaler").rescaleVels(2.0 / 3.0);
    
  Sim.ensemble = dynamo::Ensemble::loadEnsemble(Sim);

  BOOST_CHECK_EQUAL(Sim.N(), 128 * 128);
}
开发者ID:g-rutter,项目名称:DynamO,代码行数:51,代码来源:2dstepped_potential_test.cpp


示例9: init

void init(dynamo::Simulation& Sim, const double density)
{
  RNG.seed(std::random_device()());
  Sim.ranGenerator.seed(std::random_device()());

  double massFrac = 0.001, sizeRatio = 0.5;
  size_t Na=100;
  
  Sim.dynamics = dynamo::shared_ptr<dynamo::Dynamics>(new dynamo::DynNewtonian(&Sim));
  Sim.BCs = dynamo::shared_ptr<dynamo::BoundaryCondition>(new dynamo::BCPeriodic(&Sim));
  Sim.ptrScheduler = dynamo::shared_ptr<dynamo::SNeighbourList>(new dynamo::SNeighbourList(&Sim, new DefaultSorter()));

  std::unique_ptr<dynamo::UCell> packptr(new dynamo::CUFCC(std::array<long, 3>{{10, 10, 10}}, dynamo::Vector(1, 1, 1), new dynamo::UParticle()));
  packptr->initialise();
  std::vector<dynamo::Vector> latticeSites(packptr->placeObjects(dynamo::Vector(0,0,0)));
  Sim.primaryCellSize = dynamo::Vector(1,1,1);

  double simVol = 1.0;
  for (size_t iDim = 0; iDim < NDIM; ++iDim)
    simVol *= Sim.primaryCellSize[iDim];

  double particleDiam = std::cbrt(simVol * density / latticeSites.size());
  
  Sim.interactions.push_back(dynamo::shared_ptr<dynamo::Interaction>(new dynamo::IHardSphere(&Sim, particleDiam, new dynamo::IDPairRangeSingle(new dynamo::IDRangeRange(0, Na - 1)), "AAInt")));
  
  Sim.interactions.push_back(dynamo::shared_ptr<dynamo::Interaction>(new dynamo::IHardSphere(&Sim, ((1.0 + sizeRatio) / 2.0) * particleDiam, new dynamo::IDPairRangePair(new dynamo::IDRangeRange(0, Na - 1), new dynamo::IDRangeRange(Na, latticeSites.size() - 1)), "ABInt")));

  Sim.interactions.push_back(dynamo::shared_ptr<dynamo::Interaction>(new dynamo::IHardSphere(&Sim, sizeRatio * particleDiam, new dynamo::IDPairRangeAll(), "BBInt")));

  Sim.addSpecies(dynamo::shared_ptr<dynamo::Species>(new dynamo::SpPoint(&Sim, new dynamo::IDRangeRange(0, Na - 1), 1.0, "A", 0)));

  Sim.addSpecies(dynamo::shared_ptr<dynamo::Species>(new dynamo::SpPoint(&Sim, new dynamo::IDRangeRange(Na, latticeSites.size() - 1), massFrac, "B", 0)));

  Sim.units.setUnitLength(particleDiam);

  unsigned long nParticles = 0;
  Sim.particles.reserve(latticeSites.size());

  for (const dynamo::Vector & position : latticeSites)
    Sim.particles.push_back(dynamo::Particle(position, getRandVelVec() * Sim.units.unitVelocity(), nParticles++));

  Sim.ensemble = dynamo::Ensemble::loadEnsemble(Sim);

  dynamo::InputPlugin(&Sim, "Rescaler").zeroMomentum();
  dynamo::InputPlugin(&Sim, "Rescaler").rescaleVels(1.0);

  BOOST_CHECK_EQUAL(Sim.N(), 4000);
  //BOOST_CHECK_CLOSE(Sim.getNumberDensity() * Sim.units.unitVolume(), density, 0.000000001);
  //BOOST_CHECK_CLOSE(Sim.getPackingFraction(), Sim.getNumberDensity() * Sim.units.unitVolume() * M_PI / 6.0, 0.000000001);
}
开发者ID:BigMacchia,项目名称:DynamO,代码行数:50,代码来源:binaryhardsphere_test.cpp


示例10: main

int main(int argc, char** argv) {
  rng.seed();
  CALL(TEST_HashFunctions);
  CALL(overview::TEST_Construction);
  CALL(overview::TEST_Retreival);
  CALL(overview::TEST_Resizing);
  CALL(separate_chaining::TEST_Construction);
  CALL(separate_chaining::TEST_Retreival);
  CALL(open_addressing::TEST_Construction);
  CALL(open_addressing::TEST_Retreival);
  CALL(cuckoo::TEST_CuckooHashing);
  CALL(TEST_MostCommon);
  CALL(TEST_Cache);
  return 0;
}
开发者ID:ProgrammingProblems,项目名称:Volume1,代码行数:15,代码来源:main.cpp


示例11: hpx_main

// -------------------------------------------------------------------------
int hpx_main(boost::program_options::variables_map& vm)
{
    std::size_t device     = vm["device"].as<std::size_t>();
    std::size_t sizeMult   = vm["sizemult"].as<std::size_t>();
    std::size_t iterations = vm["iterations"].as<std::size_t>();
    //
    unsigned int seed = std::random_device{}();
     if (vm.count("seed"))
        seed = vm["seed"].as<unsigned int>();

    gen.seed(seed);
    std::cout << "using seed: " << seed << std::endl;

    //
    sizeMult = (std::min)(sizeMult, std::size_t(100));
    sizeMult = (std::max)(sizeMult, std::size_t(1));
    //
    // use a larger block size for Fermi and above, query default cuda target properties
    hpx::compute::cuda::target target(device);

    std::cout
        << "GPU Device " << target.native_handle().get_device()
        << ": \"" << target.native_handle().processor_name() << "\" "
        << "with compute capability " << target.native_handle().processor_family()
        << "\n";

    int block_size = (target.native_handle().processor_family() < 2) ? 16 : 32;

    sMatrixSize matrix_size;
    matrix_size.uiWA = 2 * block_size * sizeMult;
    matrix_size.uiHA = 4 * block_size * sizeMult;
    matrix_size.uiWB = 2 * block_size * sizeMult;
    matrix_size.uiHB = 4 * block_size * sizeMult;
    matrix_size.uiWC = 2 * block_size * sizeMult;
    matrix_size.uiHC = 4 * block_size * sizeMult;

    printf("MatrixA(%u,%u), MatrixB(%u,%u), MatrixC(%u,%u)\n\n",
           matrix_size.uiWA, matrix_size.uiHA,
           matrix_size.uiWB, matrix_size.uiHB,
           matrix_size.uiWC, matrix_size.uiHC);

    matrixMultiply<float>(matrix_size, device, iterations);
    return hpx::finalize();
}
开发者ID:ShmuelLevine,项目名称:hpx,代码行数:45,代码来源:cublas_matmul.cpp


示例12: init

void init(dynamo::Simulation& Sim, double density = 0.5)
{
  RNG.seed(std::random_device()());
  Sim.ranGenerator.seed(std::random_device()());

  const double elasticity = 1.0;
  const double lambda = 1.5;
  const double welldepth = 1.0;

  Sim.dynamics = dynamo::shared_ptr<dynamo::Dynamics>(new dynamo::DynNewtonian(&Sim));
  Sim.BCs = dynamo::shared_ptr<dynamo::BoundaryCondition>(new dynamo::BCPeriodic(&Sim));
  Sim.ptrScheduler = dynamo::shared_ptr<dynamo::SNeighbourList>(new dynamo::SNeighbourList(&Sim, new DefaultSorter()));

  std::unique_ptr<dynamo::UCell> packptr(new dynamo::CUFCC(std::array<long, 3>{{7,7,7}}, dynamo::Vector(1,1,1), new dynamo::UParticle()));
  packptr->initialise();
  std::vector<dynamo::Vector> latticeSites(packptr->placeObjects(dynamo::Vector(0,0,0)));
  Sim.primaryCellSize = dynamo::Vector(1,1,1);

  double simVol = 1.0;
  for (size_t iDim = 0; iDim < NDIM; ++iDim)
    simVol *= Sim.primaryCellSize[iDim];

  double particleDiam = std::cbrt(simVol * density / latticeSites.size());

  Sim.interactions.push_back(dynamo::shared_ptr<dynamo::Interaction>(new dynamo::ISquareWell(&Sim, particleDiam, lambda, welldepth, elasticity, new dynamo::IDPairRangeAll(), "Bulk")));
  Sim.addSpecies(dynamo::shared_ptr<dynamo::Species>(new dynamo::SpPoint(&Sim, new dynamo::IDRangeAll(&Sim), 1.0, "Bulk", 0)));
  Sim.units.setUnitLength(particleDiam);
  Sim.units.setUnitTime(particleDiam); 

  unsigned long nParticles = 0;
  Sim.particles.reserve(latticeSites.size());
  for (const dynamo::Vector & position : latticeSites)
    Sim.particles.push_back(dynamo::Particle(position, getRandVelVec() * Sim.units.unitVelocity(), nParticles++));

  Sim.ensemble = dynamo::Ensemble::loadEnsemble(Sim);

  dynamo::InputPlugin(&Sim, "Rescaler").zeroMomentum();
  dynamo::InputPlugin(&Sim, "Rescaler").rescaleVels(1.0);

  BOOST_CHECK_EQUAL(Sim.N(), 1372);
  BOOST_CHECK_CLOSE(Sim.getNumberDensity() * Sim.units.unitVolume(), density, 0.000000001);
  BOOST_CHECK_CLOSE(Sim.getPackingFraction(), Sim.getNumberDensity() * Sim.units.unitVolume() * M_PI / 6.0, 0.000000001);
}
开发者ID:BigMacchia,项目名称:DynamO,代码行数:43,代码来源:squarewell_test.cpp


示例13:

Random::Random(UInt64 seed) {
  if (seed == 0) {
    if( !static_gen_seeded ) {
      #if NDEBUG
        unsigned int static_seed = (unsigned int)std::chrono::system_clock::now().time_since_epoch().count();
      #else
        unsigned int static_seed = DEBUG_RANDOM_SEED;
      #endif
      static_gen.seed( static_seed );
      static_gen_seeded = true;
      NTA_INFO << "Random seed: " << static_seed;
    }
    seed_ = static_gen(); //generate random value from HW RNG
  } else {
    seed_ = seed;
  }
  // if seed is zero at this point, there is a logic error.
  NTA_CHECK(seed_ != 0);
  gen.seed((unsigned int)seed_); //seed the generator
  steps_ = 0;
}
开发者ID:breznak,项目名称:nupic.core,代码行数:21,代码来源:Random.cpp


示例14: use_graph_generator

    void use_graph_generator(const vle::devs::InitEventList& events)
    {
        model_number = events.getInt("model-number");
        std::string generator_name = events.getString("graph-generator");

        if (events.exist("graph-seed"))
            generator.seed(events.getInt("graph-seed"));

        if (generator_name == "defined")
            use_defined_graph_generator(events);
        else if (generator_name == "small-world")
            use_smallworld_graph_generator(events);
        else if (generator_name == "scale-free")
            use_scalefree_graph_generator(events);
        else if (generator_name == "sorted-erdos-renyi")
            use_sortederdesrenyi_graph_generator(events);
        else if (generator_name == "erdos_renyi")
            use_erdosrenyi_graph_generator(events);
        else
            throw vle::utils::ModellingError("Unknown graph gererator: %s",
                                             generator_name.c_str());
    }
开发者ID:eric-casellas,项目名称:vle,代码行数:22,代码来源:Builder.cpp


示例15: init

void init(dynamo::Simulation& Sim, const double density)
{
  RNG.seed(std::random_device()());
  Sim.ranGenerator.seed(std::random_device()());

  const double elasticity = 1.0;
  const size_t N = 1000;
  Sim.dynamics = dynamo::shared_ptr<dynamo::Dynamics>(new dynamo::DynNewtonian(&Sim));
  Sim.BCs = dynamo::shared_ptr<dynamo::BoundaryCondition>(new dynamo::BCPeriodic(&Sim));
  Sim.ptrScheduler = dynamo::shared_ptr<dynamo::SNeighbourList>(new dynamo::SNeighbourList(&Sim, new DefaultSorter()));
  
  dynamo::CURandom packroutine(N, dynamo::Vector{1,1,1}, new dynamo::UParticle());
  packroutine.initialise();
  std::vector<dynamo::Vector> latticeSites(packroutine.placeObjects(dynamo::Vector{0,0,0}));
  Sim.BCs = dynamo::shared_ptr<dynamo::BoundaryCondition>(new dynamo::BCPeriodic(&Sim));
  double particleDiam = std::cbrt(density / N);
  Sim.interactions.push_back(dynamo::shared_ptr<dynamo::Interaction>(new dynamo::ILines(&Sim, particleDiam, elasticity, new dynamo::IDPairRangeAll(), "Bulk")));
  Sim.addSpecies(dynamo::shared_ptr<dynamo::Species>(new dynamo::SpSphericalTop(&Sim, new dynamo::IDRangeAll(&Sim), 1.0, "Bulk", 0, particleDiam * particleDiam / 12.0)));
  Sim.units.setUnitLength(particleDiam);

  unsigned long nParticles = 0;
  Sim.particles.reserve(latticeSites.size());
  for (const dynamo::Vector & position : latticeSites)
    Sim.particles.push_back(dynamo::Particle(position, getRandVelVec() * Sim.units.unitVelocity(), nParticles++));

  Sim.dynamics->initOrientations();

  Sim.ensemble = dynamo::Ensemble::loadEnsemble(Sim);

  dynamo::InputPlugin(&Sim, "Rescaler").zeroMomentum();
  dynamo::InputPlugin(&Sim, "Rescaler").rescaleVels(1.0);

  BOOST_CHECK_EQUAL(Sim.N(), N);
  BOOST_CHECK_CLOSE(Sim.getNumberDensity() * Sim.units.unitVolume(), density, 0.000000001);
  BOOST_CHECK_CLOSE(Sim.getPackingFraction(), 0, 0.000000001);
}
开发者ID:toastedcrumpets,项目名称:DynamO,代码行数:36,代码来源:lines_test.cpp


示例16: initODE

/*******************************************************************************
Function to initialize ODE.
*******************************************************************************/
void initODE()
{
	///////////////// Initializing the ODE general features ////////////////////

	dInitODE();								//Initialize library.
	World = dWorldCreate();					//Crate a new dynamics, empty world.
	Space = dSimpleSpaceCreate(0);			//Create a new space for collision (independent).
	ContactGroup = dJointGroupCreate(0);	//Create a joints container, without specifying size.

	dWorldSetGravity( World, 0.0, -9.81, 0 );	//Add gravity to this World.

	//Define error conrrection constants.
	dWorldSetERP( World, 0.2 );
	dWorldSetCFM( World, 1e-5 );

	//Set the velocity that interpenetrating objects will separate at.
	dWorldSetContactMaxCorrectingVel( World, 0.9 );

	//Set the safety area for contacts to be considered at rest.
	dWorldSetContactSurfaceLayer( World, 0.001 );

	//Automatically disable objects that have come to a rest.
	dWorldSetAutoDisableFlag( World, false );

	/////////////// Initializing the rigid bodies in the world /////////////////

	//Create a collision plane and add it to space. The next parameters are the
	//literal components of ax + by + cz = d.
	dCreatePlane( Space, 0.0, 1.0, 0.0, 0.0 );

	const dReal xPos = 0;
	const dReal yPos = 5;
	const dReal zPos = 0;
	const dReal xRot = 0;
	const dReal yRot = 0;
	const dReal zRot = 0;
	const dReal radius = .75;
	const dReal length = 4;
	const dReal sides[3] = { 2, 2, 2 };
	

	//Create body
	body.Body = dBodyCreate(World);
	dBodySetPosition(body.Body, xPos, yPos, zPos);
	dMatrix3 Orient3;
	//dRFromAxisAndAngle(Orient3, 0, 0, 1, 3.14/4);
	dRFromEulerAngles(Orient3, xRot, yRot, zRot);
	//dRFromEulerAngles(Orient3, 0, 0, 0);
	dBodySetRotation(body.Body, Orient3);
	dBodySetLinearVel(body.Body, 0, 0, 0);
	dBodySetData(body.Body, (void *)0);
	dMass bodyMass;
	dMassSetCapsule(&bodyMass, 1.0, 3, radius, length);
	//dMassSetBox(&bodyMass, 10, sides[0], sides[1], sides[2]);
	dBodySetMass(body.Body, &bodyMass);
	body.Geom = dCreateCapsule(Space, radius, length);
	//body.Geom = dCreateBox(Space, sides[0], sides[1], sides[2]);
	dGeomSetBody(body.Geom, body.Body);

	float head_pos[ 3 ] = { 0.0f, 5.0f, -1.0f };
	createInvisibleHead( head_pos );
	
	createFrontLegs();
	createMiddleLegs();
	createBackLegs();

	rng_engine.seed( std::chrono::duration_cast< std::chrono::microseconds >( std::chrono::system_clock::now().time_since_epoch() ).count() );

	const int foodPrize = 10;

	dReal position[3] = { 10.0f, 0.0f, -20.0f };
	addFoodParticle( position, foodPrize, &World, &Space );
}
开发者ID:bmarcott,项目名称:cs275,代码行数:76,代码来源:main.cpp


示例17: init_random_seed

void init_random_seed(int seed)
{
  generator.seed(seed);
}
开发者ID:Marcello-Sega,项目名称:espresso,代码行数:4,代码来源:random.cpp


示例18: main

int main(int argc, char * argv[])
{
	for(int i = 0; i <14; i++)
	{
		cout << " " << endl;
	}
	cout << "Welcome, my friend to the simplistic game of Trinity's Nightmare. Here, you have" << endl <<
		"reached a dungeon where you are alone, standing with only your car keys and a trash" << endl <<
		"can lid that you found. This is also where the level where the real danger begins." << endl <<
		"You have conquered the attic of man eating camels -- You have trudged through" << endl <<
		"the muddy swamps of Dr. Heinz'science experiment of alligator-dogs, only to" << endl <<
		"come face to face with the most recent obstacle of the fire-breathing" << endl <<
		"coffee-ingesting cookie-stealing SQUIRRELS!! Now, hold on to your" << endl <<
		"Mountain Dew and Pizza, buckle up into your basement chair, and" << endl << 
		"change your profile picture to that of a face of fear, because" << endl <<
		"here you go..." << endl;

	cout << "To Play: " << endl;
	cout << "Unless otherwise declaried, you will show up as @" << endl;
	cout << "1.) Movement:" << endl;
	cout << "     a - moves the player left" << endl;
	cout << "     s - moves the player down" << endl;
	cout << "     d - moves the player right" << endl;
	cout << "     w - moves the player up" << endl;
	cout << "     EXTRA: DIAGONAL:"<< endl;
	cout << "         e - up to the right" << endl;
	cout << "         x - down to the right" << endl;
	cout << "         z - down to the left" << endl;
	cout << "         ` - up to the right" << endl << endl;

	cout << "2.) Picking up and Using Items:" << endl;
	cout << "     p - pick up, and thus using" << endl;

	cout << "3.) Attack:" << endl;
	cout << "     - Creatures will attack you if you are within one space of them." << endl;
	cout << "     - Weapons and Experience increase your attacking." << endl << endl;

	cout << "q will allow you to Quit -- if you are a Quitter..." << endl << endl << endl;

	mt.seed(time(NULL));
	cout << "This is command line" << endl;
	cout << "Arguments Given : " << argc << endl;

//load file into variable
	string inFileName; 
	string outFileName;
	ifstream input;
        int inputValue = 0;
	if (argc >= 3)
	{
		inFileName = argv[1];
		outFileName = argv[2];

	}
	else
	{
		cout << "Enter a file name with .xml exstension: ";
		cin >> inFileName;
		cout << endl;
		cout << "What do you want to name the output file? " ;
		cin >> outFileName;
		cout << endl;
	}
	
	if (argc >= 4)
	{
        inputValue = atoi(argv[3]);
	}
    else
    {
        cout << "How many random Dungeons do you you want generated? " ;
        cin >> inputValue;
        cout << endl;
    }

	if(!input.good())
	{
		cout << "No file by that name. Try Again. " << endl;
		return 1;
	}

	input.open(inFileName.c_str());
//make vector using XMLSerializable pointer
	vector<XMLSerializable*> vWorld;
//send variables to parseXML
	parseXML(input, vWorld);
    //dumpOntoConsole(vWorld);

//make output file
	ofstream output;
   
    bool creatureOccupied;
    bool wallOccupied;

    int tempX = 0;
    int tempY = 0;

    int thingTempX = 0;
    int thingTempY = 0;

//.........这里部分代码省略.........
开发者ID:ShannonSimpson,项目名称:RougeLikeGame,代码行数:101,代码来源:main_cl.cpp


示例19: Init

void Window::Init(int width, int height, std::string title)
{
	// Intiate Random Number Generator	
	m_Random.seed(time(0));

	//initialize all SDL subsystems
	if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
		throw std::runtime_error("SDL Init Failed");
	//if (TTF_Init() == -1)
		//throw std::runtime_error("TTF Init Failed");

	// -- For Music --
	/* We're going to be requesting certain things from our audio
	device, so we set them up beforehand */
	int audio_rate = 22050;
	Uint16 audio_format = AUDIO_S16; /* 16-bit stereo */
	int audio_channels = 2;
	int audio_buffers = 4096;

	SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);

	/* This is where we open up our audio device.  Mix_OpenAudio takes
	as its parameters the audio format we'd /like/ to have. */
	if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers))
		throw std::runtime_error("Unable to open audio!\n");

	/* If we actually care about what we got, we can ask here.  In this
	program we don't, but I'm showing the function call here anyway
	in case we'd want to know later. */
	Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels);
	/* Every sound that gets played is assigned to a channel.  Note that
	this is different from the number of channels you request when you
	open the audio device; a channel in SDL_mixer holds information
	about a sound sample that is playing, while the number of channels
	you request when opening the device is dependant on what sort of
	sound you want (1 channel = mono, 2 = stereo, etc) */

	//-- For Sounds --
	/* Mix_Chunk is like Mix_Music, only it's for ordinary sounds. */

	//Setup our window size
	mBox.x = 0;
	mBox.y = 0;
	mBox.w = width;
	mBox.h = height;

	/* Create the windows and initialize the renderers */
	//Create our window
	mWindow.reset(SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED,
		SDL_WINDOWPOS_CENTERED, mBox.w, mBox.h, SDL_WINDOW_SHOWN));

	//Make sure it created ok
	if (mWindow == nullptr)
		throw std::runtime_error("Failed to create window");

	mRenderer.reset(SDL_CreateRenderer(mWindow.get(), -1,
		SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC));

	//Make sure it created ok
	if (mRenderer == nullptr)
		throw std::runtime_error("Failed to create renderer");

	Clear();
	SDL_SetRenderDrawBlendMode(mRenderer.get(), SDL_BLENDMODE_NONE);
	SDL_RenderFillRect(mRenderer.get(), NULL);
}
开发者ID:LanceJZ,项目名称:SDL2VectorAsteroids,代码行数:66,代码来源:Window.cpp


示例20: model

		Controller() :
			network(this), model(this), resources(), display(this)
      {
	_generator.seed(42);
      }
开发者ID:Daypi,项目名称:DaltoBabel,代码行数:5,代码来源:Controller.hpp



注:本文中的std::mt19937类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ std::multimap类代码示例发布时间:2022-05-31
下一篇:
C++ std::map类代码示例发布时间:2022-05-31
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap