Random float number generation

后端 未结 14 1612
孤城傲影
孤城傲影 2020-11-22 05:05

How do I generate random floats in C++?

I thought I could take the integer rand and divide it by something, would that be adequate enough?

14条回答
  •  Happy的楠姐
    2020-11-22 05:40

    I wasn't satisfied by any of the answers so far so I wrote a new random float function. It makes bitwise assumptions about the float data type. It still needs a rand() function with at least 15 random bits.

    //Returns a random number in the range [0.0f, 1.0f).  Every
    //bit of the mantissa is randomized.
    float rnd(void){
      //Generate a random number in the range [0.5f, 1.0f).
      unsigned int ret = 0x3F000000 | (0x7FFFFF & ((rand() << 8) ^ rand()));
      unsigned short coinFlips;
    
      //If the coin is tails, return the number, otherwise
      //divide the random number by two by decrementing the
      //exponent and keep going. The exponent starts at 63.
      //Each loop represents 15 random bits, a.k.a. 'coin flips'.
      #define RND_INNER_LOOP() \
        if( coinFlips & 1 ) break; \
        coinFlips >>= 1; \
        ret -= 0x800000
      for(;;){
        coinFlips = rand();
        RND_INNER_LOOP(); RND_INNER_LOOP(); RND_INNER_LOOP();
        //At this point, the exponent is 60, 45, 30, 15, or 0.
        //If the exponent is 0, then the number equals 0.0f.
        if( ! (ret & 0x3F800000) ) return 0.0f;
        RND_INNER_LOOP(); RND_INNER_LOOP(); RND_INNER_LOOP();
        RND_INNER_LOOP(); RND_INNER_LOOP(); RND_INNER_LOOP();
        RND_INNER_LOOP(); RND_INNER_LOOP(); RND_INNER_LOOP();
        RND_INNER_LOOP(); RND_INNER_LOOP(); RND_INNER_LOOP();
      }
      return *((float *)(&ret));
    }
    

提交回复
热议问题