Addition vs Summation
Though addition and summation might sound similar, they have distinct purposes in programming:
- Addition involves combining two numbers or arrays.
- Summation refers to adding multiple elements, often over an entire array or along a specific axis.
Program:
Addition
Let’s see an example of adding two arrays element-wise using NumPy:
Let’s see an example of adding two arrays element-wise using NumPy:
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([1, 2, 3])
newarr = np.add(arr1, arr2)
print(newarr)
Output:
[2 4 6]
Program:
Summation
Now, let’s perform a summation across multiple arrays:
Now, let’s perform a summation across multiple arrays:
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([1, 2, 3])
newarr = np.sum([arr1, arr2])
print(newarr)
Output:
12Here, np.sum() sums all elements from both arrays combined.
Summation Over an Axis
You can also sum along a specific axis using the axis parameter:
Program:
import numpy as nparr1 = np.array([1, 2, 3])
arr2 = np.array([1, 2, 3])
newarr = np.sum([arr1, arr2], axis=1)
print(newarr)
Output:
[6 6]axis=1 sums the elements within each array separately.
Cumulative Sum
A cumulative sum (also called partial sum) adds elements progressively.For example, the cumulative sum of [1, 2, 3, 4] results in [1, 3, 6, 10].
You can compute this using np.cumsum():
Program:
import numpy as np
arr = np.array([1, 2, 3])
newarr = np.cumsum(arr)
print(newarr)
arr = np.array([1, 2, 3])
newarr = np.cumsum(arr)
print(newarr)