Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
NumPy Cookbook

You're reading from  NumPy Cookbook

Product type Book
Published in Oct 2012
Publisher Packt
ISBN-13 9781849518925
Pages 226 pages
Edition 1st Edition
Languages

Table of Contents (17) Chapters

NumPy Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Winding Along with IPython 2. Advanced Indexing and Array Concepts 3. Get to Grips with Commonly Used Functions 4. Connecting NumPy with the Rest of the World 5. Audio and Image Processing 6. Special Arrays and Universal Functions 7. Profiling and Debugging 8. Quality Assurance 9. Speed Up Code with Cython 10. Fun with Scikits 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...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}