python - 如何打印 float 的全精度 [Python]

标签 python python-2.7 floating-point

我编写了以下函数,其中传递了 x,y 的值:

def check(x, y):
    print(type(x))
    print(type(y))
    print(x)
    print(y)
    if x == y:
        print "Yes"

现在当我打电话check(1.00000000000000001, 1.0000000000000002)它正在打印:
<type 'float'>
<type 'float'>
1.0
1.0

现在从变量 x & y 的打印语句中,我很难调试为什么 x != y (尽管两者都打印相同的值)。虽然我通过打印 x - y 解决了它,这给了我不同的但有什么方法可以修改打印语句,以便在不使用任何外部打印库和减法解决方案的情况下知道为什么 x!=y 在这个特定用例中。

最佳答案

要获得完全精确和正确的格式,请执行以下操作

format(2**(1/2), '.60g') 
# -> '1.4142135623730951454746218587388284504413604736328125'

并检查它
import decimal
print(decimal.Decimal.from_float(2**(1/2))
# -> '1.4142135623730951454746218587388284504413604736328125'
g格式类型在需要时切换为指数表示法。

关于python - 如何打印 float 的全精度 [Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52531262/

相关文章:

Python for 循环中的线程

PHP 使用参数参数在服务器上运行可执行文件

python-2.7 - 如何在python中附加日志

math - float 学坏了吗?

python - 自动化轮类时间,同时考虑限制

python - 如何用Python中的美丽汤替换html页面中的特定文本行

python - cv2.line 和 cv2.circle 返回 None

floating-point - JPEG-XL:无损模式支持32位浮点吗?

c++ - 如何在不损失精度的情况下正确表示 float 中的大数值

for循环中的Python默认变量