001: // Copyright (c) 1997 Per M.A. Bothner.
002: // This is free software; for terms and warranty disclaimer see ./COPYING.
003:
004: package gnu.math;
005:
006: import java.io.*;
007:
008: /** A Unit which is the product or ratio of two other Units.
009: * @author Per Bothner
010: */
011:
012: class MulUnit extends Unit implements Externalizable {
013: Unit unit1;
014: Unit unit2;
015: int power1;
016: int power2;
017: MulUnit next;
018:
019: MulUnit(Unit unit1, int power1, Unit unit2, int power2) {
020: this .unit1 = unit1;
021: this .unit2 = unit2;
022: this .power1 = power1;
023: this .power2 = power2;
024: this .dims = Dimensions.product(unit1.dims, power1, unit2.dims,
025: power2);
026:
027: if (power1 == 1)
028: factor = unit1.factor;
029: else
030: factor = Math.pow(unit1.factor, (double) power1);
031: if (power2 < 0) {
032: for (int i = -power2; --i >= 0;)
033: factor /= unit2.factor;
034: } else {
035: for (int i = power2; --i >= 0;)
036: factor *= unit2.factor;
037: }
038:
039: next = unit1.products;
040: unit1.products = this ;
041: }
042:
043: MulUnit(Unit unit1, Unit unit2, int power2) {
044: this (unit1, 1, unit2, power2);
045: }
046:
047: public String toString() {
048: StringBuffer str = new StringBuffer(60);
049: str.append(unit1);
050: if (power1 != 1) {
051: str.append('^');
052: str.append(power1);
053: }
054: if (power2 != 0) {
055: str.append('*');
056: str.append(unit2);
057: if (power2 != 1) {
058: str.append('^');
059: str.append(power2);
060: }
061: }
062: return str.toString();
063: }
064:
065: public Unit sqrt() {
066: if ((power1 & 1) == 0 && (power2 & 1) == 0)
067: return times(unit1, power1 >> 1, unit2, power2 >> 1);
068: return super .sqrt();
069: }
070:
071: static MulUnit lookup(Unit unit1, int power1, Unit unit2, int power2) {
072: // Search for an existing matching MulUnit.
073: for (MulUnit u = unit1.products; u != null; u = u.next) {
074: if (u.unit1 == unit1 && u.unit2 == unit2
075: && u.power1 == power1 && u.power2 == power2)
076: return u;
077: }
078: return null;
079: }
080:
081: public static MulUnit make(Unit unit1, int power1, Unit unit2,
082: int power2) {
083: MulUnit u = lookup(unit1, power1, unit2, power2);
084: if (u != null)
085: return u;
086: return new MulUnit(unit1, power1, unit2, power2);
087: }
088:
089: /**
090: * @serialData
091: */
092:
093: public void writeExternal(ObjectOutput out) throws IOException {
094: out.writeObject(unit1);
095: out.writeInt(power1);
096: out.writeObject(unit2);
097: out.writeInt(power2);
098: }
099:
100: public void readExternal(ObjectInput in) throws IOException,
101: ClassNotFoundException {
102: unit1 = (Unit) in.readObject();
103: power1 = in.readInt();
104: unit2 = (Unit) in.readObject();
105: power2 = in.readInt();
106: }
107:
108: public Object readResolve() throws ObjectStreamException {
109: MulUnit u = lookup(unit1, power1, unit2, power2);
110: if (u != null)
111: return u;
112: return this;
113: }
114: }
|