Skip main navigation

Arithmetics and elementary functions

In this article we show how to do simple numerical operations with arrays.
© CC-BY-NC-SA 4.0 by CSC - IT Center for Science Ltd.

Element-wise operations

Simple calculations are very straightforward with NumPy arrays.

Basic arithmetic operations (+ - * / **) can all be used with arrays. The main
thing to keep in mind is that most operations are done element-wise.

a = numpy.array([1.0, 2.0, 3.0])
b = 2.0

print(a * b)
# output: [ 2. 4. 6.]

print(a + b)
# output: [ 3. 4. 5.]

print(a * a)
# output: [ 1. 4. 9.]

Elementary functions

NumPy provides also a wide range of elementary mathematical functions (sin,
cos, exp, sqrt, log, …) that work with arrays (as well as single values). In
many ways NumPy can be used as a drop-in replacement for the math module.

import numpy, math
a = numpy.linspace(-math.pi, math.pi, 8)

# output:
# [-3.14159265 -2.24399475 -1.34639685 -0.44879895 0.44879895 1.34639685
# 2.24399475 3.14159265]

# output:
# [ -1.22464680e-16 -7.81831482e-01 -9.74927912e-01 -4.33883739e-01
# 4.33883739e-01 9.74927912e-01 7.81831482e-01 1.22464680e-16]

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: only length-1 arrays can be converted to Python scalars
© CC-BY-NC-SA 4.0 by CSC - IT Center for Science Ltd.
This article is from the free online

Python in High Performance Computing

Created by
FutureLearn - Learning For Life

Our purpose is to transform access to education.

We offer a diverse selection of courses from leading universities and cultural institutions from around the world. These are delivered one step at a time, and are accessible on mobile, tablet and desktop, so you can fit learning around your life.

We believe learning should be an enjoyable, social experience, so our courses offer the opportunity to discuss what you’re learning with others as you go, helping you make fresh discoveries and form new ideas.
You can unlock new opportunities with unlimited access to hundreds of online short courses for a year by subscribing to our Unlimited package. Build your knowledge with top universities and organisations.

Learn more about how FutureLearn is transforming access to education