2 Copyright (C) 2012 Paul Davis
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.
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.
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.
21 * http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
23 * Code assumed to be in the public domain.
26 #ifndef __libpbd__floating_h__
27 #define __libpbd__floating_h__
31 #include <cstdlib> // abs(int)
34 #include "pbd/libpbd_visibility.h"
38 union /*LIBPBD_API*/ Float_t
40 Float_t (float num = 0.0f) : f(num) {}
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; }
51 /* Note: ULPS = Units in the Last Place */
53 static inline bool floateq (float a, float b, int max_ulps_diff)
62 // Different signs means they do not match.
63 if (ua.negative() != ub.negative()) {
67 // Find the difference in ULPs.
68 int ulps_diff = abs (ua.i - ub.i);
70 if (ulps_diff <= max_ulps_diff) {
79 #endif /* __libpbd__floating_h__ */