## Time for action – adding vectors

Imagine that we want to add two vectors called `a` and `b` (see https://www.khanacademy.org/science/physics/one-dimensional-motion/displacement-velocity-time/v/introduction-to-vectors-and-scalars). Vector is used here in the mathematical sense meaning a one-dimensional array. We will learn in Chapter 5, Working with Matrices and ufuncs, about specialized NumPy arrays, which represent matrices. Vector `a` holds the squares of integers `0` to n, for instance, if `n` is equal to `3`, then a is equal to `(0,1, 4)`. Vector `b` holds the cubes of integers `0` to n, so if `n` is equal to `3`, then `b` is equal to `(0,1, 8)`. How will you do that using plain Python? After we come up with a solution, we will compare it to the NumPy equivalent.

1. Adding vectors using pure Python: The following function solves the vector addition problem using pure Python without NumPy:

```def pythonsum(n):
a = range(n)
b = range(n)
c = []

for i in range(len(a)):
a[i] = i ** 2
b[i] = i ** 3
c.append(a[i] + b[i])

return c```

### Tip

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

2. Adding vectors using NumPy: Following is a function that achieves the same result with NumPy:

```def numpysum(n):
a = np.arange(n) ** 2
b = np.arange(n) ** 3
c = a + b

return c```

Notice that `numpysum()` does not need a `for` loop. Also, we used the `arange()` function from NumPy that creates a NumPy array for us with integers `0` to n. The `arange()` function was imported; that is why it is prefixed with `numpy` (actually, it is customary to abbreviate it via an alias to `np`).

Now comes the fun part. The preface mentions that NumPy is faster when it comes to array operations. How much faster is NumPy, though? The following program will show us by measuring the elapsed time, in microseconds, for the `numpysum()` and `pythonsum()` functions. It also prints the last two elements of the vector sum. Let's check that we get the same answers by using Python and NumPy:

```#!/usr/bin/env/python

from __future__ import print_function
import sys
from datetime import datetime
import numpy as np

"""
Chapter 1 of NumPy Beginners Guide.
This program demonstrates vector addition the Python way.
Run from the command line as follows

python vectorsum.py n

where n is an integer that specifies the size of the vectors.

The first vector to be added contains the squares of 0 up to n.
The second vector contains the cubes of 0 up to n.
The program prints the last 2 elements of the sum and the elapsed time.
"""

def numpysum(n):
a = np.arange(n) ** 2
b = np.arange(n) ** 3
c = a + b

return c

def pythonsum(n):
a = range(n)
b = range(n)
c = []

for i in range(len(a)):
a[i] = i ** 2
b[i] = i ** 3
c.append(a[i] + b[i])

return c

size = int(sys.argv[1])

start = datetime.now()
c = pythonsum(size)
delta = datetime.now() - start
print("The last 2 elements of the sum", c[-2:])
print("PythonSum elapsed time in microseconds", delta.microseconds)

start = datetime.now()
c = numpysum(size)
delta = datetime.now() - start
print("The last 2 elements of the sum", c[-2:])
print("NumPySum elapsed time in microseconds", delta.microseconds)```

The output of the program for `1000`, `2000`, and `3000` vector elements is as follows:

```\$ python vectorsum.py 1000
The last 2 elements of the sum [995007996, 998001000]
PythonSum elapsed time in microseconds 707
The last 2 elements of the sum [995007996 998001000]
NumPySum elapsed time in microseconds 171
\$ python vectorsum.py 2000
The last 2 elements of the sum [7980015996, 7992002000]
PythonSum elapsed time in microseconds 1420
The last 2 elements of the sum [7980015996 7992002000]
NumPySum elapsed time in microseconds 168
\$ python vectorsum.py 4000
The last 2 elements of the sum [63920031996, 63968004000]
PythonSum elapsed time in microseconds 2829
The last 2 elements of the sum [63920031996 63968004000]
NumPySum elapsed time in microseconds 274
```

### What just happened?

Clearly, NumPy is much faster than the equivalent normal Python code. One thing is certain, we get the same results whether we use NumPy or not. However, the result printed differs in representation. Notice that the result from the `numpysum()` function does not have any commas. How come? Obviously, we are not dealing with a Python list but with a NumPy array. It was mentioned in the Preface that NumPy arrays are specialized data structures for numerical data. We will learn more about NumPy arrays in the next chapter.

### Pop quiz – Functioning of the arange() function

Q1. What does `arange(5)` do?

1. Creates a Python list of 5 elements with the values 1-5.

2. Creates a Python list of 5 elements with the values 0-4.

3. Creates a NumPy array with the values 1-5.

4. Creates a NumPy array with the values 0-4.

5. None of the above.

### Have a go hero – continue the analysis

The program we used to compare the speed of NumPy and regular Python is not very scientific. We should at least repeat each measurement a couple of times. It will be nice to be able to calculate some statistics such as average times. Also, you might want to show plots of the measurements to friends and colleagues.

### Tip

Hints to help can be found in the online documentation and the resources listed at the end of this chapter. NumPy has statistical functions that can calculate averages for you. I recommend using matplotlib to produce plots. Chapter 9, Plotting with matplotlib, gives a quick overview of matplotlib.