python - 将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
解决方案
这就是我建议cythonizing的方式。创建一个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
然后在终端中构建 cythonized 函数,如下所示:
python setup.py build_ext --inplace
您可以通过使用标准 Python 语法导入来访问 cythonised 函数:
import function
function.f_passagetime_rec_cython(10)
推荐阅读
- javascript - 正则表达式'/code.? * (\w {4}) /' 不起作用
- javascript - 如何在 jQuery 中暂停 FadeTo() 方法?
- angularjs - Angular JS - 如何从另一个元素的事件中更改输入的值
- python - Shutil zipping error和shutil rmtree错误,帮我理解
- pandas - 用pandas过滤DataFrame中满足另一个DataFrame条件的多个单独行?
- outlook - 如何将数据从 SQL Azure 导入 O365 Outlook 日历
- javascript - 为什么我的 Array.prototype.find() 返回未定义?
- time-series - Stata时间序列滚动预测
- node.js - 使用 MongoDB 和 NodeJS 更新数组中的字段
- reactjs - React/redux:我必须重新加载页面才能删除