I had made a Pong game where I had to randomize the throw of the ball. To do this, I used the inbuilt random number generator and got good results in Ubuntu/GCC. On porting the code to Mac and compiling, the ball would only be projected in a single direction, meaning that the rand()
function in clang was not working as expected.
I have since reverted to a custom number generator, but here's the original problematic code in the game:
srand(time(NULL));
float ang = ((float)rand())/RAND_MAX * 120 - 60;
int side = (int)(((float)rand())/RAND_MAX * 2);
Upon further inspection, I created the following test program and compiled and ran it on both platforms.
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char** argv) {
while (1) {
int now = time(NULL);
printf("Time now is %d\n", now);
srand(now);
int random = rand();
printf("Random number generated is %d\n", random);
sleep(1);
}
}
The results (tabulated and calculated against RAND_MAX
, which is 2147483647
on both systems) are as follows:
The results speak for themselves. While there is randomness in the clang version, as compared to the value of RAND_MAX
, the randomness is very poor and is evidenced by the standard deviation of 0, compared to the standard deviation of 0.328 on gcc.
What are the reason(s) for this poor behaviour of rand()
on clang? I would also like to see the reference implementation of this function in the header file. This seems nonstandard, and I must not be the only one who ran into problems while porting programs using this method to Mac. What other design principles are good practice while using/relying upon random number generators?
Aucun commentaire:
Enregistrer un commentaire