Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

Time for action – calculating the factorial


The ndarray class has the prod() method, which computes the product of the elements in an array. Perform the following steps to calculate the factorial:

  1. Calculate the factorial of 8. To do this, generate an array with values 1 to 8 and call the prod() function on it:

    b = np.arange(1, 9)
    print("b =", b)
    print("Factorial", b.prod())

    Check the result with your pocket calculator:

    b = [1 2 3 4 5 6 7 8]
    Factorial 40320
    

    This is nice, but what if we want to know all the factorials from 1 to 8?

  2. No problem! Call the cumprod() method, which computes the cumulative product of an array:

    print("Factorials", b.cumprod())

    It's pocket calculator time again:

    Factorials [    1     2     6    24   120   720  5040 40320]
    

What just happened?

We used the prod() and cumprod() functions to calculate factorials (see ndarraymethods.py):

from __future__ import print_function
import numpy as np

a = np.arange(5)
print("a =", a)
print("Clipped", a.clip(1, 2))

a = np.arange(4)
print...