Python浮点数比较 [英] Python floating point number comparison

查看:162
本文介绍了Python浮点数比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  2.2 * 3.0我刚刚回顾了一些Python的基本知识,还有一个比较棘手的问题。 == 6.6 
3.3 * 2.0 == 6.6

我认为这些都会返回一个False 。然而,第二个给了我一个真实的。



请帮我在这里感谢!

解决方案



 >>> float.hex(2.2 * 3.0)
'0x1.a666666666667p + 2'
>>> float.hex(3.3 * 2.0)
'0x1.a666666666666p + 2'
>>> float.hex(6.6)
'0x1.a666666666666p + 2'

尽管它们都是以十进制形式显示为 6.6 ,当您检查内部表示时,其中两个以相同的方式表示,而其中一个不是。


I'm just reviewing some basics of Python and there's a tricky problem about comparing floating point numbers.

2.2 * 3.0 == 6.6
3.3 * 2.0 == 6.6

I thought these should both return a False. However, the second one gave me a True.

Please help me here. Thanks!

解决方案

This might be illuminating:

>>> float.hex(2.2 * 3.0)
'0x1.a666666666667p+2'
>>> float.hex(3.3 * 2.0)
'0x1.a666666666666p+2'
>>> float.hex(6.6)
'0x1.a666666666666p+2'

Although they are all displayed in decimal as 6.6, when you inspect the internal representation, two of them are represented in the same way, while one of them is not.

这篇关于Python浮点数比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆