c-将python转换为cython时的变量类型



我在Python中使用递归循环来计算随机行走到L点的第一次通过时间。我已经编写了代码,但我想通过将其转换为Cython来优化它,但我没有使用C的经验,我不知道如何将此代码转换为适合优化的代码,也不知道如何描述变量类型。如有任何帮助,我们将不胜感激。

%%cython
import numpy as np
cimport numpy as np
def f_passagetime_rec_cython(L,start=[0,0]):

T=10000000
r = np.zeros((T,2))
r[0]=start
delta = 1
greater=False
for i in range (0,T - 1):
if r[i,0]<=L:
theta = np.random.uniform(0, 2*np.pi, size = None)
r[i + 1,0] = r[i,0] + np.cos(theta)*delta                
r[i + 1,1] = r[i,1] + np.sin(theta)*delta
else:
greater=True
return i

if greater==False:
x=f_passagetime_rec_cython(L,r[-1])
i=x+1+i
return i

这就是我建议细胞化的方式。创建setup.py文件:

from setuptools import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize("function.pyx")
)

那么你的function.pyx文件基本上就是你的python代码:

import numpy as np
def f_passagetime_rec_cython(L,start=[0,0]):

T=10000000
r = np.zeros((T,2))
r[0]=start
delta = 1
greater=False
for i in range (0,T - 1):
if r[i,0]<=L:
theta = np.random.uniform(0, 2*np.pi, size = None)
r[i + 1,0] = r[i,0] + np.cos(theta)*delta                
r[i + 1,1] = r[i,1] + np.sin(theta)*delta
else:
greater=True
return i

if greater==False:
x=f_passagetime_rec_cython(L,r[-1])
i=x+1+i
return i

然后在终端中构建如下所示的细胞化功能:

python setup.py build_ext --inplace

您可以通过使用标准Python语法导入来访问cythonised函数:

import function
function.f_passagetime_rec_cython(10)

最新更新