Numpy Exercise 2

Imports


In [36]:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns

Factorial

Write a function that computes the factorial of small numbers using np.arange and np.cumprod.


In [1]:
def np_fact(n):
    """Compute n! = n*(n-1)*...*1 using Numpy."""
    f=np.arange(1,n+1,1) #forms a 1d array going from 1 to n
    F=np.cumprod(f)      #forms array that has cummulitive products
    if n==0:
        return 1
    else:
        return max(F)   #gives the max (last) number which is the factorial

In [38]:
assert np_fact(0)==1
assert np_fact(1)==1
assert np_fact(10)==3628800
assert [np_fact(i) for i in range(0,11)]==[1,1,2,6,24,120,720,5040,40320,362880,3628800]

Write a function that computes the factorial of small numbers using a Python loop.


In [31]:
def loop_fact(n):
    """Compute n! using a Python for loop."""
    F=1                    #defines variable set F to 1
    for f in range(1,n+1): 
        F=F*f             #continuously multiplies from 1 to n
    return F

raise NotImplementedError()


1
---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-31-3dbb0c5f0618> in <module>()
      6     return F
      7 print loop_fact(0)
----> 8 raise NotImplementedError()

NotImplementedError: 

In [ ]:
assert loop_fact(0)==1
assert loop_fact(1)==1
assert loop_fact(10)==3628800
assert [loop_fact(i) for i in range(0,11)]==[1,1,2,6,24,120,720,5040,40320,362880,3628800]

Use the %timeit magic to time both versions of this function for an argument of 50. The syntax for %timeit is:

%timeit -n1 -r1 function_to_time()

In [46]:
%timeit -n1 -r1 np_fact(50)
%timeit -n1 -r1 loop_fact(50)
raise NotImplementedError()


1 loops, best of 1: 64.1 µs per loop
1 loops, best of 1: 13.1 µs per loop
---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-46-fa1064bab8d9> in <module>()
      1 get_ipython().magic(u'timeit -n1 -r1 np_fact(50)')
      2 get_ipython().magic(u'timeit -n1 -r1 loop_fact(50)')
----> 3 raise NotImplementedError()

NotImplementedError: 

In the cell below, summarize your timing tests. Which version is faster? Why do you think that version is faster?

YOUR ANSWER HERE The np_fact took 63.2 microseconds to run and the loop_fact took 13.8 microseconds for one loop. The loop_fact was significantly faster, usually 2-4 times faster. I think that this version is faster because it only uses functions that are built in to python while np_fact uses two functions that need to be imported into python in order for it to work.