python - 为什么在相同的环境下结果会不同?
问题描述
我有以下功能:
import numpy as np
my_rects = np.array([[ 518, 792, 646, 1080]])
relative_rects = np.array([[ 16, 53, 116, 286.]])
crops_width = my_rects[:, 2] - my_rects[:, 0]
crops_height = my_rects[:, 3] - my_rects[:, 1]
def expand_rects(rects, img_width, img_height, width_ratio, height_ratio, epsilon=1e-5):
W = rects[:, 2] - rects[:, 0]
H = rects[:, 3] - rects[:, 1]
center_x = (rects[:, 0] + rects[:, 2]) / 2
center_y = (rects[:, 1] + rects[:, 3]) / 2
res = np.zeros_like(rects, dtype='float32')
res[:, 0] = center_x - W * width_ratio / 2
res[:, 2] = center_x + W * width_ratio / 2
res[:, 1] = center_y - H * height_ratio / 2
res[:, 3] = center_y + H * height_ratio / 2
res[:, 0] = np.clip(res[:, 0], 0, img_width)
res[:, 2] = np.clip(res[:, 2], 0, img_width)
res[:, 1] = np.clip(res[:, 1], 0, img_height)
res[:, 3] = np.clip(res[:, 3], 0, img_height)
return res
print(expand_rects(relative_rects, crops_width, crops_height, 1.2, 1.1 ))
运行此程序后,我得到了以下结果:
5.999996 41.34999 126. 288.
但是,第一个元素应该是 6.0 而不是 5.999996(66−1.2×(116−16)÷2 = 6)。更重要的是,如果我将函数放入另一个大文件中,输入相同,输出变为:
6. 41.35 126. 288.
我的环境是:
Linux (none) 4.9.37 #1 SMP Tue Nov 13 10:04:52 CST 2018 armv7l GNU/Linux
root@(none):/jkklklk/projects/# python3
Python 3.7.3 (default, Apr 3 2019, 05:39:12)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
对此有解释吗?我真的需要结果稳定(每次都应该是 5.9999996)。
解决方案
表示浮点值是一些计算机语言(包括 Python)的一个非常古老的问题。您可以在官方文档中阅读更多内容:https ://docs.python.org/3/tutorial/floatingpoint.html
它的这个特定部分可能会给你一个提示:
由于值的显示方式,许多用户不知道近似值。Python 只打印机器存储的二进制近似值的真实十进制值的十进制近似值。在大多数机器上,如果 Python 要打印存储为 0.1 的二进制近似值的真实十进制值,它必须显示:
>>> 0.1
>>>
0.1000000000000000055511151231257827021181583404541015625
最后,如果您想获得一致的输出,则必须将其转换为整数或使用round()
function。
推荐阅读
- python - 编译 TensorFlow 模型时定义 BLEU
- java - 如何在没有切换案例的情况下从 json 列表中实例化一组不同的对象?
- javascript - 完整日历 v5。做出反应。如何添加自定义列
- websphere - C9510-401 IBM WAS Network Deployment V8.5.5 和 Liberty Profile 认证
- r - ggplot2 for-loop 设置预定的不透明度
- javascript - 通过 XMLHttpRequest (API) 在 HTML 表上显示请求结果
- kubernetes - K8s 中针对 Pod 失败的警报
- javascript - 如何在反应中按百分比滚动?
- spring - 春季启动上下文创建错误,以防在春季 Redis 集群配置中无法访问一个主节点
- c++ - 如何使用 nlohmann json 解析对象数组?