rand() function not generating enough random

后端 未结 2 1249
星月不相逢
星月不相逢 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 17:07

    This has no business being in this function:

    srand(time(0));
    

    This should be called once at the beginning of your program (a good place is just inside main()); and most-certainly not in your display routine. Once the seed is set, you should never do it again for your process unless you want to repeat a prior sequence (which by the looks of it, you don't).

    That said, I would strongly advise using the functionality in that comes with your C++11 standard library. With it you can establish distributions (ex: uniform_int_distribution<>) that will do much of your modulo work for you, and correctly account for the problems such things can encounter (Andon pointed out one regarding likeliness of certain numbers based on the modulus).

    Spend some time with . Its worth it. An example that uses the three ranges you're using:

    #include 
    #include 
    using namespace std;
    
    int main()
    {
        std::random_device rd;
        std::default_random_engine rng(rd());
    
        // our distributions.        
        std::uniform_int_distribution<> dist1(50,60);
        std::uniform_int_distribution<> dist2(200,300);
        std::uniform_int_distribution<> dist3(0,100);
    
        for (int i=0;i<10;++i)
            std::cout << dist1(rng) << ',' << dist2(rng) << ',' << dist3(rng) << std::endl;
    
        return EXIT_SUCCESS;
    }
    

    Output (obviously varies).

    58,292,70
    56,233,41
    57,273,98
    52,204,8
    50,284,43
    51,292,48
    53,220,42
    54,281,64
    50,290,51
    53,220,7
    

    Yeah, it really is just that simple. Like I said, that library is this cat's pajamas. There are many more things it offers, including random normal distributions, different engine backends, etc. I highly encourage you to check into it.

提交回复
热议问题