%load_ext cythonmagic
%%cython
cdef double cf(double x):
return x**2 - 2 * x
def cintegre(double a, double b, int N):
cdef int i
cdef double s, dx
s = 0
dx = (b - a) / N
for i from 0 <= i < N:
s += cf(a + i*dx)
return s*dx
cintegre(0,2,2**20)
%timeit cintegre(0,2,2**20)
def f(x):
return x**2 - 2 * x
def integre(a, b, N):
s = 0
dx = (b - a) / N
for i in range(N):
s += f(a + i*dx)
return s*dx
integre(0.,2.,2**20)
%timeit integre(0.,2.,2**20)
417/4.76
def f(x):
return x**2 - 2 * x
def integre2(a, b, N):
dx = (b - a) / N
return dx * sum([f(a + i*dx) for i in range(N)])
%timeit integre2(0.,2.,2**20)
from functools import reduce
def f(x):
return x**2 - 2 * x
def integre3(a, b, N):
dx = (b - a) / N
return dx * reduce(lambda s,i : s + f(a + i*dx),range(N),0)
integre3(0.,2.,2**20)
%timeit integre3(0.,2.,2**20)