NumPy ufuncs

M.Ramya

 What are ufuncs?

ufuncs stands for Universal Functions in NumPy. These are special functions that operate element-wise on ndarray objects, enabling fast and efficient computations.

Why Should You Use ufuncs?

ufuncs play a key role in vectorization—a powerful feature of NumPy that eliminates the need for slow Python loops. Instead of processing elements one by one, ufuncs perform operations on entire arrays at once, making them significantly faster.

Additionally, ufuncs offer advanced features such as:

  • Broadcasting: Automatically expanding arrays of different shapes for operations.
  • Additional methods like reduce, accumulate, etc., which simplify complex computations.

They also accept several useful optional arguments:

  • where: A condition specifying where the operation should apply.
  • dtype: To specify the desired data type of the output.
  • out: To store the result in a specified array.

What is Vectorization?

Vectorization refers to transforming iterative code (like loops) into array operations.

This approach is faster and more efficient because it leverages low-level optimizations in modern CPUs and NumPy’s internal C-based implementation 

Adding Elements of Two Lists

Let’s see this in action by adding two lists together.

Method 1: Without ufunc (Traditional Python Loop)

Method 2: With ufunc (NumPy Vectorized Approach)

Program:

x = [1, 2, 3, 4]

y = [4, 5, 6, 7]

z = []

for i, j in zip(x, y):

    z.append(i + j)

print(z)

Output:

[5, 7, 9, 11]

Program:

Using NumPy’s add() ufunc, we can achieve the same result more efficiently:

import numpy as np

x = [1, 2, 3, 4]

y = [4, 5, 6, 7]

z = np.add(x, y)

print(z)

 Output:

[5 7 9 11]


Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send