user1699124
user1699124

Reputation: 1

How to determine if a float is within a specific range in Python

In order to determine if an input x is within 1.6 and 1.9 I tried the following:

def function(x)    
    if(x >= 1.6 & x <= 1.9):
        return True
    else
        return False

The problem here is that when you put a number that is really close to 1.6 or 1.9 then this does not work properly. E.g. 1.5999999999999999999999 will be evaluated as 1.6 and hence the function return True even though it is not in the range(1.6 - 1.9). I have tried a few other ways, but I can't get away with this rounding problem.

Can someone think of a way to do this?

Upvotes: 0

Views: 719

Answers (2)

Blckknght
Blckknght

Reputation: 104712

It is not possible to achieve perfectly accurate comparisons of numbers when using float values in Python. This is because floating point values are inherently limited in precision.

In your example, the number 1.5999999999999999999999 will have the same floating point representation as 1.6 (as mentioned by nneonneo in a comment). What may be more surprising to you is that the floating point representation is not exactly equal to either of the source numbers (to 20 decimal places, it is 1.60000000000000008882). Python conceals this a bit from you, since if you print the number out it will display 1.6 even though it is slightly larger.

The extra bit at the end is rounding error, because there is not any non-repeating binary representation of 1.6. Just like one third can only be represented exactly by an infinitely repeating decimal, 1.6 requires an infinite number of bits to represent exactly in binary. The error comes from stopping the representation after a certain number of digits and rounding the rest (like representing 1/3 as 0.333333, and rounding down the rest of the repeating 3s).

There are a number of ways that you can write code to mitigate the effects of floating point errors, but you can't make them go away entirely, except, I suppose, by not using floating point values for situations where extremely high precision is required. In Python, if you want more precision (at the cost of some performance) you can instead use the Decimal class from the standard library:

from decimal import Decimal

d1 = Decimal("1.5999999999999999999999")
d2 = Decimal("1.6")

print(d1 >= d2) # prints: False

Upvotes: 3

pepr
pepr

Reputation: 20762

This is general problem when working with float types in all languages. If you really want to know the precision of the float used in your Python on the machine, you can use sys.float_info.epsilon -- see http://docs.python.org/library/sys.html#sys.float_info. It shows the following in my case:

Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.float_info.epsilon
2.220446049250313e-16

Upvotes: 0

Related Questions