aboutsummaryrefslogtreecommitdiffhomepage
path: root/experimental/Intersection/DataTypes.cpp
blob: dc4fea1b82505e37025fc03bcaad09a2419ec7eb (plain)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "DataTypes.h"

#include <sys/types.h>
#include <stdlib.h>

#if USE_EPSILON
const double PointEpsilon = 0.000001;
const double SquaredEpsilon = PointEpsilon * PointEpsilon;
#endif

const int UlpsEpsilon = 16;

// from http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
union Float_t
{
    Float_t(float num = 0.0f) : f(num) {}
    // Portable extraction of components.
    bool negative() const { return (i >> 31) != 0; }
#if 0 // unused
    int32_t RawMantissa() const { return i & ((1 << 23) - 1); }
    int32_t RawExponent() const { return (i >> 23) & 0xFF; }
#endif
    int32_t i;
    float f;
#if SK_DEBUG
    struct
    {   // Bitfields for exploration. Do not use in production code.
        uint32_t mantissa : 23;
        uint32_t exponent : 8;
        uint32_t sign : 1;
    } parts;
#endif
};

bool AlmostEqualUlps(float A, float B)
{
    Float_t uA(A);
    Float_t uB(B);

    // Different signs means they do not match.
    if (uA.negative() != uB.negative())
    {
        // Check for equality to make sure +0==-0
        return A == B;
    }

    // Find the difference in ULPs.
    int ulpsDiff = abs(uA.i - uB.i);
    return ulpsDiff <= UlpsEpsilon;
}

// FIXME: obsolete, delete
#if 1
int UlpsDiff(float A, float B)
{
    Float_t uA(A);
    Float_t uB(B);

    return abs(uA.i - uB.i);
}
#endif