繁体   English   中英

glibc rand()不适用于python,但在在线编译器中可以正常工作

[英]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));
}

对我来说似乎是错误的。 stateinitialize的局部变量,当函数结束时,该变量停止退出,因此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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM