幫一個朋友做管理學科研究生階段的一個作業,是對庫存系統模擬,其中裡面零售商的需求是泊松分布的隨機數。需要用C語言產生泊松分布的隨機數,通過找資料和編程實踐,簡單的程式寫了出來,如下,供參考。
| 代碼如下 |
複製代碼 |
algorithm poisson random number (Knuth):
init:
Let L ← exp(−λ), k ← 0 and p ← 1.
do:
k ← k + 1.
Generate uniform. random number u in [0,1] and let p ← p × u.
while p >= L.
return (k − 1). |
C語言實現的泊松分布隨機數的代碼如下:
| 代碼如下 |
複製代碼 |
#include <stdio.h>
#include <math.h>
#include <time.h>
double U_Random();
int possion();
void main()
{
double u = U_Random();
int p = possion();
printf("%fn",u);
printf("%dn",p);
}
int possion() /* 產生一個泊松分布的隨機數,Lamda為總體平均數*/
{
int Lambda = 20, k = 0;
long double p = 1.0;
long double l=exp(-Lambda); /* 為了精度,才定義為long double的,exp(-Lambda)是接近0的小數*/
printf("%.15Lfn",l);
while (p>=l)
{
double u = U_Random();
p *= u;
k++;
}
return k-1;
}
double U_Random() /* 產生一個0~1之間的隨機數 */
{
double f;
srand( (unsigned)time( NULL ) );
f = (float)(rand() % 100);
/* printf("%fn",f); */
return f/100;
} |
關於這個簡單的庫存模擬的全部代碼:https://github.com/smilejay/c-cpp/tree/master/inventory-simulation