NumPy: Compute sine, cosine and tangent array of angles given in degrees
Write a NumPy program to compute the trigonometric sine, cosine and tangent array of angles given in degrees.
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Computing the sine values for an array of angles given in degrees
print("sine: array of angles given in degrees")
print(np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180.))
# Computing the cosine values for an array of angles given in degrees
print("cosine: array of angles given in degrees")
print(np.cos(np.array((0., 30., 45., 60., 90.)) * np.pi / 180.))
# Computing the tangent values for an array of angles given in degrees
print("tangent: array of angles given in degrees")
print(np.tan(np.array((0., 30., 45., 60., 90.)) * np.pi / 180.))
Sample Output:
sine: array of angles given in degrees [ 0. 0.5 0.70710678 0.8660254 1. ] cosine: array of angles given in degrees [ 1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01 6.12323400e-17] tangent: array of angles given in degrees [ 0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00 1.63312394e+16]
Explanation:
np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180.) – Here np.sin() takes an array of angles in degrees, converts them to radians using the formula (angle * np.pi) / 180., and returns an array of their corresponding sine values.
np.cos(np.array((0., 30., 45., 60., 90.)) * np.pi / 180.) – Here np.cos() takes an array of angles in degrees, converts them to radians using the formula (angle * np.pi) / 180., and returns an array of their corresponding cosine values.
np.tan(np.array((0., 30., 45., 60., 90.)) * np.pi / 180.) – np.tan() takes an array of angles in degrees, converts them to radians using the formula (angle * np.pi) / 180., and returns an array of their corresponding tangent values.
Pictorial Presentation:
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics