w3resource

Compute cumulative product of elements using np.multiply.accumulate


NumPy: Universal Functions Exercise-10 with Solution


ufunc Accumulate Method:

Write a NumPy program that uses the np.multiply.accumulate ufunc to compute the cumulative product of elements in a 1D array.

Sample Solution:

Python Code:

import numpy as np

# Create a 1D NumPy array of integers
array_1d = np.array([1, 2, 3, 4, 5])

# Use the np.multiply.accumulate ufunc to compute the cumulative product of elements in the array
cumulative_product = np.multiply.accumulate(array_1d)

# Print the original array and the cumulative product of its elements
print('Original 1D array:', array_1d)
print('Cumulative product using np.multiply.accumulate:', cumulative_product)

Output:

Original 1D array: [1 2 3 4 5]
Cumulative product using np.multiply.accumulate: [  1   2   6  24 120]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Create 1D NumPy Array:
    • Create a 1D NumPy array named array_1d with integers [1, 2, 3, 4, 5].
  • Use np.multiply.accumulate ufunc:
    • Used the np.multiply.accumulate ufunc to compute the cumulative product of elements in the array_1d. The accumulate method applies the np.multiply ufunc cumulatively to the elements of the array, resulting in the cumulative product.
  • Print Results:
    • Print the original array and the cumulative product of its elements computed using "np.multiply.accumulate".

Python-Numpy Code Editor: