/    /  NumPy – Mathematical Functions

NumPy – Mathematical Functions:

In Numpy, we can perform various Mathematical calculations using the various functions that are provided in the library.

Advanced Mathematical operations those can be performed are Trigonometric functions, Hyperbolic functions, Rounding, Sums, Products, differences, exponents, logarithms etc.

Here, let us perform some of those Mathematical functions.

Trigonometric Operations:

sin: This will return the element-wise Trigonometric sine calculation.

cos: This will return the element-wise Trigonometric cosine calculation.

tan: This will return the element-wise Trigonometric tangent calculation.

Example:

>>> import numpy as np

>>> np.sin(np.pi/2)
1.0

>>> np.cos(np.pi/2)
6.123233995736766e-17

>>> np.tan(np.pi/2)
16331239353195370.0

 

Rounding Operations:

floor: This will return the floor of the input, element-wise.

ceil: This will return the ceiling of the input, element-wise.

trunc: This will return the truncated value of the input, element-wise.

Example:

>>> import numpy as np

>>> x=np.array([-1.4, -1.1, -0.4, 0.7, 1.6, 1.9, 2.0])

>>> print(x)
[-1.4 -1.1 -0.4 0.7 1.6 1.9 2. ]

>>> print(np.floor(x))
[-2. -2. -1. 0. 1. 1. 2.]

>>> print(np.ceil(x))
[-1. -1. -0. 1. 2. 2. 2.]

>>> print(np.trunc(x))
[-1. -1. -0. 0. 1. 1. 2.]

 

Sums and Differences:

sum: This will return the sum of array elements for the given axis.

diff: This will return the nth-discrete difference along given axis.

Example:

>>> import numpy as np

>>> x=np.sum([[1,2],[3,4]])

>>> print(x)
10

>>> y=np.sum([[1,2],[3,4]], axis=0)

>>> print(y)
[4 6]

>>> z=np.sum([[1,2],[3,4]], axis=1)

>>> print(z)
[3 7]

>>> x=np.diff([[1,2],[3,4]])

>>> print(x)
[[1]
[1]]

>>> y=np.diff([[1,2],[3,4]], axis=0)

>>> print(y)
[[2 2]]

>>> z=np.diff([[1,2],[3,4]], axis=1)

>>> print(z)
[[1]
[1]]

 

Logarithmic Operations:

log: This will return the Natural logarithm, element-wise.

log2: This will return the Base-2 logarithm of x.

Example:

>>> import numpy as np

>>> x=np.log([1])

>>> print(x)
[ 0.]

>>> y=np.log2([2,4,8])

>>> print(y)
[ 1. 2. 3.]