w3resource

Optimizing element-wise addition of large NumPy arrays


2. Large Array Element-wise Addition Optimization

Write a NumPy program that generate two large NumPy arrays and write a function to perform element-wise addition using a for loop. Optimize it with vectorized operations.

Sample Solution:

Python Code:

import numpy as np

# Generate two large NumPy arrays with 1 million elements each
array1 = np.random.rand(1_000_000)
array2 = np.random.rand(1_000_000)

# Function to perform element-wise addition using a for loop
def add_using_loop(arr1, arr2):
    result = np.zeros_like(arr1)
    for i in range(len(arr1)):
        result[i] = arr1[i] + arr2[i]
    return result

# Perform element-wise addition using the for loop
sum_loop = add_using_loop(array1, array2)
print("Sum using for loop (first 10 elements):", sum_loop[:10])

# Optimize the element-wise addition using vectorized operations
sum_vectorized = array1 + array2
print("Sum using vectorized operations (first 10 elements):", sum_vectorized[:10])

Output:

Sum using for loop (first 10 elements): [0.82969092 0.60765517 0.99252235 0.80627455 0.83265615 0.60942688
 1.31452386 1.64925039 1.49971366 1.22739445]
Sum using vectorized operations (first 10 elements): [0.82969092 0.60765517 0.99252235 0.80627455 0.83265615 0.60942688
 1.31452386 1.64925039 1.49971366 1.22739445]

Explanation:

  • Generate two large arrays: Two large 1D NumPy arrays, each with 1 million elements, are created using np.random.rand().
  • Function with for loop: A function add_using_loop performs element-wise addition of the arrays using a for loop.
  • Calculate sum with for loop: The sum of the arrays is calculated using the for loop, and the first 10 elements are printed.
  • Optimize with vectorization: The element-wise addition is optimized using NumPy's vectorized operations, and the first 10 elements are printed.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to perform element-wise subtraction of two large arrays using a for loop, then optimize it with vectorized operations.
  • Write a Numpy program to add two large arrays while applying a conditional mask using loops, and then optimize using np.where and broadcasting.
  • Write a Numpy program to compute element-wise addition of two large arrays with overflow protection using a loop, then optimize with proper dtype handling and vectorization.
  • Write a Numpy program to add two large arrays element-wise and then compute the running sum of the result using a for loop, then optimize with np.cumsum.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Optimizing sum calculation of a large NumPy array.
Next: Optimizing Dot product calculation of large NumPy arrays.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.