MakeRandom bug crashing Linux
Posted: Sat Aug 29, 2015 4:03 pm
I ran into a problem with our MakeRandom() function today, which seems to work great for whole numbers but blew up soon as I tried to get a random value from a decimal. I sent in MakeRandom(0.94, 1) and Linux would explode. Windows, of course, loves it.
Upon investigating the function, it appears the srand() call is trying to turn my "diff" of 0.05 into an (int) (whole number) which resulted in zero, thus the arithmetic exception.
How I resolve it was this, though I not confident it was the best approach.
I added a "seed_diff" that is an int, the check if the original diff is 0, and if so use the seed_diff hardcoded to 1 instead. Otherwise, the function should behave as before.
If anyone has a better suggestion, please let me know.
Upon investigating the function, it appears the srand() call is trying to turn my "diff" of 0.05 into an (int) (whole number) which resulted in zero, thus the arithmetic exception.
Code: Select all
srand((uint32_t)time(0) * (time(0) % (int)diff));Code: Select all
float MakeRandom(float min, float max) { static bool seeded=0; float diff = max - min; int seed_diff = 0; // need to handle < 1.0 min/max if(!diff) return min; if(diff < 0) diff = 0 - diff; if((int)diff == 0) seed_diff = 1; else seed_diff = diff; if(!seeded) { srand((uint32_t)time(0) * (time(0) % (int)seed_diff)); seeded = true; } return (rand() / (float)RAND_MAX * diff + (min > max ? max : min));}If anyone has a better suggestion, please let me know.