問題描述
我正在嘗試在我的 TSP 生成器上對(duì)歐幾里德距離進(jìn)行一些 opt-3 交換,并且由于在許多情況下我有超過 500 個(gè)節(jié)點(diǎn),因此我需要隨機(jī)選擇我想要的 3 個(gè)節(jié)點(diǎn)中的至少 1 個(gè)嘗試交換.
I'm trying to do some opt-3 swapping on my TSP generator for euclidian distances, and since I in many cases have more than ~500 nodes, I need to randomly select at least 1 of the 3 nodes that I want to try swapping.
所以基本上我需要一個(gè)快速的隨機(jī)數(shù)函數(shù).(普通的 rand() 太慢了)它不必很棒,只要 足夠.
So basically I need a random-number function that's fast. (the normal rand() is way too slow) It doesn't have to be awesome, just good enough.
我忘了說,我所處的環(huán)境除了標(biāo)準(zhǔn)語言庫(例如 STL、iostream 等)之外,我無法添加任何庫.所以沒有提升 =/
I forgot to mention, i'm sitting at an environment where I can't add any libraries except the Standard Language Library (such as STL, iostream etc). So no boost =/
推薦答案
另一個(gè)帖子提到了 Marsaglia 的 xorshf 生成器,但沒有人貼出代碼.
The other thread mentioned Marsaglia's xorshf generator, but no one posted the code.
static unsigned long x=123456789, y=362436069, z=521288629;
unsigned long xorshf96(void) { //period 2^96-1
unsigned long t;
x ^= x << 16;
x ^= x >> 5;
x ^= x << 1;
t = x;
x = y;
y = z;
z = t ^ x ^ y;
return z;
}
我到處都在使用這個(gè).唯一失敗的地方是我嘗試生成隨機(jī)二進(jìn)制矩陣時(shí).超過大約 95x95 的矩陣,它開始生成太少或太多的奇異矩陣(我忘記了哪個(gè)).已經(jīng)證明該發(fā)生器等效于線性移位反饋寄存器.但是除非你在做密碼學(xué)或認(rèn)真的蒙特卡洛工作,否則這個(gè)生成器會(huì)很厲害.
I've used this one all over the place. The only place it failed was when I was trying to produce random binary matrices. Past about 95x95 matrices, it starts generating too few or too many singular matrices (I forget which). It's been shown that this generator is equivalent to a linear shift feedback register. But unless you are doing cryptography or serious monte carlo work, this generator rocks.
這篇關(guān)于需要一個(gè)快速的 C++ 隨機(jī)生成器的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!