Numpy Exercise 2

Imports


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

In [89]:
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 [90]:
def loop_fact(n):
    """Compute n! using a Python for loop."""
    if n==0:
        return 1
    y=n
    out=n
    while y>1:
        y=y-1
        out=out*y
    return(out)

In [91]:
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 [107]:
# YOUR CODE HERE
%timeit -n1 -r1 np_fact(10)
%timeit -n1 -r1 loop_fact(10)


1 loops, best of 1: 42.9 µs per loop
1 loops, best of 1: 20 µs per loop
1 loops, best of 1: 16 µs per loop
1 loops, best of 1: 16.9 µs per loop
1 loops, best of 1: 1.91 µs per loop
1 loops, best of 1: 1.91 µs per loop
1 loops, best of 1: 3.1 µs per loop
1 loops, best of 1: 2.86 µs per loop

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

YOUR ANSWER HERE


In [ ]:
# Using numpy is slower for small numbers but much faster for larger numbers
# I think this is because there is a certain baseline amount of work required
# to run numpy, but once that work has been done it is not much harder to perform
# a more complicated function. Whereas with loops the larger the function
# the more times it needs to run through

In [ ]: