[Cython] is aprogramming
language that makes
writing C extensions for the
Python language as easy as
Python itself.
http://cython.org/docs/current/src/quickstart/overview.html
http://cython.org/docs/current/src/quickstart/overview.html
• 変数の型宣言(しなくてもよい)
• Pythonの型も使える
• Python っぽいコード
def newton(double init):
cdef list result = []
cdef double current = init
cdef double past = 0
while True:
past = current
current = (current + (7 / current)) / 2
if abs(current - past) < 1e-10:
break
result.append(current)
return result
if __name__ == '__main__':
print(newton(3))
Cython の関数定義
• Cythonでは、Python 関数だけでなく
C 関数も定義できる(Pythonic に!)
• C 関数は Python コードから
直接呼びだせないことに注意
29.
• cdef キーワードで定義
•cpdef キーワードを用いると、
Python からは Python 関数を、
C からは C 関数を呼んでくれる(はず)
cpdef int tarai(int x, int y, int z):
if x <= y:
return y
else:
return tarai(
tarai(x-1, y, z),
tarai(y-1, z, x),
tarai(z-1, x, y)
)