generating random number with a specific distribution in c

前端 未结 2 1450
生来不讨喜
生来不讨喜 2020-12-31 10:59

i need a library with functions for generating random number, given average, standard deviation and using one of three distribution - exponential, normal or unified.

<
相关标签:
2条回答
  • 2020-12-31 11:56

    May I recommend the GNU Scientific Library either for use or for inspiration? It has several Random Number Distributions and is designed to be used from C and C++.

    0 讨论(0)
  • 2020-12-31 11:58

    uniform:
    Generate a random number in the range [0,1] with uniform distribution:

    double X=((double)rand()/(double)RAND_MAX);
    

    Exponentional
    generating an exponentional random variable with parameter lambda:

    -ln(U)/lambda (where U~Uniform[0,1]). 
    

    normal:
    the simplest way [though time consuming] is using the central limit theorem, [sum enough uniformly distributed numbers] but there are other methods in the wikipedia page such as the box muller transform that generates 2 independent random variables: X,Y~N(0,1)

    X=sqrt(-2ln(U))*cos(2*pi*V)
    Y=sqrt(-2ln(U))*sin(2*pi*V)
    where U,V~UNIFORM[0,1]
    

    transforming from X~N(0,1) to Z~N(m,s^2) is simple: Z = s*X + m

    Though you CAN generate these random numbers, I stand by @Amigable Clark Kant suggestion to use an existing library.

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