1 9 package org.jscience.physics.units; 10 import java.io.Serializable ; 11 12 20 public abstract class Converter implements Serializable { 21 22 26 public static final Converter IDENTITY = new Identity(); 27 28 31 protected Converter() {} 32 33 40 public abstract Converter inverse(); 41 42 49 public abstract double convert(double x) throws ConversionException; 50 51 59 public abstract double derivative(double x); 60 61 69 public abstract boolean isLinear(); 70 71 79 public boolean equals(Object obj) { 80 if (obj instanceof Converter) { 81 Converter that = (Converter) obj; 82 return this.isLinear() && that.isLinear() && 84 (Float.floatToIntBits((float) this.derivative(0)) == 85 Float.floatToIntBits((float) that.derivative(0))); 86 } else { 87 return false; 88 } 89 } 90 91 98 public int hashCode() { 99 int h = Float.floatToIntBits((float)derivative(0)); 100 h += ~(h << 9); 101 h ^= (h >>> 14); 102 h += (h << 4); 103 return h ^ (h >>> 10); 104 } 105 106 114 public Converter concatenate(Converter converter) { 115 if (converter == IDENTITY) { 116 return this; 117 } else { 118 return new Compound(converter, this); 119 } 120 } 121 122 125 private static final class Identity extends Converter { 126 127 128 public Converter inverse() { 130 return this; 131 } 132 133 public double convert(double x) { 135 return x; 136 } 137 138 public double derivative(double x) { 140 return 1.0; 141 } 142 143 public boolean isLinear() { 145 return true; 146 } 147 148 public Converter concatenate(Converter converter) { 150 return converter; 151 } 152 153 private static final long serialVersionUID = 1L; 154 } 155 156 159 private static final class Compound extends Converter { 160 161 164 private final Converter _first; 165 166 169 private final Converter _second; 170 171 178 private Compound(Converter first, Converter second) { 179 _first = first; 180 _second = second; 181 } 182 183 public Converter inverse() { 185 return new Compound(_second.inverse(), _first.inverse()); 186 } 187 188 public double convert(double x) { 190 return _second.convert(_first.convert(x)); 191 } 192 193 public double derivative(double x) { 195 return _first.derivative(x) * _second.derivative(_first.convert(x)); 196 } 197 198 public boolean isLinear() { 200 return _first.isLinear() && _second.isLinear(); 201 } 202 203 public boolean equals(Object obj) { 205 return super.equals(obj) || 206 ( (obj instanceof Compound) && 207 ((Compound)obj)._first.equals(_first) && 208 ((Compound)obj)._second.equals(_second) ); 209 } 210 211 private static final long serialVersionUID = 1L; 212 } 213 } | Popular Tags |