rand() function not generating enough random

后端 未结 2 1213
星月不相逢
星月不相逢 2021-01-21 16:17

I am working on an openGL project and my rand function is not giving me a big enough random range. I am tasked with writing a diamond program to where one diamond is centered on

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 16:46

    As WhozCraig mentioned, seeding your random number generator with the time every time you call myDisplay (...) is a bad idea. This is because time (NULL) has a granularity of 1 second, and in real-time graphics you usually draw your scene more than one time per-second. Thus, you are repeating the same sequence of random numbers every time you call myDisplay (...) when less than 1 second has elapsed.

    Also, using modulo arithmetic on a call to rand (...) adversely affects the quality of the returned values. This is because it changes the probability distribution for numbers occurring. The preferred technique should be to cast rand (...) to float and then divide by RAND_MAX, and then multiply this result by your desired range.

    GLfloat x = rand() % 50 + 10; /* <-- Bad! */
    
    /* Consider this instead */
    GLfloat x = (GLfloat)rand () / RAND_MAX * 50.0f + 10.0f;
    

    Although, come to think of it. Why are you using GLfloat for x and y if you are going to store them in an integer data structure 2 lines later?

提交回复
热议问题