-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterval.h
74 lines (58 loc) · 1.88 KB
/
interval.h
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
68
69
70
71
72
73
74
#pragma once
class interval
{
public:
double min, max;
interval() : min(infinity), max(- infinity) {}
interval(double min, double max) : min(min), max(max) {}
// Input two interval and return the intersection
interval(const interval& a, const interval& b)
{
min = a.min <= b.min ? a.min : b.min;
max = a.max >= b.max ? a.max : b.max;
}
double size() const noexcept
{
return max - min;
}
bool contains_withequ(double val) const noexcept
{
return val >= min && val <= max;
}
bool surround_noequ(double val) const noexcept
{
return val > min && val < max;
}
double clamp(double x) const noexcept
{
if(x < min) return min;
if(x > max) return max;
return x;
}
double interval_center() const noexcept
{
return (min + max) / 2.0f;
}
// interval padding deal with the precision issue
interval expand(double delta) const noexcept
{
auto padding = delta / 2.0;
return interval(min - padding, max + padding);
}
static const interval empty, universe;
};
const interval interval::empty = interval(+ infinity, - infinity);
const interval interval::universe = interval(- infinity, + infinity);
// Two interval instersection
inline interval two_interval_intersection(const interval& a, const interval& b)
{
auto new_min = a.min <= b.min ? a.min : b.min;
auto new_max = a.max >= b.max ? a.max : b.max;
return interval(new_min, new_max);
}
inline interval two_interval_merge(const interval& a, const interval& b)
{
auto new_min = std::fmin(a.min, b.min);
auto new_max = std::fmax(a.max, b.max);
return interval(new_min, new_max);
}