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:

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

Previous: Compute sum of all elements in 1D array using np.add.reduce.
Next: Compute Outer Subtraction of Two 1D Arrays Using np.subtract.outer.

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/compute-cumulative-product-of-elements-using-np-dot-multiply-dot-accumulate.php