Ardour  8.12
floating.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2012-2015 Paul Davis <paul@linuxaudiosystems.com>
3  * Copyright (C) 2013 John Emmas <john@creativepost.co.uk>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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 <cstdlib> // abs(int)
32 #include <cmath>
33 
34 #include "pbd/libpbd_visibility.h"
35 
36 namespace PBD {
37 
38 union /*LIBPBD_API*/ Float_t
39 {
40  Float_t (float num = 0.0f) : f(num) {}
41 
42  // Portable extraction of components.
43  bool negative() const { return (i >> 31) != 0; }
44  int32_t raw_mantissa() const { return i & ((1 << 23) - 1); }
45  int32_t raw_exponent() const { return (i >> 23) & 0xFF; }
46 
47  int32_t i;
48  float f;
49 };
50 
51 /* Note: ULPS = Units in the Last Place */
52 
53 static inline bool floateq (float a, float b, int max_ulps_diff)
54 {
55  Float_t ua (a);
56  Float_t ub (b);
57 
58  if (a == b) {
59  return true;
60  }
61 
62  // Different signs means they do not match.
63  if (ua.negative() != ub.negative()) {
64  return false;
65  }
66 
67  // Find the difference in ULPs.
68  int ulps_diff = abs (ua.i - ub.i);
69 
70  if (ulps_diff <= max_ulps_diff) {
71  return true;
72  }
73 
74  return false;
75 }
76 
77 } /* namespace */
78 
79 #endif /* __libpbd__floating_h__ */
Definition: axis_view.h:42
static bool floateq(float a, float b, int max_ulps_diff)
Definition: floating.h:53
int32_t raw_mantissa() const
Definition: floating.h:44
bool negative() const
Definition: floating.h:43
int32_t raw_exponent() const
Definition: floating.h:45
Float_t(float num=0.0f)
Definition: floating.h:40
int32_t i
Definition: floating.h:47
float f
Definition: floating.h:48