NumPy Universal Function

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(), and tan()
  • Arithmetic functions like add(), subtract(), and multiply()
  • Rounding functions like floor(), ceil() and around()
  • Aggregation functions like mean(), min(), and max().

Let's see some examples.

Example: Trigonometric Functions

import numpy as np

# array of angles in radians
angles = np.array([0, 1, 2])
print("Angles:", angles)

# compute the sine of the angles
sine_values = np.sin(angles)
print("Sine values:", sine_values)

# compute the inverse sine of the angles
inverse_sine = np.arcsin(angles)
print("Inverse Sine values:", inverse_sine)

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

import numpy as np

first_array = np.array([1, 3, 5, 7])
second_array = np.array([2, 4, 6, 8])

# using the add() function
result2 = np.add(first_array, second_array)
print("Using the add() function:",result2) 

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

import numpy as np

numbers = np.array([1.23456, 2.34567, 3.45678, 4.56789])

# round the array to two decimal places
rounded_array = np.round(numbers, 2)

print("Array after round():", rounded_array)

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

import numpy as np

array1 = np.array([1, 2, 3, 4, 5])

# calculate the median
median = np.median(array1)
print("Median is:",median)

# find the largest element
max = np.max(array1)
print("Largest element is", max)

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.