为什么结果在同一环境中会有所不同?

时间:2020-02-28 04:48:57

标签: python python-3.x

我具有以下功能:

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)。

1 个答案:

答案 0 :(得分:0)

在某些计算机语言(包括Python)中,表示浮点值是一个非常老的问题。您可以在官方文档https://docs.python.org/3/tutorial/floatingpoint.html

中阅读更多内容。

其中的这一特定部分可能会给您提示:

由于显示值的方式,许多用户不了解近似值。 Python仅将十进制近似值打印到机器存储的二进制近似值的真实十进制值。在大多数机器上,如果Python要打印存储为0.1的二进制近似值的真实十进制值,则必须显示:

>>> 0.1
>>>
0.1000000000000000055511151231257827021181583404541015625

最后,如果要获得一致的输出,则必须将其强制转换为整数或使用round() function