ardour
floating.h
Go to the documentation of this file.
1 /*
2  Copyright (C) 2012 Paul Davis
3 
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation; either version 2 of the License, or
7  (at your option) any later version.
8 
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  GNU General Public License for more details.
13 
14  You should have received a copy of the GNU General Public License
15  along with this program; if not, write to the Free Software
16  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 
18 */
19 
20 /* Taken from
21  * http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
22  *
23  * Code assumed to be in the public domain.
24  */
25 
26 #ifndef __libpbd__floating_h__
27 #define __libpbd__floating_h__
28 
29 #include <stdint.h>
30 
31 #include <cmath>
32 
33 #include "pbd/libpbd_visibility.h"
34 
35 namespace PBD {
36 
37 union /*LIBPBD_API*/ Float_t
38 {
39  Float_t (float num = 0.0f) : f(num) {}
40 
41  // Portable extraction of components.
42  bool negative() const { return (i >> 31) != 0; }
43  int32_t raw_mantissa() const { return i & ((1 << 23) - 1); }
44  int32_t raw_exponent() const { return (i >> 23) & 0xFF; }
45 
46  int32_t i;
47  float f;
48 };
49 
50 /* Note: ULPS = Units in the Last Place */
51 
52 static inline bool floateq (float a, float b, int max_ulps_diff)
53 {
54  Float_t ua (a);
55  Float_t ub (b);
56 
57  if (a == b) {
58  return true;
59  }
60 
61  // Different signs means they do not match.
62  if (ua.negative() != ub.negative()) {
63  return false;
64  }
65 
66  // Find the difference in ULPs.
67  int ulps_diff = abs (ua.i - ub.i);
68 
69  if (ulps_diff <= max_ulps_diff) {
70  return true;
71  }
72 
73  return false;
74 }
75 
76 } /* namespace */
77 
78 #endif /* __libpbd__floating_h__ */
bool negative() const
Definition: floating.h:42
int32_t i
Definition: floating.h:46
Float_t(float num=0.0f)
Definition: floating.h:39
float f
Definition: floating.h:47
static bool floateq(float a, float b, int max_ulps_diff)
Definition: floating.h:52
int32_t raw_mantissa() const
Definition: floating.h:43
int32_t raw_exponent() const
Definition: floating.h:44
Definition: debug.h:30