numpy.rint函数用于将数组中的每个元素舍入到最接近的整数。它返回一个包含四舍五入后的值的新数组。该函数是NumPy库中的一部分。
numpy.rint(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True, **kwargs)
参数
x:输入数组。
out:可选。输出数组,必须具有与输入形状相同的形状。
where:可选。条件,如果为False,将保持输出数组中的相应值。
casting:可选。定义数据类型转换的规则。
order:可选。指定输出数组的存储顺序。
dtype:可选。数据类型。
subok:可选。如果为True,则子类会传递给输出数组。
示例
以下是numpy.rint函数的一些示例:
1)基本用法
import numpy as np
# 创建一个包含小数的数组
arr = np.array([1.2, 2.5, 3.8, 4.4, 5.9])
# 使用 numpy.rint 函数
rounded_arr = np.rint(arr)
print("原数组:", arr)
print("舍入后的数组:", rounded_arr)
2)处理负数
import numpy as np
# 创建一个包含正负小数的数组
arr = np.array([-1.2, -2.5, -3.8, 4.4, 5.9])
# 使用 numpy.rint 函数
rounded_arr = np.rint(arr)
print("原数组:", arr)
print("舍入后的数组:", rounded_arr)
3)结合 out 参数
import numpy as np
# 创建一个包含小数的数组
arr = np.array([1.2, 2.5, 3.8, 4.4, 5.9])
# 创建一个与原数组形状相同的输出数组
out_arr = np.zeros(arr.shape)
# 使用 numpy.rint 函数并将结果存储在 out_arr 中
np.rint(arr, out=out_arr)
print("原数组:", arr)
print("输出数组:", out_arr)
4)结合 where 参数
import numpy as np
# 创建一个包含小数的数组
arr = np.array([1.2, 2.5, 3.8, 4.4, 5.9])
# 条件数组,指示要舍入的元素
condition = np.array([True, False, True, False, True])
# 使用 numpy.rint 函数并指定 where 参数
result = np.rint(arr, where=condition)
print("原数组:", arr)
print("条件数组:", condition)
print("舍入后的数组:", result)