gpt4 book ai didi

Python 四舍五入不正确的结果

转载 作者:行者123 更新时间:2023-12-02 21:42:02 25 4
gpt4 key购买 nike

我想在 python 中对数字进行四舍五入,但它总是给我不准确的结果例如我想将 99.999999946 舍入为 99.99,或将 56.3633333 舍入为 56.36这是我尝试过的:

int(99.999999946*100)/100   #result = 99
int(99.999999946*100)/100.0 #result = 99.989999999999995
round(99.999999946, 2) #result = 100.0

先谢谢了

最佳答案

在您熟悉二进制浮点的限制之前,您可能会对 decimal 模块感到更满意,该模块实现了丰富的十进制浮点模型。除此之外,它还允许对舍入模式进行精细控制:

>>> import decimal
>>> d = decimal.Decimal("99.999999946")
>>> print d
99.999999946
>>> chopped = d.quantize(decimal.Decimal(".01"), decimal.ROUND_DOWN)
>>> print chopped
99.99

概括

这是一个函数,它将截断到您喜欢的任何数字位置,并返回一个浮点值(通常,这是不精确的!):

def chop_to_n_decimals(x, n):
# This "rounds towards 0". The decimal module
# offers many other rounding modes - see the docs.
import decimal
d = decimal.Decimal(repr(x))
targetdigit = decimal.Decimal("1e%d" % -n)
chopped = d.quantize(targetdigit, decimal.ROUND_DOWN)
return float(chopped)

例如,

for x in 5555.5555, -5555.5555:
for n in range(-3, 4):
print x, n, "->", chop_to_n_decimals(x, n)

显示:

5555.5555 -3 -> 5000.0
5555.5555 -2 -> 5500.0
5555.5555 -1 -> 5550.0
5555.5555 0 -> 5555.0
5555.5555 1 -> 5555.5
5555.5555 2 -> 5555.55
5555.5555 3 -> 5555.555
-5555.5555 -3 -> -5000.0
-5555.5555 -2 -> -5500.0
-5555.5555 -1 -> -5550.0
-5555.5555 0 -> -5555.0
-5555.5555 1 -> -5555.5
-5555.5555 2 -> -5555.55
-5555.5555 3 -> -5555.555

关于Python 四舍五入不正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20257683/

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