f707dc9f5b3a0e941ab980a3903805e489c91c21
[ardour.git] / libs / pbd / pbd / floating.h
1 /* Taken from
2  * http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
3  *
4  * Code assumed to be in the public domain.
5  */
6
7 #ifndef __libpbd__floating_h__
8 #define __libpbd__floating_h__
9
10 namespace PBD {
11
12 union Float_t
13 {
14     Float_t (float num = 0.0f) : f(num) {}
15
16     // Portable extraction of components.
17     bool    negative() const { return (i >> 31) != 0; }
18     int32_t raw_mantissa() const { return i & ((1 << 23) - 1); }
19     int32_t raw_exponent() const { return (i >> 23) & 0xFF; }
20  
21     int32_t i;
22     float f;
23 };
24  
25 /* Note: ULPS = Units in the Last Place */
26
27 static inline bool floateq (float a, float b, int max_ulps_diff)
28 {
29     Float_t ua(a);
30     Float_t ub(b);
31  
32     // Different signs means they do not match.
33     if (ua.negative() != ub.negative()) {
34         // Check for equality to make sure +0==-0
35             if (a == b) {
36                     return true;
37             }
38             return false;
39     }
40  
41     // Find the difference in ULPs.
42     int ulps_diff = abs (ua.i - ub.i);
43
44     if (ulps_diff <= max_ulps_diff) {
45         return true;
46     }
47  
48     return false;
49 }
50
51 } /* namespace */
52
53 #endif /* __libpbd__floating_h__ */