w3resource

Optimizing sum calculation of a large NumPy array


NumPy: Performance Optimization Exercise-1 with Solution


Write a NumPy program that creates a large 1D array and write a function to calculate the sum of its elements using a for loop. Then, optimize it using NumPy's built-in functions.

Sample Solution:

Python Code:

import numpy as np
# Create a large 1D array with 1 million elements
large_array = np.random.rand(1_000_000)

# Function to calculate the sum using a for loop
def sum_using_loop(array):
    total = 0.0
    for element in array:
        total += element
    return total

# Calculate the sum using the for loop
sum_loop = sum_using_loop(large_array)
print("Sum using for loop:", sum_loop)

# Optimize the sum calculation using NumPy's built-in function
sum_numpy = np.sum(large_array)
print("Sum using NumPy's built-in function:", sum_numpy)

Output:

Sum using for loop: 500214.5331561951
Sum using NumPy's built-in function: 500214.5331562045

Explanation:

  • Create a large 1D array: A 1D array with 1 million elements is created using np.random.rand().
  • Function with for loop: A function sum_using_loop calculates the sum of the array elements using a for loop.
  • Calculate sum with for loop: The sum of the array elements is calculated using the for loop and printed.
  • Optimize with NumPy: The sum calculation is optimized using NumPy's built-in np.sum() function and printed.

Python-Numpy Code Editor: