forked from turian/common
-
Notifications
You must be signed in to change notification settings - Fork 0
/
floateq.py
49 lines (43 loc) · 1.49 KB
/
floateq.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#
# Determine if floating point numbers are very close
###########
import math
DEFAULT_SANITY_CHECK_EPSILON = 1e-6
def floateq(a, b, epsilon=DEFAULT_SANITY_CHECK_EPSILON):
"""
Compare two floats, with some epsilon tolerance.
"""
return absolute_relative_error(a, b) < epsilon
def absolute_relative_error(a, b, epsilon=DEFAULT_SANITY_CHECK_EPSILON):
return abs(a - b) / (abs(a) + abs(b) + epsilon)
def double_epsilon_multiplicative_eq(a, b, epsilon=DEFAULT_SANITY_CHECK_EPSILON):
"""
Determine if doubles are equal to within a multiplicative factor of
L{epsilon}.
@note: This function should be preferred over
L{double_epsilon_additive_eq}, unless the values to be compared may
have differing signs.
@precondition: sign(a) == sign(b)
@rtype: bool
"""
if a == b: return True
if a == 0 and b == 0: return True
assert a != 0
assert b != 0
assert sign(a) == sign(b)
if a > b: d = a / b
else: d = b / a
assert d >= 1
return d <= 1 + SANITY_CHECK_EPSILON
def double_epsilon_additive_eq(a, b):
"""
Determine if doubles are equal to within an additive factor of
L{SANITY_CHECK_EPSILON}.
@note: Prefer L{double_epsilon_multiplicative_eq} to this function
unless the values to be compared may have differing signs.
"""
if a == b: return True
if a == 0 and b == 0: return True
assert sign(a) != sign(b) # Should use SANITY_CHECK_EPSILON
d = math.fabs(a - b)
return d <= SANITY_CHECK_EPSILON