问题描述
在Cython中的[0,1]
中生成随机随机数的最有效,最便捷的方法是什么?一种方法是使用C库中的INT_MAX
和rand()
:
What is the most efficient and portable way to generate a random random in [0,1]
in Cython? One approach is to use INT_MAX
and rand()
from the C library:
from libc.stdlib cimport rand
cdef extern from "limits.h":
int INT_MAX
cdef float randnum = rand() / float(INT_MAX)
以这种方式使用INT_MAX
可以吗?我注意到它与您从Python的max int获得的常数有很大的不同:
Is it OK to use INT_MAX
in this way? I noticed that it's quite different from the constant you get from Python's max int:
import sys
print INT_MAX
print sys.maxint
产量:
2147483647 (C max int)
9223372036854775807 (python max int)
对于rand()
,哪个是正确的规范化"数字? 编辑,如果使用C方法从libc调用rand()
的话,如何设置随机种子(例如,基于当前时间播种)?
Which is the right "normalization" number for rand()
? EDIT additionally, how can the random seed be set (e.g. seeded based on current time) if one uses the C approach of calling rand()
from libc?
推荐答案
C标准说,rand
返回范围为0到RAND_MAX(含)的int
,因此将其除以RAND_MAX(从stdlib.h
开始)是规范化它的正确方法.实际上,RAND_MAX几乎总是等于MAX_INT,但不要依赖于此.
The C standard says rand
returns an int
in the range 0 to RAND_MAX inclusive, so dividing it by RAND_MAX (from stdlib.h
) is the proper way to normalise it. In practice, RAND_MAX will almost always be equal to MAX_INT, but don't rely on that.
由于rand
自C89以来就已成为ISO C的一部分,因此可以保证它随处可见,但不能保证其随机数的质量.但是,如果主要考虑可移植性,除非您愿意使用Python的random
模块,否则这是您的最佳选择.
Because rand
has been part of ISO C since C89, it's guaranteed to be available everywhere, but no guarantees are made regarding the quality of its random numbers. If portability is your main concern, though, it's your best option, unless you're willing to use Python's random
module.
Python的 sys.maxint
完全是一个不同的概念;它只是Python可以在自己的 int类型中表示的最大正数;较大的将必须是多头. Python的int和long与C并没有特别的关系.
Python's sys.maxint
is a different concept entirely; it's just the largest positive number Python can represent in its own int type; larger ones will have to be longs. Python's ints and longs aren't particularly related to C's.
这篇关于在Cython中生成随机数的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!