【发布时间】:2015-03-25 08:19:28
【问题描述】:
我正在尝试生成属于指数分布的随机值。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <math.h>
using namespace std;
int main(){
double x;
double random;
double one=1.0;
for(int i=0; i<1000; i++){
x = ((double) rand() / (RAND_MAX));
cout << random <<endl;
x=log(one-random)/(-3);
cout<< x<< endl;
cout<< "__"<<endl;
}
return 0;
}
我正在使用我在这篇文章Pseudorandom Number Generator - Exponential Distribution 中读到的这个公式x = log(1-u)/(−λ)
但我看到的输出是这个:
3.90272e-319
0
__
3.90272e-319
0
__
3.90272e-319
0
__
3.90272e-319
0
__
and so on
总是打印相同的随机数值,对数的结果总是0,我看不懂。
【问题讨论】:
-
您需要用时间或其他东西调用 srand,以便每次运行时获得一些不同的数字。
-
换行到
x = ((double) rand() / (RAND_MAX));到random = ((double) rand() / (RAND_MAX)); -
rand()的输出从未在示例代码中实际使用过。它被破坏了几行。因此,随机种子未初始化的事实不是问题所在,并且使得这个问题不完全是与使用rand()有关的问题的重复。 -
你可以删除
one-,U(0,1) 相当于 1-U(0,1) -
您不需要编写代码; C++ 有一个内置的指数分布:stackoverflow.com/questions/11491458/…
标签: c++ random logarithm exponential