使随机数趋于/平均到特定值

2022-01-17 00:00:00 random numbers c++

例如,我如何生成一个介于 0 和 1 之间的随机数列表,但让它们的平均值为 0.8?

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

我用 C++ 编写了这个小脚本,它会告诉你输出了哪些数字.不过,这个问题与 C++ 无关.

I have written this little script in C++ that'll tell you what numbers got output. This question is not really C++ related though.

#include <iostream>
#include <random>
#include <time.h>
int main(int argCount, char** argVector) {
    std::cout << "Generating Randoms" << std::endl;

    float avarage = 0.F;
    srand(rand() + (int) time(NULL));
    float ceiling = 0;
    float bottom = 1;
    for(unsigned int i = 0; i < 1000000; i++) {
        float random = (float) (rand() % 101) / 100;
        if(random > ceiling)
            ceiling = random;
        else if(random < bottom)
            bottom = random;
        avarage += random;
    }
    std::cout << "Avarage: " << avarage/1000000 << std::endl;
    std::cout << "Ceiling: " << ceiling << std::endl;
    std::cout << "Bottom: " << bottom << std::endl;
    return 0;
}

这个输出:

Generating Randoms
Avarage: 0.499287
Ceiling: 1
Bottom: 0

我希望上限和下限仍为 0 和 1,但能够更改平均值.该算法最好也应该是有效的.

I would like the ceiling and bottom to be still 0 and 1, but be able to change the average. The algorithm should preferably be efficient too.

我现在再次发布 C++ 代码,但任何语言都可以.

Once again, I'm now posting C++ code, but any language will do.

推荐答案

NolanPower 有一个使用权力的好主意,但他推荐的选择权力的机制是关闭的.如果随机数 U 是统一的 (0,1),则无意识统计学家的 法则 表示我们可以将任何函数 g(U) 的期望值导出为 Integral[g(U) 从:0 到:1].如果我们的函数 g(U) 是一个多项式,即对于某个常数 cU**c,求积分会产生通解1/(c + 1) 作为预期值.将其设置为所需的平均值 m 并求解,我们得到 c = (1/m) - 1.

NolanPower had a great idea using powers, but the mechanism he recommended for choosing the power is off. If the random numbers U are uniform(0,1) the law of the unconscious statistician says we can derive the expected value of any function g(U) as Integral[g(U) from: 0 to: 1]. If our function g(U) is a polynomial, i.e., U**c for some constant c, evaluating the integral yields the general solution 1 / (c + 1) as the expected value. Setting this equal to the desired mean m and solving, we get that c = (1 / m) - 1.

要获得 0.8 的预期值,c = (1/0.8) - 1 = 0.25,即,计算出 U**0.25.要获得 0.2 的期望值,c = (1/0.2) - 1 = 4,即使用 U**4 生成值.

To get an expected value of 0.8, c = (1 / 0.8) - 1 = 0.25, i.e., crank out U**0.25. To get an expected value of 0.2, c = (1 / 0.2) - 1 = 4, i.e., generate values using U**4.

相关文章