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:
print "Distance: %s Radius: %s" % (distance(lat1, long1, lat2, long2), radius)
Here distance would effectively return a float and radius is an int.
I do know that I should not compare floats directly and that I should compare with a threshold. Given that, is there a better way to check if a float is less than an int (or another float).
Update
This comparison seems to be ok from all of the replies. But I did observe this:
>>> 1.2000000000000001 > 1.2
True
>>> 1.20000000000000001 > 1.2
False
Isn’t this a problem? I am using Python 2.6.7 on Mac
Just compare them directly, there is no harm in that at all.
Python handles comparing numbers of different types perfectly well:
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:
But in comparing to
ints and/or<or>operations, you shouldn’t worry.In your update, we can use the
decimalmodule to show the cause:But does this really matter? It’s an inherent problem with floating point numbers, but only matters where you need really high precision.