Christian Elsasser (che@physik.uzh.ch)
The content of this lecture might be distributed under CC by-sa.
def fib0(n):
a,b=1,1
for i in range(n):
a,b=a+b,a
return a
fib0(5)
fib0(6)
%timeit fib0(10000)
import cython
%load_ext Cython
%%cython
def helloWorld():
print("Hello, World!")
helloWorld
helloWorld()
%%cython
def fib1(n):
a,b=1,1
for i in range(n):
a,b=a+b,a
return a
fib1
fib1(5)
%timeit fib1(10000)
%%cython
def fib2(int n):
cdef int a,b,i
a,b=1,1
for i in range(n):
a,b=a+b,a
return a
fib2
fib2(5)
%timeit fib2(10000)
%%cython
from math import sin,exp
def f0(double x):
return sin(x)*exp(-x)
def integrate0(double a,double b,int N):
cdef double dx,s
cdef int i
dx = (b-a)/N
s = 0.0
for i in range(N):
s+=f0(a+(i+0.5)*dx)
return s*dx
from math import pi
integrate0(0.0,pi,1000000)
%timeit integrate0(0.0,pi,1000000)
%%cython
from math import sin,exp
cdef double f1(double x):
return sin(x)*exp(-x)
def integrate1(double a,double b,int N):
cdef double dx,s
cdef int i
dx = (b-a)/N
s = 0.0
for i in range(N):
s+=f1(a+(i+0.5)*dx)
return s*dx
%timeit integrate1(0.0,pi,1000000)
f1(5)
%%cython
from libc.math cimport sin,exp
cpdef double f2(double x):
return sin(x)*exp(-x)
def integrate2(double a,double b,int N):
cdef double dx,s
cdef int i
dx = (b-a)/N
s = 0.0
for i in range(N):
s+=f2(a+(i+0.5)*dx)
return s*dx
%timeit integrate2(0.0,pi,1000000)
import numpy as np
def f3(x):
return np.sin(x)*np.exp(-x)
def integrate3(a,b,N):
dx = (b-a)/N
x = (np.arange(N)+0.5)*dx+a
return np.sum(f3(x))*dx
%timeit integrate3(0.0,pi,1000000)
%%cython -+
#distutils: language = c++
from libcpp.vector cimport vector
def manipulateVector(vector[double] v):
v.push_back(42.0) # Equivalent to append for list in python
return v
manipulateVector([1,2,3,4])
%%cython
cpdef int raiseError():
raise RuntimeError("A problem!")
return 1
raiseError()
%%cython
cpdef int raiseErrorBetter() except *:
raise RuntimeError("A problem!")
return 1
try:
raiseErrorBetter()
except RuntimeError:
print("Error caught")
%%cython
cpdef int raiseException(int n) except -1:
# Assuming C function returning an integer; if -1 --> Error appeared
return n
raiseException(1)
raiseException(-1)
%%cython
from libc.math cimport sin,exp
cdef class Integrand(object):
cpdef double evaluate(self,double x):
raise NotImplementedError()
cdef class SinExpFunction(Integrand):
cpdef double evaluate(self,double x):
return sin(x)*exp(-x)
def integrate(Integrand f, double a, double b, int N):
cdef int i
cdef double dx,s
dx = (b-a)/N
s = 0.0
for i in range(N):
s += f.evaluate(a+(i+0.5)*dx)
return s*dx
f = SinExpFunction()
import math
%timeit integrate(f,0,math.pi,1000000)
class Poly(Integrand):
def evaluate(self,x):
return 3*x-x**3
g = Poly()
integrate(g,0,math.pi,10000)
%timeit integrate(g,0,math.pi,1000000)