NumPy Mathematical Functions
NumPy provides a rich collection of mathematical functions for performing calculations on individual values and entire arrays. These functions make numerical programs faster, cleaner, and easier to maintain. In this lesson, you will learn how to perform arithmetic calculations, calculate powers and square roots, work with absolute values, and apply common mathematical functions to arrays.
1. Introduction to Mathematical Functions
Mathematical functions perform operations such as addition, subtraction, multiplication, division, exponentiation, and square-root calculation. NumPy functions can operate directly on arrays without requiring you to write a separate loop for every element.
Why Use NumPy Mathematical Functions?
- Perform calculations on complete arrays.
- Reduce the need for manual loops.
- Write concise and readable numerical code.
- Use consistent operations on NumPy arrays.
- Combine mathematical functions in data analysis workflows.
Output:
Here, NumPy adds five to every element in the array. The original array remains unchanged because the result is assigned to a new variable.
2. Basic Arithmetic Operations
NumPy supports the standard arithmetic operators. When these operators are applied to compatible arrays, the operation is performed element by element.
| Operation | Operator | NumPy Example | Result |
|---|---|---|---|
| Addition | + |
a + b |
[11, 22, 33] |
| Subtraction | - |
a - b |
[-9, -18, -27] |
| Multiplication | * |
a * b |
[10, 40, 90] |
| Division | / |
a / b |
[0.1, 0.1, 0.1] |
| Exponentiation | ** |
a ** 2 |
Squares each element |
| Remainder | % |
a % b |
Element-wise remainders |
Output:
np.add(), np.subtract(), and
np.multiply().
3. Using NumPy Arithmetic Functions
Named arithmetic functions provide an alternative to operators. They are useful when you want to make the purpose of an operation explicit in your code.
Output:
Common Arithmetic Functions
| Function | Purpose |
|---|---|
np.add(a, b) |
Adds corresponding elements. |
np.subtract(a, b) |
Subtracts corresponding elements. |
np.multiply(a, b) |
Multiplies corresponding elements. |
np.divide(a, b) |
Divides corresponding elements. |
np.remainder(a, b) |
Calculates the remainder for corresponding elements. |
np.power(a, b) |
Raises each element of a to the corresponding power in b. |
4. Square Roots and Powers
NumPy provides functions for calculating square roots and powers. These operations are frequently used in geometry, scientific calculations, statistics, and data processing.
Square Root with np.sqrt()
Output:
Power with np.power()
Output:
Each element in bases is raised to the power at the same
position in powers.
NumPy applies square-root and power calculations element by element.
5. Absolute Values and Sign Functions
The absolute value represents the distance of a number from zero, without
considering its sign. The np.abs() function calculates
absolute values, while np.sign() identifies whether each
value is negative, zero, or positive.
Output:
| Function | Meaning | Example |
|---|---|---|
np.abs() |
Returns absolute values. | np.abs(-8) returns 8. |
np.sign() |
Returns the sign of a value. | Negative values return -1, zero returns 0, and positive values return 1. |
6. Exponential and Logarithmic Functions
Exponential functions calculate powers of a base, while logarithmic functions help determine the exponent associated with a value. They are useful in scientific computing, growth calculations, and numerical models.
Exponential Calculation
Output:
The np.exp() function calculates \(e^x\) for each element,
where \(e\) is approximately 2.71828.
Natural Logarithm
Output:
Other Logarithmic Functions
| Function | Description |
|---|---|
np.log() |
Natural logarithm (base e). |
np.log10() |
Logarithm with base 10. |
np.log2() |
Logarithm with base 2. |
np.exp() |
Exponential function with base e. |
np.exp2() |
Calculates powers of 2. |
7. Rounding Mathematical Values
Rounding functions change the precision or integer direction of numerical values. They are helpful when displaying results or preparing numerical data for further processing.
Output:
| Function | Behavior |
|---|---|
np.round() |
Rounds to the nearest value, using ties-to-even for exact halfway cases. |
np.floor() |
Rounds down toward negative infinity. |
np.ceil() |
Rounds up toward positive infinity. |
np.trunc() |
Removes the fractional part by moving toward zero. |
-2.7 is -3,
while its truncated value is -2.
8. Working with Remainders and Quotients
NumPy provides functions for calculating the remainder and quotient of division. These are useful when dividing values into groups, checking divisibility, and performing integer-based calculations.
Output:
np.remainder() returns the remainder after division.
np.floor_divide() returns the quotient rounded down toward
negative infinity.
9. Applying Multiple Functions to an Array
Mathematical functions can be combined to create a calculation pipeline. Each step can use the result of the previous operation.
Example: Processing Student Marks
Samadhan, Pradnya, and Samiksha receive marks in a test. We will add bonus marks, calculate the square root of the updated values, and round the results for display.
Output:
NumPy performs the numerical calculations on the arrays. The loop is used only to display each student's name alongside the calculated values.
10. Common Mistakes and Best Practices
Check Array Compatibility
Element-wise operations require compatible array shapes. NumPy broadcasting allows some differently shaped arrays to work together, but incompatible shapes raise an error.
Understand Division by Zero
Division by zero in floating-point arrays can produce infinity or NaN and may generate a warning. Integer division has different constraints and may raise an error.
Use Appropriate Input Values
Functions such as square root and logarithm have domain restrictions when working with real-valued data. Check whether your inputs are appropriate for the calculation.
Keep Precision in Mind
Floating-point results may contain small representation differences.
Use np.round() for presentation when needed, but avoid
rounding intermediate calculations unnecessarily.
Output:
11. Practice Exercises
Exercise 1: Basic Calculations
Create an array containing [12, 18, 24, 30]. Add 5 to
every element, multiply the result by 2, and print the final array.
Exercise 2: Square Roots and Powers
Create an array containing [9, 16, 25, 49]. Calculate
its square roots and squares using NumPy functions.
Exercise 3: Absolute Values
Use np.abs() on [-12, -5, 0, 7, 15].
Then use np.sign() to inspect the signs.
Exercise 4: Rounding
Apply np.round(), np.floor(),
np.ceil(), and np.trunc() to
[3.2, 3.8, -3.2, -3.8]. Compare the outputs.
Exercise 5: Combined Mathematical Operations
Create an array of prices [120, 250, 480]. Apply a
10 percent increase, calculate the square root of the updated prices,
and round the results to two decimal places.
Summary
NumPy mathematical functions provide efficient ways to calculate values across arrays. They support basic arithmetic, powers, square roots, absolute values, exponential and logarithmic operations, rounding, quotients, and remainders.
- Use arithmetic operators or functions such as
np.add()andnp.multiply(). - Use
np.sqrt()for square roots andnp.power()for exponentiation. - Use
np.abs()andnp.sign()to examine numeric values. - Use
np.exp()and logarithmic functions for exponential calculations. - Use
np.round(),np.floor(),np.ceil(), andnp.trunc()according to the required rounding behavior. - Check input values, array shapes, and numerical precision when performing calculations.
These functions form the foundation for more advanced NumPy topics, including statistical analysis, data filtering, and numerical computing.