使随机数趋向于特定值的平均值 [英] Make Random Numbers Tend / Average to a Specific Value
问题描述
我如何生成一个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;
}
此输出:
This outputs:
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)
as Integral [g从:0到:1]
。如果我们的函数 g(U)
是一个多项式,即 U ** c
c> 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
.
这篇关于使随机数趋向于特定值的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!