[英]glibc rand() doesn't work with python but works fine in online compiler
我正在嘗試將glibc rand()函數嵌入python。 我的目的是基於使用LCG的假設來預測rand()的下一個值。 我讀過它僅在8字節狀態下使用LCG,因此我試圖使用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中調用時,上面的代碼不斷向我的initial_values列表中添加12345。 但是,在www.onlinegdb.com上運行C代碼時,我得到了更為合理的數字列表(11035275900、3774015750等)。 當我在initialize()
方法中調用initstate(seed, state, sizeof(state))
之后使用setstate(state)
時,只能在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
結束時state
就不會消失,
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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.