Time for action – computing the modulo

Let's call the previously mentioned functions:

  1. The remainder() function returns the remainder of the two arrays, element-wise. 0 is returned if the second number is 0:
    a = np.arange(-4, 4)
    print("Remainder", np.remainder(a, 2))

    The result of the remainder() function is shown as follows:

    Remainder [0 1 0 1 0 1 0 1]
    
  2. The mod() function does exactly the same as the remainder() function:
    print("Mod", np.mod(a, 2))

    The result of the mod() function is shown as follows:

    Mod [0 1 0 1 0 1 0 1]
    
  3. The % operator is just shorthand for the remainder() function:
    print("% operator", a % 2)

    The result of the % operator is shown as follows:

    % operator [0 1 0 1 0 1 0 1]
    
  4. The fmod() function handles negative numbers differently than mod(), fmod(), and % do. The sign of the remainder is the sign of the dividend, and the sign of the divisor has no influence on the results:
    print("Fmod", np.fmod(a, 2))

    The fmod() result is printed as follows:

    Fmod [ 0 -1  0 -1  0  1  0  1]
    

What just happened?

We demonstrated the NumPy the mod(), remainder(), and fmod() functions, which compute the modulo or remainder (see modulo.py):

from __future__ import print_function
import numpy as np

a = np.arange(-4, 4)

print("Remainder", np.remainder(a, 2))
print("Mod", np.mod(a, 2))
print("% operator", a % 2)
print("Fmod", np.fmod(a, 2))
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset