什么是兰特合适的替代者()? [英] What is a suitable replacement for rand()?

查看:129
本文介绍了什么是兰特合适的替代者()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知兰特()不生成均匀随机分布。什么功能/算法会允许我这样做?我有没有必要加密随机性,只有一个统一的随机分布。最后,有什么库提供这些功能呢?
谢谢!

As far as I know rand() does not generate a uniform random distribution. What function/algorithm will allow me to do so? I have no need for cryptographic randomness, only a uniform random distribution. Lastly, what libraries provide these functions? Thanks!

推荐答案

兰特()确实的生成一个统一的(伪)随机分布

rand() does generate a uniform (pseudo-)random distribution.

的实际需求,从 C标准(3.7 MB PDF)第7.20.2.1是:

The actual requirement, from the C standard (3.7 MB PDF), section 7.20.2.1, is:

兰特函数计算的伪随机整数序列中
  到范围0 RAND_MAX

The rand function computes a sequence of pseudo-random integers in the range 0 to RAND_MAX.

其中RAND_MAX至少32767这是无可否认的模糊,但其意图是,它给你一个均匀分布 - 在实践中,这就是实现真正做到

where RAND_MAX is at least 32767. That's admittedly vague, but the intent is that it gives you a uniform distribution -- and in practice, that's what implementations actually do.

该标准提供了一个示例实现,但C实现并不需要使用它。

The standard provides a sample implementation, but C implementations aren't required to use it.

在实践中,一定会有更好的随机数生成器在那里。和一个特定的要求兰特()是,它必须产生的数字对于一个给定的种子(参数完全相同的序列函数srand())。您的描述并不表示这将是你的问题。

In practice, there are certainly better random number generators out there. And one specific requirement for rand() is that it must produce exactly the same sequence of numbers for a given seed (argument to srand()). Your description doesn't indicate that that would be a problem for you.

一个问题是,兰特()为您提供了一个固定的范围内均匀分布的数字。如果你想在一个不同的号码范围,你必须做一些额外的工作。例如,如果RAND_MAX是32767,那么兰特()可生产32768不同的值;你不能在0..9范围内的随机数,不丢弃一些值,因为没有办法的32768不同的值均匀地分布到10相同大小的水桶。

One problem is that rand() gives you uniformly distributed numbers in a fixed range. If you want numbers in a different range, you have to do some extra work. For example, if RAND_MAX is 32767, then rand() can produce 32768 distinct values; you can't get random numbers in the range 0..9 without discarding some values, since there's no way to evenly distribute those 32768 distinct values into 10 equal sized buckets.

其他的PRNG很可能给你比更好的结果兰特(),但他们仍然可能将受到相同的问题。

Other PRNGs are likely to give you better results than rand(), but they're still probably going to be subject to the same issues.

像往常一样, comp.lang.c常见问题解答这比我好;见问题13.15 13.21通过

As usual, the comp.lang.c FAQ answers this better than I did; see questions 13.15 through 13.21.

这篇关于什么是兰特合适的替代者()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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