w3resource

NumPy - Element-wise division of large arrays using For loop and optimization

NumPy: Performance Optimization Exercise-10 with Solution

Write a NumPy program that creates two large 1D NumPy arrays and write a function to compute their element-wise division using a for loop. Optimize it with vectorized operations.

Sample Solution:

Python Code:

import numpy as np

# Generate two large 1D NumPy arrays with random integers
array1 = np.random.randint(1, 1000, size=1000000)
array2 = np.random.randint(1, 1000, size=1000000)

# Function to compute element-wise division using a for loop
def element_wise_division_with_loop(arr1, arr2):
    result = np.empty_like(arr1, dtype=float)
    for i in range(len(arr1)):
        result[i] = arr1[i] / arr2[i]
    return result

# Compute element-wise division using the for loop method
result_with_loop = element_wise_division_with_loop(array1, array2)

# Compute element-wise division using NumPy's vectorized operations
result_with_numpy = array1 / array2

# Display first 10 results to verify
print("First 10 results using for loop:")
print(result_with_loop[:10])

print("First 10 results using NumPy:")
print(result_with_numpy[:10])

Output:

First 10 results using for loop:
[ 0.59012346  0.74968072  0.99297753  4.62721893 11.5         0.60264901
  1.35180723  0.93093093  5.84732824  2.8951049 ]
First 10 results using NumPy:
[ 0.59012346  0.74968072  0.99297753  4.62721893 11.5         0.60264901
  1.35180723  0.93093093  5.84732824  2.8951049 ]

Explanation:

  • Importing numpy: We first import the numpy library for array manipulations.
  • Generating large arrays: Two large 1D NumPy arrays with random integers are generated.
  • Defining the function: A function element_wise_division_with_loop is defined to compute the element-wise division using a for loop.
  • Computing with loop: Element-wise division is computed using the for loop method.
  • Computing with numpy: Element-wise division is computed using NumPy's vectorized operations.
  • Displaying results: The first 10 results from both methods are printed out to verify correctness.

Python-Numpy Code Editor:

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

Previous: NumPy - Find maximum element in large array using For loop and optimization.
Next: NumPy - Cumulative sum of large array using For loop and optimization.

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/numpy-element-wise-division-of-large-arrays-using-for-loop-and-optimization.php