生成可靠的伪随机数 [英] generate reliable pseudorandom number

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

问题描述

我想在iOS平台上写一个多人游戏。游戏依赖于动态生成的随机数,以决定接下来会发生什么。但这是一款多人游戏,因此每个玩家的所有设备的随机数应相同,以便获得一致的游戏。

I want to write a multiplayer game on iOS platform. The game relied on random numbers that generated dynamically in order to decide what happen next. But it is a multiplayer game so this "random number" should be the same for all device for every player in order to have a consistent game play.

因此我需要一个良好可靠的伪随机数生成器,如果我首先播种相同的数字,它将在所有设备(iPad / iPhone / iPodTouch)和所有操作系统版本上保持生成相同的随机数序列。

Therefor I need a good reliable pseudorandom number generator that if I seed it a same number first than it will keep generate same sequences of random number on all device (iPad/iPhone/iPodTouch) and all OS version.

看起来 srand rand 会为我做这个工作,但我不确定 rand 保证在所有操作系统版本的所有设备上生成相同的号码?否则是否有任何好的伪随机数生成算法?

Looks like srand and rand will do the job for me but I am not sure does rand guarantee to generate same number on all device across all OS version? Otherwise is any good pseudorandom number generate algorithm?

推荐答案

来自C标准(而Objective C是C层上的薄层)所以这应该仍然存在):

From the C standard (and Objective C is a thin layer on top of C so this should still hold):


如果使用相同的种子值调用srand,则应重复伪随机数序列。

If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated.

no 保证不同的实现(甚至不同版本的相同 implementation)将根据种子给出一致的序列。如果您确实想要保证这一点,您可以编写自己的线性同余生成器,例如标准本身中的示例:

There's no guarantee that different implementations (or even different versions of the same implementation) will give a consistent sequence based on the seed. If you really want to guarantee that, you can code up your own linear congruential generator, such as the example one in the standard itself:

// RAND_MAX assumed to be 32767.
static unsigned long int next = 1;
void srand(unsigned int seed) { next = seed; }
int rand(void) {
    next = next * 1103515245 + 12345;
    return (unsigned int)(next/65536) % 32768;
}

尽管周围有更好的发电机,但简单的线性同余一个人通常绰绰有余,除非你是统计学家或密码学家。

And, despite the fact that there are better generators around, the simple linear congruential one is generally more than adequate, unless you're a statistician or cryptographer.

这篇关于生成可靠的伪随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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