NumPy universal functions are mathematical functions that allow vectorization.
Vectorization refers to performing element-wise operations on arrays. Before you read this tutorial, make sure you understand vectorization.
NumPy Universal Functions
The universal functions in NumPy include
- Trigonometric functions like
sin(),cos(), andtan()
- Arithmetic functions like
add(),subtract(), andmultiply()
- Rounding functions like
floor(),ceil()andaround()
- Aggregation functions like
mean(),min(), andmax().
Let's see some examples.
Example: Trigonometric Functions
Output
Angles: [0 1 2] Sine values: [0. 0.84147098 0.90929743] Inverse Sine values: [0. 1.57079633 nan]
In this example, we have used universal functions sin() and arcsin() to compute the sine and inverse sine values respectively.
When we perform the sin() function to the array angles, an element-wise operation is performed to entire elements of the array. This is called vectorization.
Example: Arithmetic Functions
Output
Using the add() function: [ 3 7 11 15]
Here, we used the universal function add() to add two arrays, first_array and second_array.
Example: Rounding Functions
Output
Array after round(): [1.23 2.35 3.46 4.57]
Here, we used the universal function round() to round the values of array numbers.
To learn more about Trigonometric, Arithmetic, and Rounding functions, visit NumPy Math Functions.
Example: Statistical Functions
Output
Median is: 3.0 Largest element is 5
In this example, we have used the universal functions median() and max() to find the median and largest element of array1.
To learn more, visit NumPy Statistical Functions.