﻿ Optimizing element-wise addition of large NumPy arrays

# Optimizing element-wise addition of large NumPy arrays

## NumPy: Performance Optimization Exercise-2 with Solution

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
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
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.

Python-Numpy Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿