Comparing a float and an int in Python

前端 未结 1 1069
小鲜肉
小鲜肉 2020-12-18 05:24

I am trying to see if the calculated distance between two points is smaller than a given radius like this:

if distance(lat1, long1, lat2, long2) < radius:         


        
相关标签:
1条回答
  • 2020-12-18 05:51

    Just compare them directly, there is no harm in that at all.

    Python handles comparing numbers of different types perfectly well:

    >>> type(1.1)
    <class 'float'>
    >>> type(1)
    <class 'int'>
    >>> 1.1 > 1
    True
    >>> 1.1 < 1
    False
    >>> 1 < 2
    True
    >>> 2.2 == 2.2
    True
    >>> 2 == 2.2
    False
    >>> 1.6 < 2
    True
    >>> 1.6 > 2
    False
    >>> 1.6 == 2
    False
    

    Python is duck typed, so in general you shouldn't worry about types directly, just if they can work in the way you need.

    There could be some issues with comparing floats for equality with other floats due to precision errors:

    >>> 0.3+0.3+0.3 == 0.9
    False
    >>> 0.3+0.3+0.3
    0.8999999999999999
    

    But in comparing to ints and/or < or > operations, you shouldn't worry.

    In your update, we can use the decimal module to show the cause:

    >>> Decimal(1.2000000000000001)
    Decimal('1.20000000000000017763568394002504646778106689453125')
    >>> Decimal(1.20000000000000001)
    Decimal('1.1999999999999999555910790149937383830547332763671875')
    

    But does this really matter? It's an inherent problem with floating point numbers, but only matters where you need really high precision.

    0 讨论(0)
提交回复
热议问题