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;
}
这个输出:
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)
是一个多项式,即对于某个常数 c
的 U**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
.
这篇关于使随机数趋于/平均到特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使随机数趋于/平均到特定值
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01