簡體   English   中英

為什么round(x)和round(np.float64(x))之間有區別?

[英]Why is there a difference between round(x) and round(np.float64(x))?

據我了解,2.675和numpy.float64(2.675)都是相同的數字。 但是,round(2.675,2)得到2.67,而round(np.float64(2.675),2)得到2.68。 為什么會這樣?

import numpy as np
from decimal import Decimal

x = 2.675
np_x = np.float64(x)
type(x) # float
Decimal(x)    # Decimal('2.67499999999999982236431605997495353221893310546875')
Decimal(np_x) # Decimal('2.67499999999999982236431605997495353221893310546875')
x == np_x # True

# This is the bit that bothers me
round(x, 2) # 2.67
round(np_x, 2) # 2.68

# Using numpy's round gives 2.68 for both the numpy float as well as the Python built-in float...
np.round(x, 2) # 2.68
np.round(np_x, 2) # 2.68

# ... but this is because it might be converting the number to a numpy float before rounding
type(np.round(x, 2)) # numpy.float64

# Versions
# Python 3.6.8 running on 64-bit Windows 10
# Numpy 1.16.2

一個非常有趣的問題:)看起來它與以5結尾的數字有關。

# list of incoherences between Python Numpy with round(x, 2)
for i in range(1001):
    x = i/1000
    np_x = np.float64(x)
    if round(x, 2) != round(np_x, 2):
        print(x)

# 0.005
# 0.015
# 0.025   <<< some values are missing!
# 0.065
# 0.075
# 0.085
# ...

暫無
暫無

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

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