| Ben.Dougall |
Jul 5th, 2007 7:03 PM |
Templated Random Number Generator
Hi guys, new to the forum, plan to contribute here a lot as i get bored at work. Quick question on a Random Generator.
I'm making a library for common tasks in C++ ( random, XML Reader, HTML Document maker, etc ) and I am just wondering the best way to go about this is. Right now, even though it is templated, doubles and floats are never real numbers, always whole numbers.
:
/** @brief Seeds the Random Number generator @param seed The value to seed the generator with. @note The generator is only seeded once, no matter how many times you call the method */ void SeedGenerator( int seed = static_cast<int>( time(0) ) ) { static bool seeded = false; if ( !seeded ) { srand( seed ); rand(); seeded = true; } } /** @brief Generates Random Number @param low The lowest possible number @param high The highest possible number @return The random number between the range. */ template <typename T> inline T RandomNumber( const T &low, const T &high ) { return static_cast<T>(low + rand() % high ); }
I have been using this formula for 4 years during Java development, and works fine for whole number generation. I was just wondering what the best, and most efficent method of doing this would be.
|