Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 3. Get into Terms with Commonly ... > Time for action calculating the fact...

Time for action calculating the factorial

The ndarray has the prod method, which computes the product of the elements in an array.

  1. Call the prod function: Calculate the factorial of eight. To do that, generate an array with values 1 to 8 and call the prod function on it:

    b = numpy.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. Call cumprod: 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]
    

  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial