問題描述
我正在嘗試在我的 TSP 生成器上對歐幾里德距離進行一些 opt-3 交換,并且由于在許多情況下我有超過 500 個節點,因此我需要隨機選擇我想要的 3 個節點中的至少 1 個嘗試交換.
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.
所以基本上我需要一個快速的隨機數函數.(普通的 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.
我忘了說,我所處的環境除了標準語言庫(例如 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 =/
推薦答案
另一個帖子提到了 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;
}
我到處都在使用這個.唯一失敗的地方是我嘗試生成隨機二進制矩陣時.超過大約 95x95 的矩陣,它開始生成太少或太多的奇異矩陣(我忘記了哪個).已經證明該發生器等效于線性移位反饋寄存器.但是除非你在做密碼學或認真的蒙特卡洛工作,否則這個生成器會很厲害.
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.
這篇關于需要一個快速的 C++ 隨機生成器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!