需要一个快速随机生成器的c ++ [英] Need a fast random generator for c++

查看:103
本文介绍了需要一个快速随机生成器的c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对我的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等)。所以没有boost = /

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 ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆