generating random number with a specific distribution in c

前端 未结 2 1473
生来不讨喜
生来不讨喜 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: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.

提交回复
热议问题