All,
Years ago I created a small function to return random numbers. The calling function would send a limit and the return would send a number between 0 and the limit. I used a time function to set the seed. It's worked pretty good over the years until now.
I have a test program for randomly locating pixels to the screen. The program writes random numbers to an array. It then uses the array to locate the pixels. The issue is the random number to the array loops so fast that the results are uniformed. I figure it's time to get away from the C time function and look for a newer one. I briefly read something about nanoseconds with a C++ call. Any recommendations? Is there a more current way of creating random numbers?
The issue is the random number to the array loops so fast that the results are uniformed.
You should call srand just once, not every time you want a new random number. srand resets the number sequence that rand produces. So if you end up with the same seed, you get the same output.
What torhu said! You could use a static bool in your function so you can keep calling it when needed but it only seeds the first time.
Thanks all, I'll give that a try. I figured there had to be a better approach.
After the advice, I was thinking along the same lines as you Dizzy. I want to keep the function self-contained. Thanks again all.
srand and rand is sufficient for most purposes.
The mersenne twister PRNG (Psuedo random number generator) provides better more random results across ranges of values. And you seed and poll it just like rand.
If you're in a C++ mood you could try:
#include <random> int random_no(int limit) { static std::minstd_rand gen; return std::uniform_int_distribution<int>(0, limit-1)(gen); }
Supposedly minstd_rand is a better random number generator than rand(). There are a few internet articles saying don't use rand()%limit and a few more saying it doesn't matter.
Thanks Peter, I figured there had to be a more current command.
As of now though, I updated my code to include a bool that limits the seeding to one time. It seems to work well. I also caught that I have a couple variables declared that I don't use for anything. I removed them (int number & char run) Must have used them years ago or was at least trialing a new approach back in the day.
Meanwhile, can you tell me if your approach would eliminate the need for different time functions, depending on while compiler I'm using? IE no need to seed?
Edgar, was this what you were mentioning as well?
Mersenne twister is in c++11. Pretty simple use, just google it.
Thanks Edgar. I just read the Wiki. Worth looking into deeper. I'll check it out.
You can see how I wrapped it to get regular numbers in my Eagle library.
https://github.com/EdgarReynaldo/EagleGUI/blob/master/src/Eagle/Random.cpp
https://github.com/EdgarReynaldo/EagleGUI/blob/master/include/Eagle/Random.hpp