首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用ctype将数组从python传递到C,然后在Python中使用该数组

使用ctype将数组从python传递到C,然后在Python中使用该数组
EN

Stack Overflow用户
提问于 2020-10-25 21:11:36
回答 1查看 83关注 0票数 0

我正在试着做一个histogram of Poisson random generated variables using Python and C。我想使用Python for plottingC for generating. This resulted in the following to codes

Python:

代码语言:javascript
运行
复制
import ctypes
import numpy as np
import matplotlib.pyplot as plt
import time

lam = 5.0
n = 1000000

def generate_poisson(lam, n):
    array = np.zeros(n, dtype= np.int)
    f = ctypes.CDLL('./generate_poisson.so').gen_poisson
    f(ctypes.c_double(lam), ctypes.c_int(n), ctypes.c_void_p(array.ctypes.data))
    return array

start_time = time.time()
array = generate_poisson(lam,n)
print(time.time() - start_time)

plt.hist(array, bins = [0,1,2,3,4,5,6,7,8,9,10,11,12], density = True)
plt.savefig('fig.png')
print(array)

C:

代码语言:javascript
运行
复制
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

double get_random() { return ((double)rand() / (double)RAND_MAX); }

int poisson_random(double lam){
    int X;
    double prod, U, explam;

    explam = exp(-lam);
    X = 0;
    prod = 1.0;
    while (1){
        U = get_random();
        prod *= U;
        if (prod > explam){
            X+=1;
        }
        else {
            return X;
        }
    }
}

void gen_poisson(double lam, int n, void * arrayv)
{
    int * array = (int *) arrayv;
    int index = 0;
    srand(time(NULL));

    for (int i =0; i<n; i++, index++){
        //printf("before %d\n", array[i]);
        array[index++] = poisson_random(lam);
        //printf("after %d\n", array[i]);
    }
}

理解这种方法工作的原因,或者至少它看起来工作正常的问题,出现在gen_poisson()中的for循环中。以某种方式使用array[index++]而不是array[index]会得到正确的直方图。但我真的不明白为什么一定要这样。当for循环更改为

代码语言:javascript
运行
复制
for (int i =0; i<2*n; i++){
        //printf("before %d\n", array[i]);
        array[i++] = poisson_random(lam);
        //printf("after %d\n", array[i]);
}

有人能解释一下为什么在这种情况下循环必须递增两次吗?我刚开始用C编程,虽然我有一些Python的经验。因此,假设罪魁祸首是我对C的缺乏理解。

EN

回答 1

Stack Overflow用户

发布于 2020-10-26 03:54:04

gen_poisson更改为:

代码语言:javascript
运行
复制
void gen_poisson(double lam, int n, void * arrayv)
{
    long * array = (long *) arrayv;
    srand(time(NULL));
    for (int i =0; i<n; i++){
        array[i] = poisson_random(lam);
    }
}

解决了问题。正如将数组声明为int *而不是long *时所指出的问题一样。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64524071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档