0
0
NumPydata~5 mins

Universal functions (ufuncs) in NumPy

Choose your learning style9 modes available
Introduction

Universal functions, or ufuncs, let you do math on whole arrays quickly and easily. They work element by element, like doing math on each number in a list all at once.

When you want to add, subtract, multiply, or divide every number in a list or table.
When you need to apply math functions like square root or sine to many numbers fast.
When you want to avoid slow loops and make your code run faster.
When working with large datasets and need quick calculations on arrays.
When you want simple, readable code for math operations on arrays.
Syntax
NumPy
numpy.ufunc_name(array1, array2, ...)

# Example:
np.add(array1, array2)

Replace ufunc_name with the math operation you want, like add, subtract, multiply, sqrt, etc.

You can use one or more arrays as inputs, depending on the function.

Examples
Adds 5 to each element in the array.
NumPy
import numpy as np

arr = np.array([1, 2, 3])
result = np.add(arr, 5)
print(result)
Calculates the square root of each element.
NumPy
import numpy as np

arr = np.array([4, 9, 16])
result = np.sqrt(arr)
print(result)
Multiplies elements from two arrays element-wise.
NumPy
import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = np.multiply(arr1, arr2)
print(result)
Sample Program

This program adds two arrays element by element, then finds the square root of each sum. It shows how ufuncs work on arrays without loops.

NumPy
import numpy as np

# Create two arrays
array1 = np.array([10, 20, 30])
array2 = np.array([1, 2, 3])

# Add arrays element-wise
added = np.add(array1, array2)

# Calculate square root of the result
sqrt_result = np.sqrt(added)

print("Added:", added)
print("Square root of added:", sqrt_result)
OutputSuccess
Important Notes

Ufuncs are very fast because they run compiled code internally.

They support broadcasting, so arrays of different shapes can work together if compatible.

Many common math functions in numpy are ufuncs, making array math easy.

Summary

Ufuncs apply math operations element-wise on arrays quickly.

They help avoid slow loops and make code simpler and faster.

Common ufuncs include add, subtract, multiply, divide, sqrt, sin, and more.