Numpy Exercise 2

Imports


In [1]:
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 [3]:
def np_fact(n):
    """Compute n! = n*(n-1)*...*1 using Numpy."""
    if n==0:
        return 1
    vals = np.arange(1,n+1,1)
    fact = vals.cumprod()
    return fact[-1]
np_fact(3)


Out[3]:
6

In [4]:
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 [15]:
def loop_fact(n):
    """Compute n! using a Python for loop."""
    fact = 1
    for i in range(1,n+1):
        fact=fact*i
    return fact
loop_fact(5)


Out[15]:
120

In [16]:
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 [20]:
%timeit -nint(1.0)


The slowest run took 23.65 times longer than the fastest. This could mean that an intermediate result is being cached 
10000000 loops, best of 3: 121 ns per loop

In [ ]:
%timeit -n1 -r1 np_fact(1000000)
%timeit -n1 -r1 loop_fact(1000000)

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

The loop runs quicker at low n but given a really big n, numpy beats out the loop by a ton.