You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何无需np.set_printoptions修改NumPy数组浮点精度以做相等校验

压缩NumPy数组浮点精度用于相等性检查

要处理NumPy数组的浮点精度(非打印用途,仅用于相等性检查),无需修改全局打印选项,直接对数组数值做舍入/截断处理即可,以下是几种实用方法:

方法1:四舍五入到指定小数位

使用np.round()函数直接对数组元素进行四舍五入,指定保留的小数位数:

import numpy as np
e = np.array([0.8292222222222225, 0.1310000000000003])

# 四舍五入到6位小数
rounded_e = np.round(e, 6)
print(rounded_e)  # 输出: [0.829222 0.131   ]

# 此时可直接与目标数组比较
other_e = np.array([0.829222, 0.131])
print(np.array_equal(rounded_e, other_e))  # 输出: True

方法2:自定义截断/进位

如果需要严格截断或向上/向下进位(而非四舍五入),可以通过「乘法+取整+除法」实现:

# 向上取整到6位小数
ceil_e = np.ceil(e * 1e6) / 1e6
print(ceil_e)  # 输出: [0.829223 0.131001]

# 向下截断到6位小数
floor_e = np.floor(e * 1e6) / 1e6
print(floor_e)  # 输出: [0.829222 0.131   ]

方法3:直接容差比较(无需修改数组)

如果只是为了做相等性检查,推荐使用np.allclose()函数,通过指定容差避免浮点误差带来的判断错误,无需修改原数组:

# 检查两个数组是否在1e-6的容差范围内相等
print(np.allclose(e, other_e, atol=1e-6))  # 输出: True

内容的提问来源于stack exchange,提问作者Majoris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 21:06:09