Generating random number between [-1, 1] in C?

后端 未结 7 855
北恋
北恋 2020-12-08 21:57

I have seen many questions on SO about this particular subject but none of them has any answer for me, so I thought of asking this question.

I wanted to generate a r

7条回答
  •  隐瞒了意图╮
    2020-12-08 22:49

    I had a similar question a while back and thought that it might be more efficient to just generate the fractional part directly. I did some searching and came across an interesting fast floating point rand that doesn't use floating point division or multiplication or a int->float cast can be done with some intimate knowledge of the internal representation of a float:

    float sfrand( void )
    {
        unsigned int a=(rand()<<16)|rand();  //we use the bottom 23 bits of the int, so one
                                             //16 bit rand() won't cut it.
        a=(a&0x007fffff) | 0x40000000;  
    
        return( *((float*)&a) - 3.0f );
    }
    

    The first part generates a random float from [2^1,2^2), subtract 3 and you have [-1, 1). This of course may be too intimate for some applications/developers but it was just what I was looking for. This mechanism works well for any range that is a power of 2 wide.

提交回复
热议问题