
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
NumPy - Mathematical Functions
NumPy Mathematical Functions
NumPy provides a wide range of mathematical functions that are essential for performing numerical operations on arrays. These functions include basic arithmetic, trigonometric, exponential, logarithmic, and statistical operations, among others.
In this tutorial, we will explore the most commonly used mathematical functions in NumPy, with examples to help you understand their application.
Basic Arithmetic Operations
In NumPy, basic arithmetic operations include addition, subtraction, multiplication, and division on arrays. These operations are element-wise, meaning they are applied to each corresponding element in the arrays.
For example, adding two arrays results in a new array where each element is the sum of the corresponding elements from the input arrays.
NumPy also supports scalar operations, allowing you to apply a number to each element of an array directly.
Example: Addition, Subtraction, Multiplication, and Division
In the following example, we perform basic arithmetic operations like addition, subtraction, multiplication, and division on two NumPy arrays −
import numpy as np # Define two arrays a = np.array([10, 20, 30]) b = np.array([5, 10, 15]) # Perform basic arithmetic operations addition = a + b subtraction = a - b multiplication = a * b division = a / b print("Addition:", addition) print("Subtraction:", subtraction) print("Multiplication:", multiplication) print("Division:", division)
We get the output as shown below −
Addition: [15 30 45] Subtraction: [ 5 10 15] Multiplication: [ 50 200 450] Division: [2. 2. 2.]
Trigonometric Functions
NumPy also provides several functions to perform trigonometric operations on arrays. These include basic trigonometric functions like sine, cosine, and tangent, which operate element-wise on arrays.
Example: Sine, Cosine, and Tangent
Let us explore how to calculate the sine, cosine, and tangent of an array in NumPy −
import numpy as np # Define an array of angles in radians angles = np.array([0, np.pi/4, np.pi/2, np.pi]) # Calculate sine, cosine, and tangent sine_values = np.sin(angles) cosine_values = np.cos(angles) tangent_values = np.tan(angles) print("Sine values:", sine_values) print("Cosine values:", cosine_values) print("Tangent values:", tangent_values)
Following is the output obtained −
Sine values: [0.00000000e+00 7.07106781e-01 1.00000000e+00 1.22464680e-16] Cosine values: [ 1.00000000e+00 7.07106781e-01 6.12323400e-17 -1.00000000e+00] Tangent values: [ 0.00000000e+00 1.00000000e+00 1.63312394e+16 -1.22464680e-16]
Note that the tangent of pi/2 is infinity because the cosine of pi/2 is zero, and division by zero is undefined.
Exponential and Logarithmic Functions
NumPy also provides functions to calculate exponential values and logarithms, which are used in various scientific and engineering calculations. These functions allow you to compute powers, roots, and logarithms of arrays.
Exponentiation
The numpy.exp() function calculates the exponential of all elements in the input array. Following is an example −
import numpy as np # Create an array arr = np.array([1, 2, 3]) # Calculate the exponential of the array exp_array = np.exp(arr) print("Exponential values:", exp_array)
This will produce the following result −
Exponential values: [ 2.71828183 7.3890561 20.08553692]
Logarithm
NumPy provides the numpy.log() function for calculating the natural logarithm (base e), and numpy.log10() function for calculating the logarithm to base 10.Following is an example −
import numpy as np # Create an array arr = np.array([1, 2, 10]) # Calculate the natural logarithm and base-10 logarithm log_array = np.log(arr) log10_array = np.log10(arr) print("Natural logarithm values:", log_array) print("Base-10 logarithm values:", log10_array)
Following is the output of the above code −
Natural logarithm values: [0. 0.69314718 2.30258509] Base-10 logarithm values: [0. 0.30103 1. ]
Statistical Functions in NumPy
NumPy also provides a wide variety of statistical functions. These include calculating mean, median, variance, standard deviation, and more. These functions are useful when analyzing data and performing statistical analysis on arrays.
Mean and Median
The numpy.mean() function calculates the arithmetic mean, and the numpy.median() function calculates the median of an array as shown in the example below −
import numpy as np # Create an array arr = np.array([1, 2, 3, 4, 5]) # Calculate the mean and median of the array mean_value = np.mean(arr) median_value = np.median(arr) print("Mean value:", mean_value) print("Median value:", median_value)
The output obtained is as shown below −
Mean value: 3.0 Median value: 3.0
Standard Deviation and Variance
The numpy.std() function calculates the standard deviation, and numpy.var() function calculates the variance of the array −
import numpy as np # Create an array arr = np.array([1, 2, 3, 4, 5]) # Calculate the standard deviation and variance std_dev = np.std(arr) variance = np.var(arr) print("Standard Deviation:", std_dev) print("Variance:", variance)
After executing the above code, we get the following output −
Standard Deviation: 1.4142135623730951 Variance: 2.0
Linear Algebra Functions
NumPy also provides a set of linear algebra functions, such as matrix multiplication, dot products, and matrix determinants, which are important for operations on vectors and matrices.
Dot Product
The numpy.dot() function is used to calculate the dot product of two arrays. It is commonly used in machine learning, physics, and engineering −
import numpy as np # Create two arrays arr1 = np.array([1, 2]) arr2 = np.array([3, 4]) # Calculate the dot product dot_product = np.dot(arr1, arr2) print("Dot product:", dot_product)
The result produced is as follows −
Dot product: 11
Matrix Multiplication
Matrix multiplication in NumPy is performed using the @ operator or the numpy.matmul() function. It calculates the dot product of two arrays, where the number of columns in the first matrix must equal the number of rows in the second matrix.
The result is a new matrix where each element is the sum of the products of corresponding row and column elements. Matrix multiplication is commonly used in linear algebra and machine learning tasks.
Example
In this example, matrix A is multiplied by matrix B to produce matrix C, where each element is calculated by the dot product of rows from A and columns from B −
import numpy as np # Define two matrices A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) # Perform matrix multiplication C = np.matmul(A, B) # Print the result print(C)
We get the output as shown below −
[[19 22] [43 50]]