【问题标题】:Why in Python 1.0 == 1 >>> True; -2.0 == -2 >>> True and etc.?为什么在 Python 1.0 == 1 >>> True; -2.0 == -2 >>> 真等等?
【发布时间】:2014-02-16 23:24:19
【问题描述】:

我想设置比数字必须是整数的条件。并且 x == int(x) 在 x == 1.0 的情况下无济于事...... 谢谢。

【问题讨论】:

  • 为什么不是真的?
  • 您的意思是要确保 x 是一个整数?
  • @Keith Integer 可能是合适的 - 1.0 也是一个整数。
  • 浮点数不是数学定义;这是一种表示实数子集(包括整数)的方式。整数有不同的定义,但它们的区别仅在于包含哪些整数。如果一个数字是一个整数,它就是一个整数。
  • @chepner 这被标记为“python”而不是“数学理论”。 Python 中的整数定义明确,与浮点数来自不同的域。

标签: python python-2.7 floating-point integer


【解决方案1】:

Python 将整数值转换成它的等值的实数,然后检查这两个值,因此在检查值等价时答案为真,但如果检查类型等价则答案为假。

【讨论】:

    【解决方案2】:

    在 python 上不大,但我用这个来检查:

    i = 123
    f = 123.0
    
    if type(i) == type(f) and i == f:
        print("They're equal by value and type!")      
    elif type(i) == type(f):
        print("They're equal by type and not value.")
    elif i == f:
        print("They're equal by value and not type.")
    else:
        print("They aren't equal by value or type.")
    

    返回:

    They're equal by value and not type.
    

    【讨论】:

    • @downvoter 这个答案有什么问题?它编译并回答问题。
    • 我没有否决,但这可能是因为在 Python 中不鼓励检查绝对类型。太精确了。它不考虑 Python 2 中的两种整数类型或任何子类。 isinstance() 通常是你想要的。
    【解决方案3】:

    只要检查它是否是一个整数。

    >>> def int_check(valuechk, valuecmp):
            if valuechk == valuecmp and type(valuechk) == int:
                    return True
            else:
                    return False
    
    >>> int_check(1, 1)
    True
    >>> int_check(1.0, 1)
    False
    

    【讨论】:

      【解决方案4】:
      isinstance(x, (int, long))
      

      isinstance 测试第一个参数是否是第二个参数指定的类型的实例。我们指定(int, long) 来处理Python 自动切换到longs 以​​表示非常大的数字的情况,但如果您确定要排除longs,可以使用int。有关详细信息,请参阅docs

      至于为什么1.0 == 1,是因为1.01代表同一个数字。 Python 并不要求两个对象必须具有相同的类型才能被视为相等。

      【讨论】:

      • 或者如果你也想接受Python整数接口的第三方实现,可以isinstance(x, numbers.Integral)。例如gmpy。附带好处,它也适用于 Python 3。
      猜你喜欢
      • 2014-07-04
      • 1970-01-01
      • 2013-01-05
      • 1970-01-01
      • 1970-01-01
      • 2013-08-17
      • 2022-04-12
      • 2021-10-08
      • 2016-09-17
      相关资源
      最近更新 更多