Reputation: 2063
I know there are many duplicates of this question around but my problem is different. What I am trying to do is generating a simple random float number in the range [-0.5, 0.5]. What I have been using is the formula expressed in this link:
C++ random float number generation
I need two different random float numbers jitter_dx
and jitter_dy
. According to the formula of the link above I have:
float jitter_dx = -0.5f + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (0.5f - (-0.5f))));
float jitter_dy = -0.5f + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (0.5f - (-0.5f))));
Now, my problem is weird because when I try to debug the code, jitter_dx
seems being always the same (or slightly different) while jitter_dy
is generated quite randomly. I hereby give you the values of both jitter_dx
and jitter_dy
during 10 different debugging sessions:
0.213156521, 0.123004854
0.215659022, 0.323389411
0.216849267, 0.259575188
0.217856407, -0.460295409
0.218955040, 0.147907972
0.220358908, -0.259910882
0.221335471, 0.0202490091
0.224143207, 0.204702914
0.225333393, 0.140888691
As you can see jitter_dx
is always (almost) the same. Both values are calculated one right after the other one, without any code in the middle. May you help me finding the problem? Thanks in advance.
Upvotes: 1
Views: 564
Reputation: 50053
If I recall correctly, the sequence produced by MSVC's implementation of rand
after the common srand(time(NULL))
depends in a very predictable way on the time, in the sense that a small change in time (with small as in small compared to the time between 00:00:00 UTC on 1 January 1970 and 03:14:07 UTC on 19 January 2038) will lead to very similar resulting sequences.
If you insist on using rand
, discard the first couple hundred or thousand values it produces. Then the results will at least look better (while still being terrible).
What you really should do is use the modern <random>
(or boost.random if you cannot use C++11) facilities, for your application std::uniform_real_distribution
.
For further information, this is an interesting watch.
Upvotes: 6