NumPy Mathematical Functions

NumPy is a powerful Python library for scientific computing, which provides functions for performing mathematical operations on arrays and matrices of numbers. In this article, we will discuss some of the most commonly used mathematical functions in NumPy, along with examples to illustrate their usage.

NumPy Mathematical Functions

NumPy provides a variety of mathematical functions that can be applied to arrays and matrices of numbers. These functions are implemented in a highly optimized manner, making them much faster than equivalent functions implemented using loops in pure Python.

Trigonometric Functions

NumPy provides functions for computing the trigonometric functions sin, cos, and tan for arrays of angles in radians. For example:

import numpy as np # Create an array of angles in radians angles = np.array([0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi]) # Compute sines, cosines, and tangents of the angles sines = np.sin(angles) cosines = np.cos(angles) tangents = np.tan(angles) print(sines) # Output: [ 0. 1. 0. -1. 0.] print(cosines) # Output: [ 1. 0. -1. 0. 1.] print(tangents) # Output: [ 0. 1. 0. -1. 0.]

NumPy also provides functions for computing the inverse trigonometric functions arcsin, arccos, and arctan for arrays of angles in radians. For example:

import numpy as np # Create an array of sines sines = np.array([0, 1, 0, -1, 0]) # Compute angles in radians whose sines are given by the array angles = np.arcsin(sines) print(angles) # Output: [ 0. 1.57 -1.57 1.57 0. ]

Exponential and Logarithmic Functions

NumPy provides functions for computing the exponential function exp and the natural logarithm log for arrays of numbers. For example:

import numpy as np # Create an array of numbers x = np.array([1, 2, 3, 4, 5]) # Compute exponentials and logarithms of the numbers exponentials = np.exp(x) logarithms = np.log(x) print(exponentials) # Output: [ 2.72 7.39 20.09 54.6 148.41] print(logarithms) # Output: [ 0. 0.69 1.1 1.39 1.61]

NumPy also provides functions for computing the base-2 logarithm log2 and the base-10 logarithm log10 for arrays of numbers. For example:

import numpy as np # Create an array of numbers x = np.array([1, 2, 4, 8, 16]) # Compute base-2 and base-10 logarithms of the numbers log2 = np.log2(x) log10 = np

No comments

Powered by Blogger.