MATHEMATICAL FUNCTIONS IN NUMPY

In this tutorial, we are going to learn about different mathematical functions in numpy like sin, cos and tan, along with their inverse sides we will look at some handy examples as well.


Recommended Book: Numerical Python



Numpy has a variety of built-in mathematical functions which allow us to solve problems related to trigonometry, arithmetic operations etc.

mathematical-numpy

Trigonometric functions

Numpy has an in-built feature of calculating sine, cosine and tangent of angles provided in radians. Let’s have a look at some of the examples:

Sine Function:

import numpy as np  
arr = np.array([0, 30, 60, 90, 120, 150, 180])  
print("sine: array of angles given in degrees")

print(np.sin(arr * np.pi / 180))  

Output:

sine: array of angles given in degrees
[0.00000000e+00 5.00000000e-01 8.66025404e-01 1.00000000e+00
 8.66025404e-01 5.00000000e-01 1.22464680e-16]

Cosine Function:

import numpy as np
arr = np.array([0, 30, 60, 90, 120, 150, 180])
print("cosine: array of angles given in degrees")

print(np.cos(arr * np.pi / 180))

Output:

cosine: array of angles given in degrees
[ 1.00000000e+00  8.66025404e-01  5.00000000e-01  6.12323400e-17
 -5.00000000e-01 -8.66025404e-01 -1.00000000e+00]


Tangent Function:

import numpy as np
arr = np.array([0, 30, 60, 90, 120, 150, 180])
print("tangent: array of angles given in degrees")

print(np.tan(arr * np.pi / 180))

Output:

tangent: array of angles given in degrees
[ 0.00000000e+00  5.77350269e-01  1.73205081e+00  1.63312394e+16
-1.73205081e+00 -5.77350269e-01 -1.22464680e-16]

You can use the inverse trigonometric functions as well such as arcsin(), arccos() and arctan() which will generate inverse values of the given angles.

The cosec function – arcsin():

import numpy as np
arr = np.array([0, 30, 60])

print("cosec: array of angles given in degrees")
sin = np.sin(arr * np.pi / 180)

cosec = np.arcsin(sin)
print("Inverse of sin is: ", cosec)

Output:

cosec: array of angles given in degrees
Inverse of sin is:  [0.         0.52359878 1.04719755]

The sec function – arccos():

import numpy as np
arr = np.array([0, 30, 60])
print("sec: array of angles given in degrees")

cos = np.cos(arr * np.pi / 180)

sec = np.arccos(cos)
print("Inverse of cos is: ", sec)

Output:

sec: array of angles given in degrees
Inverse of cos is:  [0.         0.52359878 1.04719755]


The cot function – arctan()

import numpy as np
arr = np.array([0, 30, 60])
print("cot: array of angles given in degrees")

tan = np.tan(arr * np.pi / 180)

cot = np.arctan(tan)
print("Inverse of tan is: ", cot)

Output:

cot: array of angles given in degrees
Inverse of tan is:  [0.         0.52359878 1.04719755]

There are a lot of other mathematical functions which you can refer to in the main documentation of numpy here