We will profile Cython and NumPy code that tries to approximate the Euler constant with the following formula:
See http://en.wikipedia.org/wiki/E_%28mathematical_constant%29 for more background information.
This section demonstrates how to profile Cython code with the following steps:
For the NumPy approximation of e, follow these steps:
First, we will create an array of
1
ton
(n
is40
in our example).Then we will compute the cumulative product of this array, which happens to be the factorial. After that, we take the reciprocal of the factorials. Finally, we apply the formula from the Wikipedia page. At the end, we put the standard profiling code, giving us the following program:
from __future__ import print_function import numpy as np import cProfile import pstats def approx_e(n=40, display=False): # array of [1, 2, ... n-1] arr = np.arange(1, n) # calculate the factorials and convert to floats arr = arr.cumprod().astype(float) # reciprocal...