<jupyter_start><jupyter_text>Matrices: Numpy 1  [Download exercises zip](../_static/generated/matrices-numpy.zip)[Browse files online](https://github.com/DavidLeoni/softpython-en/tree/master/matrices-numpy) IntroductionPreviously we've seen [Matrices as lists of lists](https://en.softpython.org/matrices-lists/matrices-lists-sol.html), here we focus on matrices using Numpy libraryThere are substantially two ways to represent matrices in Python: as list of lists, or with the external library [numpy](https://www.numpy.org). The most used is surely Numpy, let's see the reason the principal differences:List of lists - [see separate notebook](https://en.softpython.org/matrices-lists/matrices-lists1-sol.html)1. native in Python2. not efficient3. lists are pervasive in Python, probably you will encounter matrices expressed as list of lists anyway4. give an idea of how to build a nested data structure5. may help in understanding important concepts like pointers to memory and copies Numpy - this notebook1. not natively available  in Python2. efficient3. many libraries for scientific calculations are based on Numpy (scipy, pandas)4. syntax to access elements is slightly different from list of lists5. in rare cases might give problems of installation and/or conflicts (implementation is not pure Python) Here we will see data types and essential commands of [Numpy library](https://www.numpy.org), but we will not get into the details.The idea is to simply pass using the the data format `ndarray` without caring too much about performances: for example, even if `for` cycles in Python are slow because they operate cell by cell, we will use them anyway. In case you actually need to execute calculations fast, you will want to use operators on vectors but for this we invite you to read links below **ATTENTION**: Numpy does not work in [Python Tutor](http://www.pythontutor.com/visualize.htmlmode=edit)      What to do- unzip exercises in a folder, you should get something like this: ```matrices-numpy    matrices-numpy1.ipynb    matrices-numpy1-sol.ipynb    matrices-numpy2.ipynb    matrices-numpy2-sol.ipynb    matrices-numpy3-chal.ipynb    numpy-images.ipynb    numpy-images-sol.ipynb        jupman.py```**WARNING**: to correctly visualize the notebook, it MUST be in an unzipped folder !- open Jupyter Notebook from that folder. Two things should open, first a console and then browser. The browser should show a file list: navigate the list and open the notebook `matrices-numpy/matrices-numpy1.ipynb`- Go on reading that notebook, and follow instuctions inside.Shortcut keys:- to execute Python code inside a Jupyter cell, press `Control + Enter`- to execute Python code inside a Jupyter cell AND select next cell, press `Shift + Enter`- to execute Python code inside a Jupyter cell AND a create a new cell aftwerwards, press `Alt + Enter`- If the notebooks look stuck, try to select `Kernel -> Restart`  np.arrayFirst of all, we import the library, and for convenience we rename it to `np`<jupyter_code>import numpy as np<jupyter_output><empty_output><jupyter_text>With lists of lists we have often built the matrices one row at a time, adding lists as needed. In Numpy instead we usually create in one shot the whole matrix, filling it with zeroes.In particular, this command creates an `ndarray` filled with zeroes:<jupyter_code>mat = np.zeros( (2,3)  )   # 2 rows, 3 columns
mat<jupyter_output><empty_output><jupyter_text>Note like inside `array( )` the content seems represented like a list of lists, BUT in reality in physical memory the data is structured in a linear sequence which allows Python to access numbers in a faster way. We can also create an `ndarray` from a list of lists:<jupyter_code>mat = np.array( [ [5.0,8.0,1.0], 
                  [4.0,3.0,2.0]])
mat
type(mat)<jupyter_output><empty_output><jupyter_text>Creating a matrix filled with ones<jupyter_code>np.ones((3,5))  # 3 rows, 5 columns<jupyter_output><empty_output><jupyter_text>Creating a matrix filled with a number `k`<jupyter_code>np.full((3,5), 7)<jupyter_output><empty_output><jupyter_text>Dimensions of a matrixTo obtain the dimension, we write like the following:    **ATTENTION**: after `shape` there are **no** round parenthesis !`shape` is an attribute, not a function to call<jupyter_code>mat = np.array( [ [5.0,8.0,1.0], 
                  [4.0,3.0,2.0]])

mat.shape<jupyter_output><empty_output><jupyter_text>If we want to memorize the dimension in separate variables, we can use thi more pythonic mode (note the comma between `num_rows` and `num_cols`:<jupyter_code>num_rows, num_cols = mat.shape
num_rows
num_cols<jupyter_output><empty_output><jupyter_text>Reading and writingTo access data or overwrite square bracket notation is used, with the important difference that in Numpy you can write _both_ the indeces _inside_ the same brackets, separated by a comma:**ATTENTION**: notation `mat[i,j]` is only for Numpy, with list of lists **does not** work!<jupyter_code>mat = np.array( [ [5.0,8.0,1.0], 
                  [4.0,3.0,2.0]])

# Let's put number `9` in cell at row `0` and column `1`

mat[0,1] = 9
mat<jupyter_output><empty_output><jupyter_text>Let's access cell at row `0` and column `1`<jupyter_code>mat[0,1]<jupyter_output><empty_output><jupyter_text>We put number `7` into cell at row `1` and column `2`<jupyter_code>mat[1,2] = 7
mat<jupyter_output><empty_output><jupyter_text>**✪ EXERCISE**: try to write like the following, what happens? ```pythonmat[0,0] = "c"```<jupyter_code># write here<jupyter_output><empty_output><jupyter_text>**✪ EXERCISE**: Try writing like this, what happens?    ```pythonmat[1,1.0]```<jupyter_code># write here<jupyter_output><empty_output><jupyter_text>Filling the whole matrixWe can MODIFY the matrix by writing inside a number with  `fill()`<jupyter_code>mat = np.array([[3.0, 5.0, 2.0],
                [6.0, 2.0, 9.0]])

mat.fill(7)  # NOTE: returns nothings !!
mat<jupyter_output><empty_output><jupyter_text>SlicesTo extract data from an `ndarray` we can use slices, with the notation we already used for regular lists. There are important difference, though. Let's see them.The first difference is that we can extract sub-matrices by specifying two ranges among the same squared brackets:<jupyter_code>mat = np.array( [ [5, 8, 1], 
                  [4, 3, 2],
                  [6, 7, 9],
                  [9, 3, 4],
                  [8, 2, 7]])
mat[0:4, 1:3]  # rows from 0 *included* to 4 *excluded*
               # and columns from 1 *included* to 3 *excluded*
               
mat[0:1,0:3]  # the whole first row
mat[0:1,:]  # another way to extract the whole first row
mat[0:5, 0:1]  # the whole first column
mat[:, 0:1]  # another way to extract the whole first column<jupyter_output><empty_output><jupyter_text>**The step**: We can also specify a step as a third paramter after the `:`. For example, to extract only even rows we can add a `2` like this:<jupyter_code>mat[0:5:2, :]<jupyter_output><empty_output><jupyter_text>**WARNING: by modifying the numpy slice you also modify the original matrix!**   Differently from slices of lists which always produce new lists, this time of performance reasons with numpy slices we only obtain a _view_ on the original data: by writing into the view we will also write on the original matrix:<jupyter_code>mat = np.array( [ [5, 8, 1], 
                  [4, 3, 2],
                  [6, 7, 9],
                  [9, 3, 4],
                  [8, 2, 7]])
sub_mat = mat[0:4, 1:3]  
sub_mat
sub_mat[0,0] = 999
mat<jupyter_output><empty_output><jupyter_text>Writing a constant in a sliceWe can also write a constant in all the cells of a region by identifying the region with a slice, and assigning a constant to it:<jupyter_code>mat = np.array( [ [5, 8, 1], 
                  [4, 3, 2],
                  [6, 7, 9],
                  [9, 3, 4],
                  [8, 2, 5]])

mat[0:4, 1:3]  = 7

mat<jupyter_output><empty_output><jupyter_text>Writing a matrix into a sliceWe can also write into all the cells in a region by identifying the region with a slice, and then assigning to it a matrix from which we want to read the cells.**WARNING**: To avoid problems, **double check** you're using the same dimensions in both left and right slices!<jupyter_code>mat = np.array( [ [5, 8, 1], 
                  [4, 3, 2],
                  [6, 7, 9],
                  [9, 3, 4],
                  [8, 2, 5]])

mat[0:4, 1:3]  = np.array([
                            [10,50],
                            [11,51],
                            [12,52],
                            [13,53],
                        ])

mat<jupyter_output><empty_output><jupyter_text>Assignment and copyWith Numpy we must take particular care when using the assignment operator `=`: as with regular lists, if we perform an assignment into the new variable, it will only contain a pointer to the original region of memory.<jupyter_code>va = np.array([1,2,3])
va
vb = va
vb[0] = 100
vb
va<jupyter_output><empty_output><jupyter_text>If we wanted a complete copy of the array, we should use the `.copy()` method:<jupyter_code>va = np.array([1,2,3])
vc = va.copy()
vc
vc[0] = 100
vc
va<jupyter_output><empty_output><jupyter_text>CalculationsNumpy is extremely flexible, and allows us to perform on arrays almost the same operations from classical vector and matrix algebra:<jupyter_code>va = np.array([5,9,7]) 
va
vb = np.array([6,8,0]) 
vb<jupyter_output><empty_output><jupyter_text>Whenever we perform an algebraic operation, typically a NEW array is created:<jupyter_code>vc = va + vb   
vc<jupyter_output><empty_output><jupyter_text>Note the sum didn't change the input:<jupyter_code>va
vb<jupyter_output><empty_output><jupyter_text>Scalar multiplication<jupyter_code>m = np.array([[5, 9, 7],
              [6, 8, 0]])
3 * m<jupyter_output><empty_output><jupyter_text>Scalar sum<jupyter_code>3 + m<jupyter_output><empty_output><jupyter_text>MultiplicationBe careful about multiplying with `*`: differently from classical matrix multiplication, it multiplies _element by element_ and so requires matrices of identical dimensions:<jupyter_code>ma = np.array([[1,  2,  3],
               [10, 20, 30]])

mb = np.array([[1,  0,  1],
               [4,  5,  6]]) 

ma * mb<jupyter_output><empty_output><jupyter_text>If we want the matrix multiplication [from classical algebra](https://en.wikipedia.org/wiki/Matrix_multiplication), we must use the `@` operator taking care of having compatible matrix dimensions:<jupyter_code>mc = np.array([[1,  2,  3],
               [10, 20, 30]])
md = np.array([[1, 4],
               [0, 5],
               [1, 6]]) 

mc @ md<jupyter_output><empty_output><jupyter_text>Dividing by a scalar<jupyter_code>ma = np.array([[1,  2,  0.0],
               [10, 0.0, 30]])

ma / 4<jupyter_output><empty_output><jupyter_text>Careful about dividing by `0.0`, the program execution will still continue with a warning and we will find a matrix with strange `nan` and `inf` which have a bad tendency to create problems later - see the section [NaNs and infinities](NaNs-and-infinities)<jupyter_code>print(ma / 0.0)
print("AFTER")<jupyter_output>[[inf inf nan]
 [inf nan inf]]
AFTER<jupyter_text>AggregationNumpy provides several functions to calculate statistics, we only show some:<jupyter_code>m = np.array([[5, 4, 6],
              [3, 7, 1]])
np.sum(m)
np.max(m)   
np.min(m)<jupyter_output><empty_output><jupyter_text>Aggregating by row or column By adding the `axis` parameter we can tell numpy to perform the affrefation on each column (`axis=0`) or row (`axis=1`):<jupyter_code>np.max(m, axis=0)  # the maximum of each column
np.sum(m, axis=0)   # sum each column
np.max(m, axis=1)  # the maximum of each row
np.sum(m, axis=1)   # sum each row<jupyter_output><empty_output><jupyter_text>FilteringNumpy offers a mini-language to filter the numbers in an array, by specifying the selection criteria. Let's see an example:<jupyter_code>mat = np.array([[5, 2, 6],
                [1, 4, 3]])
mat<jupyter_output><empty_output><jupyter_text>Suppose you want to obtain an array with all the numbers from `mat` which are greater than 2.We can tell numpy the matrix `mat` we want to use, then _inside square brackets_ we put a kind of boolean conditions, _reusing_ the `mat` variable like so:<jupyter_code>mat[ mat > 2 ]<jupyter_output><empty_output><jupyter_text>Exactly, what is that strange expression we put inside the squared brackts? Let's try executing it alone:<jupyter_code>mat > 2<jupyter_output><empty_output><jupyter_text>We note it gives us a matrix of booleans, which are `True` whenever the corresponding cell in the original matrix satisfies the condition we imposed.By then placing this expression inside `mat[   ]` we obtain the values from the original matrix which satisfy the expression:<jupyter_code>mat[ mat > 2 ]<jupyter_output><empty_output><jupyter_text>Not only that, we can also build more complex expressions by using * `&` symbol as the logical conjunction _and_* `|` (pipe character) as the logical conjunction _or_<jupyter_code>mat = np.array([[5, 2, 6],
                [1, 4, 3]])
mat[(mat > 3) & (mat < 6)]
mat = np.array([[5, 2, 6],
                [1, 4, 3]])
mat[(mat < 2) | (mat > 4)]<jupyter_output><empty_output><jupyter_text>**WARNING: REMEMBER THE ROUND PARENTHESIS AMONG THE VARIOUS EXPRESSIONS!**   **EXERCISE**: try to rewrite the expressions above by 'forgetting' the round parenthesis in the various components (left/right/both) and see what happens. Do you obtain errors or unexpected results?<jupyter_code>#jupman-purge-output
mat = np.array([[5, 2, 6],
                [1, 4, 3]])

# write here
print(  mat[(mat > 3) & mat < 6]  )
print(  mat[mat > 3 & (mat < 6)]    )
#print(  mat[mat > 3 & mat < 6]      )
# the last one produces:
# ---------------------------------------------------------------------------
# ValueError                                Traceback (most recent call last)
# <ipython-input-212-33c5a083b265> in <module>
#       3 print(  mat[(mat > 3) & mat < 6]  )
#       4 print(  mat[mat > 3 & (mat < 6)]    )
# ----> 5 print(  mat[mat > 3 & mat < 6]      )

# ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()<jupyter_output>[5 2 6 1 4 3]
[5 2 6 4 3]<jupyter_text>**WARNING**:  `and` **and** `or` **DON'T WORK!** **EXERCISE**: try rewriting the expressions above by substituting `&` with `and` and `|` with `or` and see what happens. Do you get errors or unexpected results?<jupyter_code>mat = np.array([[5, 2, 6],
                [1, 4, 3]])

# write here
#print(  mat[(mat > 3) and (mat < 6) ]  )
#---------------------------------------------------------------------------
#ValueError                                Traceback (most recent call last)
#<ipython-input-218-3edf025af7c0> in <module>
#      4 
#      5 # write here
#----> 6 print(  mat[(mat > 3) and (mat < 6) ]  )     

#ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

#print(  mat[(mat > 3) or (mat < 6)]    )
#---------------------------------------------------------------------------
#ValueError                                Traceback (most recent call last)
#<ipython-input-219-192c022d9d87> in <module>
#     16 
#     17 
#---> 18 print(  mat[(mat > 3) or (mat < 6)]    )

#ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()<jupyter_output><empty_output><jupyter_text>Finding indexes with  `np.where`We've seen how to find the content of cells which satisfy a certain criteria.   What if we wanted to find the _indeces_ of those cells? In that case we would use the function `np.where`, passing as parameter the condition expressed in the same language used before. For example, if we wanted to find the _indexes_ of cells containing numbers less than 40 or greater than 60 we would write like so:<jupyter_code>#0  1  2  3  4  5
v = np.array([30,60,20,70,40,80])

np.where((v < 40) | (v > 60))<jupyter_output><empty_output><jupyter_text>Writing into cells which satisfy a criteriaWe can use `np.where` to substitute values in the cells which satisfy a criteria with other values which we'll be expressed in two extra matrices `ma` and `mb`. In case the criteria is satisfied, numpy will take the corresponding values from `ma`, otherwise from `mb`.<jupyter_code>ma = np.array([
    [ 1, 2, 3, 4],
    [ 5, 6, 7, 8],
    [ 9,10,11,12]
])

mb = np.array([
    [ -1, -2, -3, -4],
    [ -5, -6, -7, -8],
    [ -9,-10,-11,-12]
])


mat = np.array([
    [40,70,10,80],
    [20,30,60,40],
    [10,60,80,90]
])

np.where(mat < 50, ma, mb)<jupyter_output><empty_output><jupyter_text>arange and linspace sequencesThe standard function `range` of Python does not allow for float increments, which we can instead obtain by building sequences of float numbers with `np.arange`, by specifying left limit (**included**), right limit (**excluded**) and the increment:<jupyter_code>np.arange(0.0, 1.0, 0.2)<jupyter_output><empty_output><jupyter_text>Alternatively, we can use `np.linspace`, which takes a left limit **included**, a right limit this time **included**, and the **number of repetitions** to subdivide this space:<jupyter_code>np.linspace(0, 0.8, 5)
np.linspace(0, 0.8, 10)<jupyter_output><empty_output><jupyter_text>NaNs and infinitiesFloat numbers can be numbers and.... not numbers, and infinities. Sometimes during calculations extremal conditions may arise, like when dividing a small number by a huge number. In such cases, you might end up having a float which is a dreaded _Not a Number_, _NaN_ for short, or you might get an infinity. This can lead to very awful unexpected behaviours, so you must be well aware of it. Following behaviours are dictated by IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754) which Numpy uses and is implemented in all CPUs, so they actually  regard all programming languages.   NaNsA NaN is _Not a Number_. Which is already a silly name, since a NaN is actually a very special member of floats, with this astonishing property: **WARNING: NaN IS NOT EQUAL TO ITSELF** !!!! Yes you read it right, NaN is really _not_ equal to itself.Even if your mind wants to refuse it, we are going to confirm it.To get a NaN, you can use Python module `math` which holds this alien item:<jupyter_code>import math
math.nan    # notice it prints as 'nan' with lowercase n<jupyter_output><empty_output><jupyter_text>As we said, a NaN is actually considered a float:<jupyter_code>type(math.nan)<jupyter_output><empty_output><jupyter_text>Still, it behaves very differently from its fellow floats, or any other object in the known universe:<jupyter_code>math.nan == math.nan   # what the F... alse<jupyter_output><empty_output><jupyter_text>Detecting NaNGiven the above, if you want to check if a variable `x` is a NaN, you _cannot_ write this:<jupyter_code>x = math.nan
if x == math.nan:  # WRONG
    print("I'm NaN ")
else:
    print("x is something else ??")<jupyter_output>x is something else ??<jupyter_text>To correctly handle this situation, you need to use `math.isnan` function:<jupyter_code>x = math.nan
if math.isnan(x):  # CORRECT
    print("x is NaN ")
else:
    print("x is something else ??")<jupyter_output>x is NaN<jupyter_text>Notice `math.isnan` also work with _negative_ NaN:<jupyter_code>y = -math.nan
if math.isnan(y):  # CORRECT
    print("y is NaN ")
else:
    print("y is something else ??")<jupyter_output>y is NaN<jupyter_text>Sequences with NaNsStill, not everything is completely crazy. If you compare a sequence holding NaNs to another one, you will get reasonable results:<jupyter_code>[math.nan, math.nan] == [math.nan, math.nan]<jupyter_output><empty_output><jupyter_text>Exercise NaN: two varsGiven two number variables `x` and `y`, write some code that prints `"same"` when they are the same, _even_ when they are NaN. Otherwise, prints `"not the same"<jupyter_code># expected output: same
x = math.nan
y = math.nan

# expected output: not the same
#x = 3
#y = math.nan

# expected output: not the same
#x = math.nan
#y = 5

# expected output: not the same
#x = 2
#y = 7

# expected output: same
#x = 4
#y = 4

# write here
if math.isnan(x) and math.isnan(y):
    print('same')
elif x == y:
    print('same')
else:
    print('not the same')<jupyter_output>same<jupyter_text>Operations on NaNsAny operation on a NaN will generate another NaN:<jupyter_code>5 * math.nan
math.nan + math.nan
math.nan / math.nan<jupyter_output><empty_output><jupyter_text>The only thing you cannot do is dividing by zero with an unboxed NaN: ```pythonmath.nan / 0``````python---------------------------------------------------------------------------ZeroDivisionError                         Traceback (most recent call last) in ----> 1 math.nan / 0ZeroDivisionError: float division by zero``` NaN corresponds to boolean value `True`:<jupyter_code>if math.nan: 
    print("That's True")<jupyter_output>That's True<jupyter_text>NaN and NumpyWhen using Numpy you are quite likely to encounter NaNs, so much so they get redefined inside Numpy, but they are exactly the same as in `math` module:<jupyter_code>np.nan
math.isnan(np.nan)
np.isnan(math.nan)<jupyter_output><empty_output><jupyter_text>In Numpy when you have unknown numbers you might be tempted to put a `None`. You can actually do it, but look closely at the result:<jupyter_code>import numpy as np
np.array([4.9,None,3.2,5.1])<jupyter_output><empty_output><jupyter_text>The resulting array type is _not_  an array of float64 which allows fast calculations, instead it is an array containing generic _objects_, as Numpy is assuming the array holds heterogenous data. So what you gain in generality you lose it in performance, which should actually be the whole point of using Numpy. Despite being weird, NaNs are actually regular float citizen so they can be stored in the array:<jupyter_code>np.array([4.9,np.nan,3.2,5.1])   # Notice how the `dtype=object` has disappeared<jupyter_output><empty_output><jupyter_text>Where are the NaNs ?Let's try to see where we can spot NaNs and other weird things such infinities in the wild First, let check what happens when we call function `log` of standard module `math`.As we know, log function behaves like this:* $x < 0$: not defined * $x = 0$: tends to minus infinity * $x > 0$: defined![log function u9u9u9](_static/img/log.png)So we might wonder what happens when we pass to it a value where it is not defined. Let's first try with the standard `math.log`  from Python library: ```python>>> math.log(-1)``````pythonValueError                                Traceback (most recent call last) in ----> 1 math.log(-1)ValueError: math domain error``` In this case `ValueError` is raised and **the execution gets interrupted.**Let's try the equivalent with Numpy:<jupyter_code>np.log(-1)<jupyter_output>/home/da/.local/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in log
  """Entry point for launching an IPython kernel.<jupyter_text>In this case we **actually got as a result** `np.nan`, so execution was not interrupted, Jupyter only informed us with an extra print that something dangerous happened.The default behaviour of Numpy regarding dangerous calculations is to perform them anyway and storing the result in as a NaN or other limit objects. This also works for arrays calculations:<jupyter_code>np.log(np.array([3,7,-1,9]))<jupyter_output>/home/da/.local/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in log
  """Entry point for launching an IPython kernel.<jupyter_text>InfinitiesAs we said previously, NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). Since somebody at IEEE decided to capture the misteries of infinity into floating numbers, we have yet another citizen to take into account when performing calculations (for more info see [Numpy documentation on constants](https://numpy.org/devdocs/reference/constants.html)):  Positive infinity `np.inf`<jupyter_code>np.array( [ 5 ] ) / 0
np.array( [ 6,9,5,7 ] ) / np.array( [ 2,0,0,4 ] )<jupyter_output>/home/da/.local/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: divide by zero encountered in true_divide
  """Entry point for launching an IPython kernel.<jupyter_text>Be aware that: - Not a Number is **not** equivalent to infinity- positive infinity is **not** equivalent to negative infinity- infinity is equivalent to positive infinity This time, infinity is equal to infinity:<jupyter_code>np.inf == np.inf<jupyter_output><empty_output><jupyter_text>so we can safely detect infinity with `==`:<jupyter_code>x = np.inf
 
if x == np.inf:
    print("x is infinite")
else:
    print("x is finite")<jupyter_output>x is infinite<jupyter_text>Alternatively, we can use the function `np.isinf`:<jupyter_code>np.isinf(np.inf)<jupyter_output><empty_output><jupyter_text>Negative infinityWe can also have negative infinity, which is different from positive infinity:<jupyter_code>-np.inf == np.inf<jupyter_output><empty_output><jupyter_text>Note that `isinf` detects _both_ positive and negative:<jupyter_code>np.isinf(-np.inf)<jupyter_output><empty_output><jupyter_text>To actually check for negative infinity you have to use `isneginf`:<jupyter_code>np.isneginf(-np.inf)
np.isneginf(np.inf)<jupyter_output><empty_output><jupyter_text>Where do they appear? As an example, let's try `np.log` function:<jupyter_code>np.log(0)<jupyter_output>/home/da/.local/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: divide by zero encountered in log
  """Entry point for launching an IPython kernel.<jupyter_text>Combining infinities and NaNsWhen performing operations involving infinities and NaNs, IEEE arithmetics tries to mimic classical analysis, sometimes including NaN as a result:<jupyter_code>np.inf + np.inf
- np.inf - np.inf
np.inf * -np.inf<jupyter_output><empty_output><jupyter_text>What in classical analysis would be undefined, here becomes NaN:<jupyter_code>np.inf - np.inf
np.inf / np.inf<jupyter_output><empty_output><jupyter_text>As usual, combining with NaN results in NaN:<jupyter_code>np.inf + np.nan
np.inf / np.nan<jupyter_output><empty_output><jupyter_text>Negative zero We can even have a _negative_ zero - who would have thought?<jupyter_code>np.NZERO<jupyter_output><empty_output><jupyter_text>Negative zero of course pairs well with the more known and much appreciated _positive_ zero:<jupyter_code>np.PZERO<jupyter_output><empty_output><jupyter_text>**NOTE**: Writing `np.NZERO` or `-0.0` is _exactly_ the same thing. Same goes for positive zero. At this point, you might start wondering with some concern if they are actually _equal_. Let's try:<jupyter_code>0.0 == -0.0<jupyter_output><empty_output><jupyter_text>Great! Finally one thing that makes sense. Given the above, you might think in a formula you can substitute one for the other one and get same results, in harmony with the rules of the universe. Let's make an attempt of substitution, as an example we first try dividing a number by positive zero (even if math teachers tell us such divisions are forbidden) - what will we ever get??$\frac{5.0}{0.0}=???$In Numpy terms, we might write like this to box everything in arrays:<jupyter_code>np.array( [ 5.0 ] ) / np.array( [ 0.0 ] )<jupyter_output>/home/da/.local/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: divide by zero encountered in true_divide
  """Entry point for launching an IPython kernel.<jupyter_text>Hmm, we got an array holding an `np.inf`.If `0.0`  and `-0.0` are actually the same, dividing a number by `-0.0`  we should get the very same result, shouldn't we?Let's try:<jupyter_code>np.array( [ 5.0 ] ) / np.array( [ -0.0 ] )<jupyter_output>/home/da/.local/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: divide by zero encountered in true_divide
  """Entry point for launching an IPython kernel.<jupyter_text>Oh gosh. This time we got an array holding a _negative_ infinity `-np.inf`If all of this seems odd to you, do not bash at Numpy. This is the way pretty much any CPUs does floating point calculations so you will find it in almost ALL computer languages.What programming languages can do is add further controls to protect you from paradoxical situations, for example when you directly write `1.0/0.0` Python raises `ZeroDivisionError` (blocking thus execution), and when you operate on arrays Numpy emits a warning (but doesn't block execution).  Exercise: detect proper numbersWrite some code that PRINTS `equal numbers` if two numbers `x` and `y` passed are equal and actual numbers, and PRINTS `not equal numbers` otherwise. **NOTE**: `not equal numbers` must be printed if any of the numbers is infinite or NaN.To solve it, feel free to call functions indicated in [Numpy documentation about costants](https://docs.scipy.org/doc/numpy/reference/constants.html)<jupyter_code># expected: equal numbers
x = 5
y = 5

# expected: not equal numbers
#x = np.inf
#y = 3

# expected: not equal numbers
#x = 3
#y = np.inf

# expected: not equal numbers
#x = np.inf
#y = np.nan

# expected: not equal numbers
#x = np.nan
#y = np.inf

# expected: not equal numbers
#x = np.nan
#y = 7

# expected: not equal numbers
#x = 9
#y = np.nan

# expected: not equal numbers
#x = np.nan
#y = np.nan


# write here

# SOLUTION 1 - the ugly one
if np.isinf(x) or np.isinf(y) or np.isnan(x) or np.isnan(y):
    print('not equal numbers')
else:
    print('equal numbers')
    
# SOLUTION 2 - the pretty one
if np.isfinite(x) and np.isfinite(y):
    print('equal numbers')
else:
    print('not equal numbers')<jupyter_output>equal numbers
equal numbers
{'fraction_non_alphanumeric': 0.11438183347350715, 'fraction_numerical': 0.020925147182506307, 'mean_word_length': 4.070100631076241, 'pattern_counts': {'":': 0, '<': 303, '<?xml version=': 0, '>': 314, 'https://': 8, 'lorem ipsum': 0, 'www.': 3, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '74', 'dir': 'jupyter-structured-clean-dedup', 'id': '75129', 'license': 'CC-BY-4.0', 'n_tokens_mistral': 9861, 'n_tokens_neox': 9320, 'n_words': 3487, 'path': 'matrices-numpy/matrices-numpy1-sol.ipynb', 'repo_name': 'simoneb1x/softpython-en', 'size': '29725'}