View Single Post
Old Jul 5th, 2007, 7:03 PM   #1
Ben.Dougall
Programmer
 
Ben.Dougall's Avatar
 
Join Date: Jul 2007
Location: London, Ontario, Canada
Posts: 34
Rep Power: 0 Ben.Dougall is on a distinguished road
Send a message via MSN to Ben.Dougall
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.

cpp Syntax (Toggle Plain Text)
  1. /**
  2. @brief Seeds the Random Number generator
  3. @param seed The value to seed the generator with.
  4. @note The generator is only seeded once, no matter how many times you call the method */
  5. void SeedGenerator( int seed = static_cast<int>( time(0) ) )
  6. {
  7. static bool seeded = false;
  8. if ( !seeded )
  9. {
  10. srand( seed );
  11. rand();
  12. seeded = true;
  13. }
  14. }
  15.  
  16. /**
  17. @brief Generates Random Number
  18. @param low The lowest possible number
  19. @param high The highest possible number
  20. @return The random number between the range.
  21. */
  22. template <typename T>
  23. inline T RandomNumber( const T &low, const T &high )
  24. {
  25. return static_cast<T>(low + rand() % high );
  26. }

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.

Last edited by Ben.Dougall; Jul 5th, 2007 at 7:39 PM.
Ben.Dougall is offline   Reply With Quote