【发布时间】:2013-07-21 15:24:19
【问题描述】:
例如,我如何生成一个介于 0 和 1 之间的随机数列表,但让它们的平均值为 0.8?
我用 C++ 编写了这个小脚本,它会告诉你输出了哪些数字。不过,这个问题与 C++ 无关。
#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,但能够更改平均值。该算法最好也应该是有效的。
我现在再次发布 C++ 代码,但任何语言都可以。
【问题讨论】:
-
您有首选的发行版吗?如果要设置
mu,有很多选择。例如en.wikipedia.org/wiki/Normal_distribution。或者可能是均匀分布,或者 beta,或者...... -
好吧,如果平均值是 0.5,就像现在一样,我希望所有数字都有尽可能多的机会被选择为 0.5。如果它像 0.7,我希望数字在接近 0.7 时有更多机会,以使平均结果为 0.7。所以它并不是那个 wiki 页面。
-
我不确定我是否理解。您想要一个均值为 0.5 的均匀分布,但如果均值与 0.5 不同,则为非均匀分布?您需要指定接近 0.7 的数字的“机会”,在正态分布示例中,这基本上是方差参数。
-
几率是 1% 几率的直线。如果您希望 0.70 为平均值,请将线稍微转一下,使 0.70 仍然是 1%,但它前面的数字会更少机会,而它前面的数字会更多。
-
你能画出你的意思吗?请标记轴。