gpt4 book ai didi

python - 如何确定小数是否可以完全表示为 Python float?

转载 作者:行者123 更新时间:2023-11-28 20:41:04 24 4
gpt4 key购买 nike

来自 Python tutorial :

Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine.

我想知道如何检查给定的小数是否会精确表示为 Python float。例如,0.25 可以精确表示,而 0.1 不能:

>>> 0.1 + 0.1 + 0.1 == 0.3
False
>>> 0.25 + 0.25 + 0.25 == 0.75
True

最佳答案

在那个页面上:

On most machines today, floats are approximated using a binary fraction with the numerator using the first 53 bits starting with the most significant bit and with the denominator as a power of two.

因此,要使小数精确表示为 float,它必须是分母为 2 的幂的分数:

>>> 1/10 + 1/10 + 1/10 == 3/10  # 0.1 + 0.1 + 0.1
False
>>> 1/4 + 1/4 + 1/4 == 3/4 # 0.25 + 0.25 + 0.25
True

关于python - 如何确定小数是否可以完全表示为 Python float?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34371807/

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