# Optimizing sum calculation of large 3D NumPy arrays

## NumPy: Performance Optimization Exercise-8 with Solution

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:**

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

**Weekly Trends and Language Statistics**- Weekly Trends and Language Statistics