-
Notifications
You must be signed in to change notification settings - Fork 3
/
Util.java
90 lines (76 loc) · 2.19 KB
/
Util.java
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package org.usfirst.frc4904.standard;
import edu.wpi.first.hal.util.BoundaryException;
/**
* Common utilities
*/
public class Util {
/**
* Returns true if {@code value} is less than {@code epsilon}. This is useful
* for floating point numbers, whose arithmetic operations tend to introduce
* small errors.
*
* @param value The floating point number to be compared
* @param epsilon The maximum magnitude of var such that it can be considered
* zero
* @return Whether or not {@code value} is less than {@code epsilon}
*/
public static boolean isZero(double value, double epsilon) {
return Math.abs(value) < epsilon;
}
/**
* Returns true if {@code value} is less than {@code epsilon}. This is useful
* for floating point numbers, whose arithmetic operations tend to introduce
* small errors.
*
* @param value The floating point number to be compared
* @return Whether or not {@code value} is effectively zero
*/
public static boolean isZero(double value) {
return isZero(value, Math.sqrt(Math.ulp(1.0)));
}
public static class Range {
private final double min;
private final double max;
public Range(double min, double max) {
if (min > max) {
throw new BoundaryException("Range min " + min + " greater than max " + max);
}
this.min = min;
this.max = max;
}
public double getRange() {
return max - min;
}
public boolean contains(double value) {
return value >= min && value <= max;
}
public double getMin() {
return min;
}
public double getMax() {
return max;
}
public double getCenter() {
return (min + max) / 2.0;
}
/**
* Scales a value (between -1 and 1) to the range. Example: (new
* Range(0,6)).scaleValue(0.5) == 4.5
*
* @param value between -1 and 1 (will be limited to [-1, 1])
* @return the scaled value
*/
public double scaleValue(double value) {
return limitValue(getCenter() + value * (getRange() / 2.0));
}
/**
* Limits a value to the range. Example: (new Range(0,6)).limitValue(7) == 6
*
* @param value the value to be limited
* @return the limited value
*/
public double limitValue(double value) {
return Math.max(Math.min(value, max), min);
}
}
}