Book Image

NumPy Cookbook - Second Edition

By : Ivan Idris
Book Image

NumPy Cookbook - Second Edition

By: Ivan Idris

Overview of this book

<p>NumPy has the ability to give you speed and high productivity. High performance calculations can be done easily with clean and efficient code, and it allows you to execute complex algebraic and mathematical computations in no time.</p> <p>This book will give you a solid foundation in NumPy arrays and universal functions. Starting with the installation and configuration of IPython, you'll learn about advanced indexing and array concepts along with commonly used yet effective functions. You will then cover practical concepts such as image processing, special arrays, and universal functions. You will also learn about plotting with Matplotlib and the related SciPy project with the help of examples. At the end of the book, you will study how to explore atmospheric pressure and its related techniques. By the time you finish this book, you'll be able to write clean and fast code with NumPy.</p>
Table of Contents (19 chapters)
NumPy Cookbook Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Profiling the Cython code


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.

How to do it...

This section demonstrates how to profile Cython code with the following steps:

  1. For the NumPy approximation of e, follow these steps:

    • First, we will create an array of 1 to n (n is 40 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...