What is a good random number generator for a game?

前端 未结 16 1553
渐次进展
渐次进展 2020-12-02 04:26

What is a good random number generator to use for a game in C++?

My considerations are:

  1. Lots of random numbers are needed, so speed is good.
  2. P
16条回答
  •  一整个雨季
    2020-12-02 05:18

    Based on the random number generator by Ian C. Bullard:

    // utils.hpp
    namespace utils {
        void srand(unsigned int seed);
        void srand();
        unsigned int rand();
    }
    
    // utils.cpp
    #include "utils.hpp"
    #include 
    
    namespace {
        static unsigned int s_rand_high = 1;
        static unsigned int s_rand_low = 1 ^ 0x49616E42;
    }
    
    void utils::srand(unsigned int seed)
    {
        s_rand_high = seed;
        s_rand_low = seed ^ 0x49616E42;
    }
    
    void utils::srand()
    {
        utils::srand(static_cast(time(0)));
    }
    
    unsigned int utils::rand()
    {
        static const int shift = sizeof(int) / 2;
        s_rand_high = (s_rand_high >> shift) + (s_rand_high << shift);
        s_rand_high += s_rand_low;
        s_rand_low += s_rand_high;
        return s_rand_high;
    }
    

    Why?

    • very, very fast
    • higher entropy than most standard rand() implementations
    • easy to understand

提交回复
热议问题