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

后端 未结 7 811
北恋
北恋 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 23:02

    If all you have is the Standard C library, then other people's answers are sensible. If you have POSIX functionality available to you, consider using the drand48() family of functions. In particular:

    #define _XOPEN_SOURCE 600  /* Request non-standard functions */
    #include <stdlib.h>
    
    double f = +1.0 - 2.0 * drand48();
    double g = -1.0 + 2.0 * drand48();
    

    Note that the manual says:

    The drand48() and erand48() functions shall return non-negative, double-precision, floating-point values, uniformly distributed over the interval [0.0,1.0).

    If you strictly need [-1.0,+1.0] (as opposed to [-1.0,+1.0)), then you face a very delicate problem with how to extend the range.

    The drand48() functions give you considerably more randomness than the typical implementation of rand(). However, if you need cryptographic randomness, none of these are appropriate; you need to look for 'cryptographically strong PRNG' (PRNG = pseudo-random number generator).

    0 讨论(0)
提交回复
热议问题