Arithmetic Array Operations
Learn how to perform element-wise addition, subtraction, multiplication, division, exponentiation, and remainder operations on NumPy arrays. Understand scalar arithmetic, mathematical operators, array calculations, and common numerical errors through detailed explanations and practical examples.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Understand element-wise arithmetic operations in NumPy.
- Perform addition and subtraction on arrays.
- Multiply and divide array elements.
- Use exponentiation and remainder operators.
- Perform arithmetic between arrays and scalar values.
- Use NumPy arithmetic functions such as
np.add()andnp.multiply(). - Understand the difference between element-wise multiplication and matrix multiplication.
- Identify common arithmetic errors and handle numerical results carefully.
2. Introduction to Arithmetic Array Operations
NumPy provides arithmetic operations that work directly on arrays. These operations generally calculate results element by element, allowing you to process entire datasets without writing explicit Python loops.
For example, if two arrays contain corresponding student marks, NumPy can add or subtract the values at matching positions. The result is another array containing the calculated values.
Output:
NumPy adds the first elements, then the second elements, and continues until all corresponding elements have been processed. This is called an element-wise operation.
Each element is added to the element at the corresponding position.
3. Addition of NumPy Arrays
The addition operator + adds corresponding elements
from two arrays. It is useful for combining values such as daily
sales, student scores, expenses, or measurements.
Output:
Each total represents the sum of morning and evening sales for the corresponding position. NumPy performs these calculations across the arrays in one expression.
Using np.add()
NumPy also provides the np.add() function. It performs
the same element-wise addition as the + operator
for compatible arrays.
Output:
+ for concise arithmetic
expressions. Use np.add() when its explicit function
form improves clarity or when working with NumPy's function-based
calculation patterns.
4. Subtraction of NumPy Arrays
The subtraction operator - subtracts each element
in the second array from the corresponding element in the first
array. The order matters because subtraction is not commutative.
Output:
The result indicates the difference between the two sets of marks at each position. A negative result would mean that the first value is smaller than the corresponding second value.
Output:
a - b and b - a
usually produce different results because the order of operands
changes the calculation.
5. Multiplication of NumPy Arrays
The multiplication operator * performs element-wise
multiplication. Each value in the first array is multiplied by
the value at the corresponding position in the second array.
Output:
This example calculates the amount for each product by multiplying its quantity by its unit price. Each position in the result corresponds to one product.
Using np.multiply()
Output:
* operator
multiplies corresponding elements. Matrix multiplication uses
operations such as @ or np.matmul().
6. Division of NumPy Arrays
The division operator / divides each element of
the first array by the corresponding element of the second array.
For ordinary integer and floating-point numeric arrays, true
division generally produces floating-point results.
Output:
The operation calculates a quotient at each corresponding position. Floating-point results allow NumPy to represent fractional values when a division is not exact.
Using np.divide()
Output:
inf or nan and may
raise a runtime warning. Check the denominator when zero values
are not valid for your calculation.
Checking Denominators
Output:
In this example, division is performed only where the denominator is nonzero. The output array was initialized with zeros, so positions where the condition is false retain zero. Select a suitable fallback value for your application's requirements.
7. Exponentiation with NumPy Arrays
Exponentiation raises each element to a specified power. The
** operator performs element-wise exponentiation
when used with compatible arrays.
Output:
Each element is multiplied by itself because the exponent is two. You can use other exponents depending on the mathematical calculation you need.
Output:
The np.power() function provides an explicit
function-based way to perform element-wise exponentiation.
8. Remainder and Modulo Operations
The remainder operation returns the remainder after division.
NumPy provides the % operator and the
np.remainder() function for element-wise calculations.
Output:
For example, ten divided by three leaves a remainder of one. Fifteen divided by four leaves a remainder of three.
Checking Even and Odd Numbers
Output:
9. Arithmetic Between Arrays and Scalars
NumPy allows you to perform arithmetic between an array and a single scalar value. The scalar operation is applied to every element in the array.
Output:
Scalar arithmetic is useful when applying a constant adjustment to an entire dataset. For example, you can add a fixed bonus to marks or apply a common scaling factor to measurements.
10. Arithmetic Operations on Different Data Types
NumPy arrays have data types that influence how arithmetic operations are calculated and how results are stored. When different numeric types are combined, NumPy may promote the result to a compatible type.
Output:
The result uses a floating-point type so that fractional parts can be represented. The precise result type depends on the input dtypes and NumPy's type-promotion rules.
11. Understanding Element-Wise Multiplication and Matrix Multiplication
Element-wise multiplication and matrix multiplication are different operations. Element-wise multiplication multiplies matching elements. Matrix multiplication combines rows and columns according to linear algebra rules.
Output:
| Operation | Operator | Meaning |
|---|---|---|
| Element-wise multiplication | * |
Multiplies values at corresponding positions. |
| Matrix multiplication | @ |
Combines rows of the first matrix with columns of the second matrix. |
| Matrix multiplication function | np.matmul() |
Performs matrix multiplication using NumPy's function API. |
@,
verify that the number of columns in the first matrix equals
the number of rows in the second matrix.
12. Common Arithmetic Errors
Incompatible Array Shapes
Arithmetic between two arrays requires compatible shapes. NumPy supports broadcasting, which allows certain differently shaped arrays to work together. However, incompatible shapes produce an error.
Output:
The arrays have lengths three and two. Their shapes cannot be
aligned under NumPy's broadcasting rules, so adding them directly
would raise a ValueError.
Integer Division
When integer quotients are required, use // for
floor division. Unlike true division, floor division returns
the floor of the quotient.
Output:
13. Practical Activity
Activity: Sales and Revenue Calculations
Samadhan, Pradnya, and Samiksha are analyzing daily sales for four products. The dataset contains quantities sold, unit prices, and discounts. Use NumPy arithmetic operations to calculate revenue and adjusted values.
Tasks:
- Create arrays for product quantities and unit prices.
- Calculate total revenue for each product.
- Apply a fixed discount to each revenue value.
- Calculate the difference between original and adjusted revenue.
- Use the remainder operator to identify quantities that are even.
- Display the resulting arrays and their data types.
Sample Solution
Expected key results:
- Revenue:
[200, 450, 800, 250] - Adjusted revenue:
[190, 440, 790, 240] - Difference:
[10, 10, 10, 10] - Even quantities:
[2, 4]
Summary
In this lesson, we learned how to perform arithmetic operations on NumPy arrays using addition, subtraction, multiplication, division, exponentiation, and remainder operators. We explored the equivalent NumPy functions, including add(), subtract(), multiply(), divide(), and power(), and learned how scalar arithmetic applies a calculation to every element in an array.
We also compared element-wise multiplication with matrix multiplication, examined data type promotion, and discussed common issues such as incompatible array shapes, division by zero, and integer overflow. These operations make numerical calculations concise and efficient. Always check array shapes, data types, and denominator values when necessary to ensure that arithmetic results are appropriate for your application.