-
Notifications
You must be signed in to change notification settings - Fork 0
/
range.hpp
73 lines (62 loc) · 1.62 KB
/
range.hpp
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
/*
* range.hpp
*
* Created on: Sep 24, 2015
* Author: Joost Huizinga
*/
#ifndef MODULES_MISC_RANGE_HPP_
#define MODULES_MISC_RANGE_HPP_
/**
* A range object storing a minimum, maximum and step-size.
*/
struct Range{
Range(){
min = 0;
max = 0;
step = 0;
}
float min;
float max;
float step;
unsigned nb_of_bins(float tolerance = 0.00001){
return unsigned(((max - min) / step) + tolerance) + 1;
}
unsigned get_bin(float value, float tolerance = 0.00001){
return unsigned(((value - min) / step) + tolerance);
}
};
std::ostream& operator<<(std::ostream& is, const Range& obj){
is << "min: " << obj.min << " max: " << obj.max << " step: " << obj.step;
return is;
}
/**
* Takes a vector of floats and returns a range that includes the minimum,
* maximum and smallest step in the vector.
*/
Range get_range(std::vector<float>& v, float tolerance = 0.00001){
Range result;
if(v.empty()){
return result;
}
result.min = v.front();
result.max = v.front();
result.step = std::numeric_limits<float>::max();
for(unsigned i=0; i<v.size(); ++i){
for(unsigned j=i+1; j<v.size(); ++j){
float difference = fabs(v[i] - v[j]);
if(difference > tolerance){
if(difference < result.step){
result.step = difference;
}
}
}
if(v[i] < result.min){
result.min = v[i];
}
if(v[i] > result.max){
result.max = v[i];
}
}
return result;
}
#endif /* MODULES_MISC_RANGE_HPP_ */