Book Image

NumPy Cookbook

Book Image

NumPy Cookbook

Overview of this book

Today's world of science and technology is all about speed and flexibility. When it comes to scientific computing, NumPy is on the top of the list. NumPy will give you both speed and high productivity. "NumPy Cookbook" will teach you all about NumPy, a leading scientific computing library. NumPy replaces a lot of the functionality of Matlab and Mathematica, but in contrast to those products, it is free and open source. "Numpy Cookbook" will teach you to write readable, efficient, and fast code that is as close to the language of Mathematics as much as possible with the cutting edge open source NumPy software library. You will learn about installing and using NumPy and related concepts. At the end of the book, we will explore related scientific computing projects. This book will give you a solid foundation in NumPy arrays and universal functions. You will also learn about plotting with Matplotlib and the related SciPy project through examples. "NumPy Cookbook" will help you to be productive with NumPy and write clean and fast code.
Table of Contents (17 chapters)
NumPy Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Profiling Cython code


We will profile Cython and NumPy code that tries to approximate the Euler constant. You can refer to http://en.wikipedia.org/wiki/E_%28mathematical_constant%29 for the required formula.

How to do it...

This section demonstrates how to profile Cython code. To do this, go through the following steps:

  • NumPy approximation of e: For the NumPy approximation of e perform the following steps:

    1. First, we will create an array of 1 to n (n is 40 in our example).

    2. Then, we will compute the cumulative product of this array, which happens to be the factorial.

    3. After that, we take the reciprocal of the factorials.

    4. Finally, we apply the formula from the Wikipedia page. At the end, we put standard profiling code, giving us the following program:

      import numpy
      import cProfile
      import pstats
      
      def approx_e(n=40):
         # array of [1, 2, ... n-1]
         arr = numpy.arange(1, n) 
      
         # calculate the factorials and convert to floats
         arr = arr.cumprod().astype(float)
      
         # reciprocal 1/n
         arr = numpy.reciprocal...