看板 C_and_CPP 關於我們 聯絡資訊
今天買了支新鍵盤,是羅技的得意手。本來呢,是看上了它的輕薄短小,誰知回來才發現 -喵的竟然把方向鍵上的home、printscreen等鍵給我乾坤大挪移啦~這樣以後都沒辦法 盲打了。真是Orz...。把用了八年的BTC換掉,還真是有點捨不得呢。不管怎樣,這篇文 就是這支新嬌客的產品,希望未來可以好好的工作,不要出鎚就是。 以下是三支函數,分別可以產生服從gamma、normal及uniform的亂數。不過呢,這是我從 幾百年前的參考書裡面照著algorithm作出來的。所以,如果有問題,也請不要鞭我就是。 #define RANDOMIZE \ srand((unsigned int)_getseed()); \ #define RAND ((double)rand()/(double)RAND_MAX) /* This is my random seed, it doesn't use timer() for seeding but uses QueryPerformanceCounter(). */ unsigned int _getseed(void) { LARGE_INTEGER n; if(!QueryPerformanceCounter(&n)) return 0; return (unsigned int)n.QuadPart; } /* This is a function generates random numbers comply gamma distribution */ double _gamma(double alpha, double beta) { double a=pow(2*alpha-1,-0.5),b=alpha-log(4),q=alpha+1/a,t=4.5,d=1+log(t); double u1,u2; double v,y,z,w; redo: RANDOMIZE u1=RAND; u2=RAND; v=a*log(u1/(1-u1)); y=alpha*exp(v); z=pow(u1,2)*u2; w=b+q*v-y; if(w+d-t*z>=0) return y*beta; if(w>=log(z)) return y*beta; goto redo; } /* This is a function generates random numbers comply normal distribution. It implements the POLOR METHOD */11 double _normal(double mean, double variance) { double u1,u2; double v1,v2; double s,z; double stdev; redo: RANDOMIZE u1=RAND; u2=RAND; v1=2*u1-1; v2=2*u2-1; s=pow(v1,2.0)+pow(v2,2.0); if(s>=1) goto redo; z=sqrt(-2*log(s)/s)*v1; stdev=sqrt(variance); return z*stdev+mean; } /* as you see, it's just a uniform generater */ double _uniform(double a, double b) { double u; RANDOMIZE u=RAND; return a+(b-a)*u; } -- -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.166.202.151
drkkimo:好好研究看看~~@@ 03/20 01:04
drkkimo:gamma的return 後面的goto 是~??@@ 03/20 01:04
ccbruce:為了偷懶,沒用迴圈,用goto用懶人寫法 03/20 01:07
yoco315:random 那個好 :D 03/20 07:42
drkkimo:要修過統計才比較能了解.. 03/20 08:20
drugger:random process 03/20 12:20
lyonchen:good job~ 03/20 22:26