f 字符串格式中应用什么类型的舍入?

问题描述 投票:0回答:1

下面的 f 字符串格式应用了哪种类型的舍入?

List = [0.0505, 0.0515, 0.0525, 0.0535, 0.0545, 
     0.0555, 0.0565, 0.0575, 0.0585, 0.0595]

print(['{:.3f}'.format(p) for p in List])

# result
# ['0.051', '0.051', '0.052', '0.053', '0.054', 
# '0.056', '0.057', '0.058', '0.059', '0.059']

# '''
# third decimal place

# number 0: 0 to 1
# -------------------------
# number 1: 1 in 1
# number 2: 2 in 2
# number 3: 3 in 3
# number 4: 4 in 4
# -------------------------
# number 5: 5 to 6
# number 6: 6 to 7
# number 7: 7 to 8
# number 8: 8 to 9
# -------------------------
# number 9: 9 in 9 

# '''

对称性似乎暗示着一种特殊的类型。

我期望得到像 numpy.round(List,3) 这样的结果

数组([0.05,0.052,0.052,0.054,0.054,0.056,0.056,0.058,0.058,0.06])

python format rounding f-string
1个回答
0
投票

在您提供的 f 字符串格式中:

print(['{:.3f}'.format(p) for p in List])

格式采用 round half to Even 四舍五入,也称为 banker's roundingrounding to the 最接近的偶数

以下是它如何与您的示例配合使用:

  • 0.0505 四舍五入为 0.051,因为它是 0.050 和 0.051 之间的中间值。
  • 0.0515 也舍入为 0.051,因为它比 0.052 更接近 0.051。
  • 0.0525 四舍五入为 0.052,因为它是 0.052 和 0.053 之间的中间值。
  • 0.0535 舍入为 0.054,因为它比 0.053 更接近 0.054。

您期望的行为,类似于使用

传统舍入
numpy.round(List, 3),确实会给您带来不同的结果。在传统舍入中,如果小数部分大于或等于 0.5,则数字向上舍入,否则向下舍入。这将产生您在预期结果中描述的模式。

因此,总而言之,f 字符串格式使用四舍五入(银行家舍入),而不是传统舍入,这就是您得到观察到的结果的原因。

© www.soinside.com 2019 - 2024. All rights reserved.