NumPy rint()

The numpy.rint() function rounds each element in an input array to the nearest integer while maintaining the original data type.

Syntax

</>
Copy
numpy.rint(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)

Parameters

ParameterTypeDescription
xarray_likeInput array containing floating-point numbers.
outndarray, None, or tuple of ndarray and None, optionalOptional output array to store the results. If None, a new array is created.
wherearray_like, optionalBoolean mask that specifies where rounding should be applied.
castingstr, optionalDefines the casting behavior when computing the function.
orderstr, optionalMemory layout order of the output array.
dtypedata-type, optionalSpecifies the data type of the output array.
subokbool, optionalDetermines if subclasses of ndarray are preserved in the output.

Return Value

Returns an array with elements rounded to the nearest integer. If the input is a scalar, a scalar is returned.


Examples

1. Rounding a Single Floating-Point Number

This example demonstrates how numpy.rint() rounds a single number to the nearest integer.

</>
Copy
import numpy as np

# Define a floating-point number
num = 3.6  

# Compute the rounded value
rounded_value = np.rint(num)

# Print the result
print("Rounded value:", rounded_value)

Output:

Rounded value: 4.0

2. Rounding an Array of Floating-Point Numbers

We apply numpy.rint() to an array of floating-point numbers to round each element to the nearest integer.

</>
Copy
import numpy as np

# Define an array of floating-point numbers
arr = np.array([1.2, 2.5, 3.7, -1.8, -2.3])

# Compute the rounded values
rounded_array = np.rint(arr)

# Print the results
print("Original array:", arr)
print("Rounded array:", rounded_array)

Output:

Original array: [ 1.2  2.5  3.7 -1.8 -2.3]
Rounded array: [ 1.  2.  4. -2. -2.]

3. Using the out Parameter

Using an output array to store the results instead of creating a new array.

</>
Copy
import numpy as np

# Define an array of floating-point numbers
arr = np.array([0.4, 1.9, 2.2, -3.5])

# Create an empty output array
output_array = np.empty_like(arr)

# Compute the rounded values and store in output_array
np.rint(arr, out=output_array)

# Print the results
print("Rounded values:", output_array)

Output:

Rounded values: [ 0.  2.  2. -4.]

4. Using the where Parameter

Using a condition to apply rounding only to selected elements.

</>
Copy
import numpy as np

# Define an array of floating-point numbers
arr = np.array([1.1, 2.6, 3.3, 4.7])

# Define a condition (only round numbers greater than 3)
mask = arr > 3

# Compute the rounded values where the condition is met
result = np.rint(arr, where=mask)

# Print the results
print("Rounded values with condition:", result)

Output:

Rounded values with condition: [0. 0. 3. 5.]

The function rounds only elements greater than 3.