Make Random Numbers Tend / Average to a Specific Value

前端 未结 3 631

How can I for example generate a list of random numbers between 0 and 1, but have them avarage at 0.8?

I have written this little script in C++ that\'ll tell you wh

3条回答
  •  囚心锁ツ
    2020-12-22 06:36

    Here's an example that generates a standard normal distribution, i.e. mu = 0, sigma = 1.

    I used the Box-Muller transform.

    All plots have x axis = value and y axis = frequency.

    #include 
    #include 
    #include 
    #include 
    int main(int argCount, char** argVector) {
        const double pi = 3.14159265359;
        const double nums = 1000000;
        double u, v, x;
    
        srand(rand() + (int) time(NULL));
    
        for(unsigned int i = 0; i < nums; i++){
            u = rand() / (((double)RAND_MAX) + 1.0);
            v = rand() / (((double)RAND_MAX) + 1.0);
            x = sqrt(-2*log(u)) * cos(2*pi*v);
    
            if (std::isfinite(x)){
                std::cout << x <<" ";
            }
        }
    
        return 0;
    }
    

    standardnorm

    >>> np.std(nums)
    1.0004139708929858
    >>> np.average(nums)
    7.1785002756408726e-05
    

    You can shift/scale x as necessary to obtain a mu and sigma of your choosing.

    Here's an example that gives a uniform distribution with a given mu:

    #include 
    #include 
    #include 
    #include 
    int main(int argCount, char** argVector) {
        const double pi = 3.14159265359;
        const double nums = 1000000;
        double x,mu;
    
        srand(rand() + (int) time(NULL));
        mu = 3.0;
    
        for(unsigned int i = 0; i < nums; i++){
            x = rand() / (((double)RAND_MAX) + 1.0);
            x *= 2*mu;
    
            if (std::isfinite(x)){
                std::cout << x <<" ";
            }
        }
    
        return 0;
    }
    

    unif

    >>> np.average(nums)
    3.0003091558133184
    

    You can use the documented rand() % range + min to truncate.

提交回复
热议问题