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:

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

Previous: Numpy Performance Optimization Exercises Home.
Next: Optimizing element-wise addition of large NumPy arrays.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/optimizing-sum-calculation-of-a-large-numpy-array.php