w3resource

Optimizing sum calculation of large 3D NumPy arrays


8. Large 3D Array Sum Optimization

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to compute the total sum of all elements in a large 3D array using triple nested loops, then optimize with np.sum.
  • Write a Numpy program to calculate the sum along a specific axis of a large 3D array using loops, then optimize using np.sum with an axis parameter.
  • Write a Numpy program to sum only those elements in a large 3D array that meet a given condition using loops, then optimize with boolean indexing and np.sum.
  • Write a Numpy program to compute partial sums on slices of a large 3D array using loops, then optimize with np.add.reduce over slices.

Python-Numpy Code Editor:

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

Previous: Optimizing element-wise multiplication of large 2D NumPy arrays.
Next: NumPy - Find maximum element in large array using For loop and optimization

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.