Mathematical Operations in NumPy Framework

NumPy is a powerful library for numerical computing in Python. It provides a variety of mathematical operations that can be performed efficiently on arrays.

1. Importing NumPy

Before using NumPy, it needs to be imported.

            import numpy as np
        

2. Basic Arithmetic Operations

NumPy supports element-wise arithmetic operations such as addition, subtraction, multiplication, and division.

            a = np.array([1, 2, 3])
            b = np.array([4, 5, 6])
            
            print(a + b)  # Output: [5 7 9]
            print(a - b)  # Output: [-3 -3 -3]
            print(a * b)  # Output: [4 10 18]
            print(a / b)  # Output: [0.25 0.4 0.5]
        

3. Exponentiation and Logarithm

NumPy provides functions for exponentiation and logarithmic calculations.

            print(np.exp(a))  # Exponential function
            print(np.log(b))  # Natural logarithm
            print(np.log10(b))  # Base-10 logarithm
        

4. Trigonometric Functions

NumPy includes trigonometric functions such as sine, cosine, and tangent.

            angles = np.array([0, np.pi/2, np.pi])
            
            print(np.sin(angles))  # Output: [0. 1. 0.]
            print(np.cos(angles))  # Output: [1. 0. -1.]
            print(np.tan(angles))  # Output: [ 0. 1.633e+16 -1.224e-16]
        

5. Aggregate Functions

NumPy provides functions to compute summation, mean, and standard deviation.

            values = np.array([1, 2, 3, 4, 5])
            
            print(np.sum(values))  # Output: 15
            print(np.mean(values))  # Output: 3.0
            print(np.std(values))  # Output: 1.414
        

6. Linear Algebra Operations

NumPy supports matrix operations such as dot product and matrix multiplication.

            matrix1 = np.array([[1, 2], [3, 4]])
            matrix2 = np.array([[5, 6], [7, 8]])
            
            print(np.dot(matrix1, matrix2))  # Matrix multiplication
            print(np.linalg.det(matrix1))  # Determinant of a matrix
            print(np.linalg.inv(matrix1))  # Inverse of a matrix
        

Conclusion

NumPy provides an extensive set of mathematical functions that simplify numerical computations in Python. These operations are optimized for performance and are useful in various scientific and engineering applications.





Advertisement