NumPy’s tan()
Function: Calculating Tangents
The tan()
function in NumPy computes the tangent of an angle (in radians). It’s a vectorized function, meaning it can operate on single values, arrays, or even matrices with remarkable efficiency.
import numpy as np
= np.pi / 4 # 45 degrees in radians
angle_rad = np.tan(angle_rad)
tangent print(f"The tangent of {angle_rad} radians is: {tangent}")
= np.array([0, np.pi/2, np.pi])
angles_rad = np.tan(angles_rad)
tangents print(f"Tangents of angles: {tangents}") # Note: you'll get an inf for pi/2
#Handling potential errors
= np.array([0, np.pi/2, np.pi])
angles_rad
try:
= np.tan(angles_rad)
tangents print(f"Tangents of angles: {tangents}")
except RuntimeWarning as e:
print(f"Error calculating tangent: {e}")
The output demonstrates how tan()
gracefully handles both scalar and array inputs. Remember that angles must be provided in radians. The example also shows error handling for cases where the tangent is undefined, such as at pi/2
NumPy’s arctan()
Function: Finding Arctangents
The inverse trigonometric function arctan()
, also known as tan⁻¹()
, calculates the angle whose tangent is a given value. Like tan()
, it’s vectorized and operates on various input types. The result is in radians.
import numpy as np
= 1
tangent_value = np.arctan(tangent_value)
angle_rad print(f"The arctangent of {tangent_value} is: {angle_rad} radians")
= np.array([0, 1, -1])
tangent_values = np.arctan(tangent_values)
angles_rad print(f"Arctangents of values: {angles_rad} radians")
#Using arctan2 for a more robust solution
= np.array([1, 1, -1, -1])
x_values = np.array([1, -1, 1, -1])
y_values = np.arctan2(y_values, x_values)
angles_rad print(f"Arctangents using arctan2: {angles_rad} radians")
The code showcases the basic usage of arctan()
. Note that arctan()
returns values in the range (-π/2, π/2). For a more solution that accounts for all four quadrants, consider using arctan2(y, x)
, which takes both the y and x coordinates as input, providing a more accurate angle.
Beyond the Basics: Degrees and Broadcasting
While tan()
and arctan()
operate on radians, you can easily convert between radians and degrees using NumPy’s degrees()
and radians()
functions. NumPy’s broadcasting rules allow for seamless operations between arrays of different shapes (under certain conditions), making these functions extremely versatile for complex calculations. Exploring these aspects will further enhance your ability to use the power of NumPy’s trigonometric capabilities.