How to Use round in NumPy: Syntax and Examples
Use
numpy.round(array, decimals) to round elements of a NumPy array to a specified number of decimal places. The decimals parameter controls how many digits to keep after the decimal point, defaulting to 0 for rounding to the nearest integer.Syntax
The numpy.round function rounds each element in an array to the specified number of decimals.
array: The input NumPy array or number to round.decimals: Number of decimal places to round to (default is 0).
python
numpy.round(array, decimals=0)
Example
This example shows how to round a NumPy array of floats to 2 decimal places and to the nearest integer.
python
import numpy as np arr = np.array([3.14159, 2.71828, 1.61803]) rounded_two_decimals = np.round(arr, 2) rounded_integer = np.round(arr) print("Original array:", arr) print("Rounded to 2 decimals:", rounded_two_decimals) print("Rounded to nearest integer:", rounded_integer)
Output
Original array: [3.14159 2.71828 1.61803]
Rounded to 2 decimals: [3.14 2.72 1.62]
Rounded to nearest integer: [3. 3. 2.]
Common Pitfalls
One common mistake is forgetting that decimals defaults to 0, so np.round(arr) rounds to integers. Another is expecting np.round to modify the original array; it returns a new array instead. Also, rounding floating-point numbers can sometimes produce unexpected results due to binary representation.
python
import numpy as np arr = np.array([2.675, 2.685]) # Wrong: expecting in-place change np.round(arr, 2) print("Array after np.round call:", arr) # Right: assign the result rounded = np.round(arr, 2) print("Rounded array:", rounded)
Output
Array after np.round call: [2.675 2.685]
Rounded array: [2.67 2.69]
Quick Reference
Remember these tips when using numpy.round:
- Input: array or number
- decimals: number of digits after decimal (can be negative to round to tens, hundreds, etc.)
- Returns: new array with rounded values
- Does not modify original array
Key Takeaways
Use numpy.round(array, decimals) to round array elements to desired decimal places.
The decimals parameter defaults to 0, rounding to nearest integer.
numpy.round returns a new array; it does not change the original array.
Negative decimals round to tens, hundreds, etc., e.g., decimals=-1 rounds to nearest 10.
Floating-point rounding can have small precision quirks due to binary representation.