Special simple random number generator

后端 未结 7 2073
一整个雨季
一整个雨季 2020-12-01 08:47

How to create a function, which on every call generates a random integer number? This number must be most random as possible (according to uniform distribution). It is only

相关标签:
7条回答
  • 2020-12-01 08:49

    Here's a function with uniform distribution over the entire range of int:

    int rand()
    {
      static int random = 0;
      return random++;
    }
    
    0 讨论(0)
  • 2020-12-01 08:55

    I use this

    SUBROUTINE GNA(iiseed)
        USE Variaveis
        parameter (ia=843314861,ib=453816693,m=1073741824, r231=1./2147483648.)
        INTEGER :: iiseed
    
        iiseed = ib + ia*iiseed
        if (iiseed.lt.0) iiseed = (iiseed+m) + m
        RndNum = iiseed*r231
    
    END SUBROUTINE GNA
    

    A big gain of randomness can be achieved without spending more computational time creating a random number generator for each call the random number generator made in the program.

    This is a very good trick!

    0 讨论(0)
  • 2020-12-01 08:56

    You might have a look at this. It's far from beeing a "perfect" random number generator, but it does fulfil your requirements as far as i can see.

    Here you can find some additional information about random number generation.

    0 讨论(0)
  • 2020-12-01 08:57

    Boost has a very nice random number library, and the source code is available, so you could try looking there and using what you need (i.e. cut and paste).

    0 讨论(0)
  • 2020-12-01 08:58
    public long randomLong() {
      x ^= (x << 21);
      x ^= (x >>> 35);
      x ^= (x << 4);
      return x;
    }
    

    Seed cannot be 0. Source: http://www.javamex.com/tutorials/random_numbers/xorshift.shtml#.VlcaYzKwEV8

    Additional info in wiki: https://en.wikipedia.org/wiki/Xorshift

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

    If I write man rand, I can read a possible example, given in POSIX.1-2001, for implementing rand() and srand(). See e.g. here. If you need something more sophisticated, take a look at GNU Scientific Library; you can of course download the code and see the implementation(s).

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