How to calculate a tangent for a given angle in python ?

Published: April 13, 2021

Tags: Python; Math;

DMCA.com Protection Status

Examples of how to calculate and plot a tangent function in python

Calculate a tangent for a given angle

To get the tangent of a given angle a solution is to use the module math, for example

import math

angle = 0

math.tan(angle)

returns

0

Note: the tan function assumes that the input is in radian. To convert degree to radian a solution is to use math.radians()

angle = 45 # angle in degree
angle = math.radians(angle) # angle in radian

Another example

angle = math.pi / 6

math.tan(angle)

returns

0.5773502691896256

Note: to round a float in python, a solution is to use round():

round( math.tan(angle), 2 )

gives

0.58

Plot a tangent function

import matplotlib.pyplot as plt
import numpy as np

angle_min = - 2.0 * math.pi
angle_max = 2.0 * math.pi
res = 0.01

angle_list = [a for a in np.arange(angle_min,angle_max,res)]
angle_tan_list = [math.tan(a) for a in angle_list]

plt.plot(angle_list, angle_tan_list)

plt.title("How to calculate a tangent for a given angle in python ?",fontsize=12)

plt.ylim(-10,10)

plt.savefig("tangent_function_01.png", bbox_inches='tight', dpi=100)

plt.show()

How to calculate a tangent for a given angle in python ?
How to calculate a tangent for a given angle in python ?

References

Image

of