w3resource

Apply np.sin, np.cos, and np.tan ufuncs to angles in NumPy

NumPy: Universal Functions Exercise-5 with Solution

Applying Multiple ufuncs:

Write a NumPy program that applies np.sin, np.cos, and np.tan ufuncs to a 1D NumPy array of angles (in radians) and print the results.

Sample Solution:

Python Code:

import numpy as np

# Create a 1D NumPy array of angles in radians
angles = np.array([0, np.pi/6, np.pi/4, np.pi/3, np.pi/2])

# Apply np.sin ufunc to the angles array
sin_values = np.sin(angles)

# Apply np.cos ufunc to the angles array
cos_values = np.cos(angles)

# Apply np.tan ufunc to the angles array
tan_values = np.tan(angles)

# Print the original angles array and the resulting arrays
print('Original angles (radians):\n', angles)
print('Sine values:\n', sin_values)
print('Cosine values:\n', cos_values)
print('Tangent values:\n', tan_values)

Output:

Original angles (radians):
 [0.         0.52359878 0.78539816 1.04719755 1.57079633]
Sine values:
 [0.         0.5        0.70710678 0.8660254  1.        ]
Cosine values:
 [1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
 6.12323400e-17]
Tangent values:
 [0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
 1.63312394e+16]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Create 1D NumPy Array of Angles:
    • Create a 1D NumPy array named angles with values [0, np.pi/6, np.pi/4, np.pi/3, np.pi/2] representing angles in radians.
  • Apply np.sin ufunc:
    • Apply the np.sin ufunc to the angles array to compute the sine of each angle.
  • Apply np.cos ufunc:
    • Apply the np.cos "ufunc" to the angles array to compute the cosine of each angle.
  • Apply np.tan ufunc:
    • Apply the np.tan ufunc to the angles array to compute the tangent of each angle.
  • Print Results:
    • Print the original angles array and the resulting arrays of sine, cosine, and tangent values.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Element-wise Multiplication of 2D arrays using np.multiply in NumPy.
Next: Create array using np.where based on condition in NumPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/apply-np-dot-sin-np-dot-cos-and-np-dot-tan-ufuncs-to-angles-in-numpy.php