Random float number

后端 未结 5 488
有刺的猬
有刺的猬 2020-12-16 00:41

I wrote this function to get a pseudo random float between 0 .. 1 inclusive:

float randomFloat()
{
      float r = (float)rand()/(float)RAND_MAX;
      retur         


        
相关标签:
5条回答
  • 2020-12-16 00:55

    That is because the C random-generator is a pseudo-random generator (and that is, BTW, a very good thing, with many applications). (The ANSI C standard requires such a pseudo-random generator)

    Essentially each time your console application is re-started it uses the same [default] seed for the random generator.

    by adding a line like

      srand(time(NULL));
    

    you will get a distinct seed each time, and the sequence of number produced with vary accordingly.
    Note: you only need to call srand() once, not before each time you call rand().

    Edit: (Test/Debug-time hint)
    [from a remark by Artelius] For testing purposes, it's best to srand(SOME_CONST), and change the value of the constant between runs. This way if a bug manifests itself due to some combination of random numbers, you'll be able to reproduce it.

    0 讨论(0)
  • 2020-12-16 01:01

    Do you call it more than once? rand() will always return the same pseudo random. You might want to call srand() with some nice seed, like the current time.

    0 讨论(0)
  • 2020-12-16 01:18

    You need to call

    srand(time(NULL));
    

    before using rand for the first time. time is in <time.h>.

    EDIT: As Jonathan Leffler points out, this is easily predicted, so don't try using it for cryprography.

    0 讨论(0)
  • 2020-12-16 01:18

    drand48 is perfect for your usage, better than (float)rand()/RAND_MAX, because

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

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    int main() {
        int i;
    
        srand48(time(NULL));
    
        for (i = 0; i < 10; i++)
            printf("%g\n", drand48());
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-16 01:19

    You have to initialize a random seed with

    void srand ( unsigned int seed );
    

    You can take for example the system time.

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