RatioNumber extends Number implements Comparable<RatioNumber> { public RatioNumber add(RatioNumber other) { if (other == null) { return new RatioNumber(this.value, this.ratio); } else { if (this.equals(RatioNumber.ZERO)) { return new RatioNumber(other.value, other.ratio); } else if (other.equals(RatioNumber.ZERO)) { return new RatioNumber(this.value, this.ratio); } else { double value = this.value + other.value; double ratio = (this.ratio * this.value + other.ratio * other.value) / value; return new RatioNumber(value, ratio); } } } RatioNumber(double value, double ratio); static RatioNumber valueOf(String valueString); @Override int intValue(); @Override long longValue(); @Override float floatValue(); @Override double doubleValue(); @Override int compareTo(RatioNumber other); RatioNumber add(RatioNumber other); double value(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static final RatioNumber ZERO; }
@Test public void testAdd() throws Exception { RatioNumber r1; RatioNumber r2; r1 = new RatioNumber(10, 0.1); r2 = new RatioNumber(40, 0.1); assertEquals(50, r1.add(r2).value(), 0); assertEquals(0.1, r1.add(r2).doubleValue(), 0); r1 = new RatioNumber(40, 0.1); r2 = new RatioNumber(60, 0.1); assertEquals(100, r1.add(r2).value(), 0); assertEquals(0.1, r1.add(r2).doubleValue(), 0); r1 = new RatioNumber(40, 1); r2 = new RatioNumber(60, 1); assertEquals(100, r1.add(r2).value(), 0); assertEquals(1, r1.add(r2).doubleValue(), 0); r1 = new RatioNumber(40, 0.2); r2 = new RatioNumber(60, 0.1); assertEquals(100, r1.add(r2).value(), 0); assertEquals(0.14, r1.add(r2).doubleValue(), 0); r1 = new RatioNumber(1, 0.5); r2 = RatioNumber.ZERO; assertEquals(1.0, r1.add(r2).value(), 0); assertEquals(0.5, r1.add(r2).doubleValue(), 0); r1 = RatioNumber.ZERO; r2 = new RatioNumber(1, 0.5); assertEquals(1.0, r1.add(r2).value(), 0); assertEquals(0.5, r1.add(r2).doubleValue(), 0); r1 = RatioNumber.ZERO; r2 = new RatioNumber(0, 1.0); assertEquals(0, r1.add(r2).value(), 0); assertEquals(1.0, r1.add(r2).doubleValue(), 0); }
@Test public void testAddZero() throws Exception { Number ratioNumber = new RatioNumber(10, 0.1); Number zero = 0; assertEquals(ratioNumber, LoadEntry.DataLocality.add(ratioNumber, zero)); assertEquals(ratioNumber, LoadEntry.DataLocality.add(zero, ratioNumber)); assertEquals(zero, LoadEntry.DataLocality.add(zero, zero)); }