gpt4 book ai didi

python - 为什么 round(x) 和 round(np.float64(x)) 有区别?

转载 作者:太空狗 更新时间:2023-10-29 21:10:29 25 4
gpt4 key购买 nike

据我了解,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 结尾的数字有关。Numpy 将它们四舍五入,但并不总是……

# 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
# ...

关于python - 为什么 round(x) 和 round(np.float64(x)) 有区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55994184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com