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 package com.generationjava.math;
37
38
39 /***
40 * A continuous range between two doubles.
41 */
42 public class Interval {
43
44 private double lower;
45 private double upper;
46
47 /***
48 * Create an Interval between two doubles.
49 */
50 public Interval(double lower, double upper) {
51 this.lower = lower;
52 this.upper = upper;
53 }
54
55 /***
56 * Make an Interval with the specified center and difference from the
57 * center.
58 */
59 static public Interval makeIntervalCenterWidth(double center, double difference) {
60 return new Interval(center - difference, center + difference);
61 }
62
63 /***
64 * Make an Interval with the specified center and the specified
65 * percentage difference from the center.
66 */
67 static public Interval makeIntervalCenterPercentage(double center, float percentage) {
68 return new Interval(center - (center*percentage/100), center + (center*percentage/100));
69 }
70
71 /***
72 * Add this Interval to another one.
73 */
74 public Interval add(Interval i) {
75 return new Interval(i.lower + this.lower, i.upper + this.upper);
76 }
77
78 /***
79 * Multiple this Interval by another one.
80 */
81 public Interval mul(Interval i) {
82 double p1 = i.lower * this.lower;
83 double p2 = i.lower * this.upper;
84 double p3 = i.upper * this.lower;
85 double p4 = i.upper * this.upper;
86 return new Interval( min(p1,p2,p3,p4), max(p1,p2,p3,p4) );
87 }
88
89 /***
90 * Divide this interval by another.
91 */
92 public Interval div(Interval i) {
93 return mul( new Interval( 1/i.upper, 1/i.lower ) );
94 }
95
96 /***
97 * Subtract an Interval from this Interval.
98 */
99 public Interval sub(Interval i) {
100 return add( new Interval( -i.upper, -i.lower ) );
101 }
102
103 /***
104 * Find the minimum of 4 values.
105 */
106 private double min(double d1, double d2, double d3, double d4) {
107 double tmp = d1;
108 if(d2 < tmp) {
109 tmp = d2;
110 }
111 if(d3 < tmp) {
112 tmp = d3;
113 }
114 if(d4 < tmp) {
115 tmp = d4;
116 }
117 return tmp;
118 }
119
120 /***
121 * Find the maximum of 4 values.
122 */
123 private double max(double d1, double d2, double d3, double d4) {
124 double tmp = d1;
125 if(d2 > tmp) {
126 tmp = d2;
127 }
128 if(d3 > tmp) {
129 tmp = d3;
130 }
131 if(d4 > tmp) {
132 tmp = d4;
133 }
134 return tmp;
135 }
136
137 public String toString() {
138 return this.lower+" - "+this.upper;
139 }
140
141 public boolean equals(Object obj) {
142 if(obj instanceof Interval) {
143 Interval ivl = (Interval)obj;
144 return ( (this.lower == ivl.lower) && (this.upper == ivl.upper) );
145 } else {
146 return false;
147 }
148 }
149
150 public int hashCode() {
151 return (int) ((this.lower + this.upper) % Integer.MAX_VALUE);
152 }
153 }