簡體   English   中英

為什么在同樣的環境下結果會不同?

[英]Why is the result different in the same environment?

我有以下功能:

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()函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM