Reputation: 9321
In Python, how can I check if a floating point number is approximately a whole number, with a user-specified maximum difference?
I am thinking of something like is_whole(f, eps)
, where f
is the value in question and eps
is the allowed maximum deviation, with the following results:
>>> is_whole(1.1, 0.05)
False
>>> is_whole(1.1, 0.2)
True
>>> is_whole(-2.0001, 0.01)
True
Upvotes: 1
Views: 715
Reputation: 410
I would probably just write a function doing this myself.
def is_whole(f, eps):
whole_number = round(f)
deviation = abs(eps)
return whole_number - deviation <= f <= whole_number + deviation
I wrote this on the fly, if there are mistakes please tell me! Hope I could help.
Upvotes: 1
Reputation: 9321
One solution I came up with is
def is_whole(f, eps):
return abs(f - round(f)) < abs(eps)
but I am not sure if there is a more pythonic way to do this.
EDIT
Use abs(eps)
instead of just eps
to avoid silent misbehavior.
Upvotes: 5