Skip to content
Home » numpy Part 12 – Operations with Scalars

numpy Part 12 – Operations with Scalars

Spread the love

Today we’ll be talking about numerical operations on numpy arrays with scalars.

Scalars are numbers like integers or floats as opposed to arrays. If we perform an operation on a scalar and an array, the operation is performed elementwise, so on each element of the array. For example, if we multiply a scalar and an array, the scalar is multiplied by each number in the array. The other operations work exactly the same.

scalars

Here are some examples:

Let’s create a list and turn it to a numpy array:

>>> import numpy as np
>>> nums = [2, 5, 8.5, 12.25, 20]
>>> n = np.array(nums)
>>> print(n)
[ 2.    5.    8.5  12.25 20.  ]

Let’s see how addition works:

>>> m = n + 10
>>> print(m)
[12.   15.   18.5  22.25 30.  ]

What about subtraction?

>>> k = n - 2
>>> print(k)
[ 0.    3.    6.5  10.25 18.  ]

As you probably expect, multiplication works exactly the same:

>>> n = n * 10
>>> print(n)
[ 20.   50.   85.  122.5 200. ]

And so does division, both true division:

>>> p = n / 5
>>> print(p)
[ 4.  10.  17.  24.5 40. ]

and floor division:

>>> r = p // 4
>>> print(r)
[ 1.  2.  4.  6. 10.]

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Here’s an example with exponentiation:

>>> s = n ** 3
>>> print(s)
[   8000.     125000.     614125.    1838265.625 8000000.   ]

and one more with modulus:

>>> t = s % 100
>>> print(t)
[ 0.     0.    25.    65.625  0.   ]

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

And here’s a slightly more complex example with a multidimensional array and two operations, multiplication and addition:

>>> x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> print(x)
[[1 2 3]
 [4 5 6]
 [7 8 9]]
>>> y = 5 * x + 1
>>> print(y)
[[ 6 11 16]
 [21 26 31]
 [36 41 46]]

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love

Leave a Reply