I am now implementing a function that requires the input list lst
to be a distribution, which means sum(lst)
is equal to 1.
In the code, I use assert
statement
assert sum(lst) == 1, "the lst has to be a distribution"
However, as elements in lst
will all be floating numbers, I am not sure whether sum(lst) == 1
will be violated for some subtle cases because of machine precision. To be more specific, I guess my question is
- How
==
is implemented in the very low level. What is the tolerance for comparing two floating numbers? Does this value vary machine from machine (for example, the set of values returned bysys.float_info
)? - When is the good practice of using
==
. Besides comparing two floating numbers, are there other similar cases that warrant extra attention (for example, comparing strings, objects, etc).