w3resource

Optimizing sum calculation of large 3D NumPy arrays


Write a NumPy program to generate a large 3D NumPy array and write a function to compute the sum of all elements using nested for loops. Optimize it using NumPy's built-in functions.

Sample Solution:

Python Code:

import numpy as np

# Create a large 3D NumPy array with shape (100, 100, 100)
large_array = np.random.rand(100, 100, 100)

# Function to compute the sum of all elements using nested for loops
def sum_using_loops(array):
    total_sum = 0.0
    for i in range(array.shape[0]):
        for j in range(array.shape[1]):
            for k in range(array.shape[2]):
                total_sum += array[i, j, k]
    return total_sum

# Compute the sum using the nested for loops
sum_loop = sum_using_loops(large_array)
print("Sum using nested for loops:", sum_loop)

# Optimize the sum computation 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 nested for loops: 500193.4387505151
Sum using NumPy's built-in function: 500193.438750515

Explanation:

  • Create a large array: A 3D NumPy array with shape (100, 100, 100) is created using np.random.rand().
  • Function with nested for loops: A function sum_using_loops computes the sum of all elements using nested for loops.
  • Compute sum with loops: The sum of all elements is calculated using the nested for loops and printed.
  • Optimize with NumPy: The sum computation is optimized using NumPy's built-in np.sum() function and printed.

Python-Numpy Code Editor: