Random float number generation

后端 未结 14 1322
孤城傲影
孤城傲影 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条回答
  •  孤独总比滥情好
    2020-11-22 05:27

    On some systems (Windows with VC springs to mind, currently), RAND_MAX is ridiculously small, i. e. only 15 bit. When dividing by RAND_MAX you are only generating a mantissa of 15 bit instead of the 23 possible bits. This may or may not be a problem for you, but you're missing out some values in that case.

    Oh, just noticed that there was already a comment for that problem. Anyway, here's some code that might solve this for you:

    float r = (float)((rand() << 15 + rand()) & ((1 << 24) - 1)) / (1 << 24);
    

    Untested, but might work :-)

提交回复
热议问题