Numpy Exercise 2

Imports


In [41]:
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 [16]:
np.arange(1+1)


Out[16]:
array([0, 1])

In [23]:
def np_fact(n):
    """Compute n! = n*(n-1)*...*1 using Numpy."""
    
    x = np.arange(n) + 1
    y = np.cumprod(x)
    if n == 0:
        return 1
    else:
        return(y[n-1])
print(np_fact(55))


6711489344688881664

In [42]:
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 [43]:
def loop_fact(n):
    """Compute n! using a Python for loop."""
    if n == 0:
        return 1
    else:
        total = 1
        for i in range(n):
            if n > i:
                total = total*(n-i)
            else:
                total = total
        return(total)
            
loop_fact(4)


Out[43]:
24

In [44]:
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 [54]:
%timeit -n1 -r1 np_fact(100)


1 loops, best of 1: 59.1 µs per loop

In [56]:
%timeit -n1 -r1 loop_fact(100)


1 loops, best of 1: 47.9 µs per loop

In [ ]:
"""When I run the tests, my loop version of the factorial seems to 
take about half the time of the np version, which actually was
quite surprsing as I thought the np functions were known for 
efficiency. I assume the explanation may lie in that for something
like determing a factorial, the mathematical iterations necessary to 
do so are most easily done in bare bones coding with loops (at leadt for
small numbers)"""

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

YOUR ANSWER HERE

"""When I run the tests, my loop version of the factorial seems to take about half the time of the np version, which actually was quite surprsing as I thought the np functions were known for efficiency. I assume the explanation may lie in that for something like determing a factorial, the mathematical iterations necessary to do so are most easily done in bare bones coding with loops (at leadt for small numbers)""