使用概率分布函数生成随机数的 C++ 程序
概率密度函数(pdf)是描述此随机变量取给定值的相对可能性的函数。它也称为连续随机变量的密度。
随机变量落在特定值范围内的概率由该变量在该范围内的密度积分给出,因此,它由密度函数下但在水平轴上方以及最低值和最大值之间的面积给出范围的。概率分布基于此概率密度函数。
算法
Begin Declare n Assign pdf=0 For i =0 to n , do pdf = rand() mod 200 If pdf greater than 360 Print 1 Else if pdf less than 0 Print 0 Else Print pdf * 0.1 / 360 Done Done end
示例代码
#include输出结果using namespace std; int n = 6; int main(int argc, char **argv) { int pdf = 0; for (int i = 0; i < n; i++) { pdf = rand() % 200; if (pdf > 360) cout << 1 << " "; else if (pdf < 0) cout << 0 << " "; else cout << pdf * 0.1 / 360 << " "; } cout << "..."; }
0.0508333 0.0238889 0.0491667 0.0319444 0.0536111 0.0375 ...