A simple application with NumPy

Let’s assume we have two vectors, a and b, and we want to add them.

The vector a holds the squares of integers 0 to n. The vector b holds the cube of integers 0 to n. For example, if n = 3 then the vector a is equal to 0, 1, or 4; and the vector b is equal to 0, 1, or 8.

Let’s do it first with plain Python then with NumPy.

Create a new notebook and add the following code to it:

def pythonsum(n):	
	a = list(range(n))	
	b = list(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

pythonsum(3)

# output
[0, 2, 12]

Let’s do it now with NumPy:

import numpy

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

numpysum(3)

# output
array([ 0,  2, 12])

There you have it! With NumPy we don’t need a for loop, we used the arrange() function from NumPy that creates an array (with integers from 0 to n) for us, and it is faster.

The results are the same but Python outputs a Python list while the NumPy outputs a NumPy array.

Leave a Reply