我正在尝试将glibc rand()函数嵌入到python中。我的目的是根据使用LCG的假设预测rand()的下一个值。我已经读过它只使用LCG,如果它在8字节状态下运行,所以我试图使用initstate方法来设置它。
我的glibc_random.c文件中有以下代码:
#include <stdlib.h>
#include "glibc_random.h"
void initialize()
{
unsigned int seed = 1;
char state[8];
initstate(seed, state, sizeof(state));
}
long int call_glibc_random()
{
long r = rand();
return r;
}
以及各自的glibc_random.h中的以下内容:
void initialize();
long int call_glibc_random();
python中的代码:
def test():
glibc_random.initialize()
number_of_initial_values = 10
number_of_values_to_predict = 5
initial_values = []
for i in range(number_of_initial_values):
initial_values.extend([glibc_random.call_glibc_random()])
在python中调用时,上面的代码不断将12345添加到我的initial_values列表中。但是,当在www.onlinegdb.com中运行C代码时,我得到一个更合理的数字列表(11035275900,3774015750等)。当我在setstate(state)
方法中调用initstate(seed, state, sizeof(state))
之后使用initialize()
时,我只能在onlinegdb中重现我的问题。
任何人都可以在这里提出错误的建议吗?我正在使用swig和python2.7,顺便说一句。
我之前从未使用过initstate
void initialize()
{
unsigned int seed = 1;
char state[8];
initstate(seed, state, sizeof(state));
}
对我来说似乎不对。 state
是initialize
的局部变量,当函数结束时,变量停止退出,因此rand()
可能会给你垃圾,因为它试图访问不再有效的指针。
您可以将state
声明为static
,以便在initialize
结束时它不会停止存在,
void initialize()
{
unsigned int seed = 1;
static char state[8];
initstate(seed, state, sizeof(state));
}
或使state
成为全局变量。
char state[8];
void initialize()
{
unsigned int seed = 1;
initstate(seed, state, sizeof(state));
}