NumPy Ufunc Summations
In this article, we will explore NumPy ufunc summations in detail and calculating summations utilizing NumPy, in order to discover which method will be most suitable for you.
What are NumPy Ufunc Summations?
NumPy ufunc summations are mathematical operations that calculate the sum of ndarrays element-wise.
They are implemented as ufuncs, which allows them to perform fast and efficient calculations on large arrays.
The NumPy ufunc summation functions include:
|numpy.sum()||Computes the sum of array elements along a given axis.|
|numpy.cumsum()||Returns the cumulative sum of the elements along a given axis.|
|numpy.nansum()||Computes the sum of array elements along a given axis, ignoring NaN values.|
|numpy.cumprod()||Returns the cumulative product of the elements along a given axis.|
|numpy.prod()||Computes the product of array elements along a given axis.|
|numpy.nanprod()||Computes the product of array elements along a given axis, ignoring NaN values.|
Difference Between Summation and Addition
According to Numpy Ufunc summations, addition occurs between two arguments, while summation occurs over n elements.
Initialize the two arrays even_arr and odd_arr then apply the add() function to add both arrays together:
Upon execution you will see below outcome:
Execute the add() function on both the prime_arr and nonprime_arr arrays after creating them:
Take the sum of the even_arr and odd_arr arrays:
Apply the sum() function to the following arrays:
If you specify axis=1 according to Numpy Ufunc summations, NumPy will sum the numbers in the arrays based on the axis value you provide.
You can compute the summation of the even_arr and odd_arr arrays over the 1st axis as follows:
Execute the sum() function with axis = 1 on the square_arr and cube_arr arrays:
The cumulative sum refers to the part-by-part addition of items in an array.
For example, the partial total of [7, 13, 19] would be [7, 7+13, 7+13+19] = [7, 20, 39].
You can utilize the cumsum() function to calculate partial sums.
Calculate the cumulative sum of the following gap_arr array:
First create the factorial_arr array then implement the cumsum() function on it:
In first line, the NumPy library is imported using the alias “npy” to save time and make the code more concise. Then, an array of factorials is created using the npy.array() function, which takes a list of integers as input and returns an array with those values.
The list [1, 2, 6, 24, 120] represents the factorials of the first five positive integers, i.e., 1!, 2!, 3!, 4!, and 5!.
The next line uses the npy.cumsum() function to compute the cumulative sum of the elements in the factorial_arr array.
This function takes an array as input and returns an array containing the cumulative sum of each element.