📜  Python numpy.rint()(1)

📅  最后修改于: 2023-12-03 14:46:01.259000             🧑  作者: Mango

Python numpy.rint()

The numpy.rint() function is used to round the elements of an array to the nearest integer, element-wise. It returns the rounded values as a new array, with data type preserved.

Syntax
numpy.rint(arr, out=None)
  • arr: An array-like object containing the elements to be rounded.
  • out: (Optional) Output array to store the result. It must have the same shape as the input array.
Return Value

The function returns a new array with the same shape as the input array, where each element is rounded to the nearest integer.

Examples

Let's see a few examples to understand how the numpy.rint() function works:

import numpy as np

arr = np.array([1.2, 2.7, 3.5, 4.9, -1.2, -2.7])

result = np.rint(arr)

print(result)

Output:

[ 1.  3.  4.  5. -1. -3.]

In the above example, we first import the numpy module and create an array arr with some floating-point values. Then, we pass this array to numpy.rint() function, which rounds each element to the nearest integer. The resulting array result contains the rounded values.

Important Points
  • The numpy.rint() function uses the round-half-to-even strategy to round the values to the nearest even integer. This ensures that statistical analysis using rounded values is statistically unbiased.
  • The function handles both positive and negative values correctly.
  • If the input array has an integer data type, the result will be the same as the input array.
Conclusion

The numpy.rint() function in Python is a convenient tool for rounding array elements to the nearest integer. It is useful in various mathematical and statistical operations where rounding is required.