Units and Measures with JScience

Units and Measures with JScience

By Lance Finney, OCI Senior Software Engineer

June 2006


Introduction

Many applications have a need for defining units and measures. Engineering and scientific applications need to support length, mass, volume, velocity, and many more types of units. Financial applications require currencies, perhaps of several different countries. Mathematical applications need functions and complex numbers. By default, Java does not provide support for application developers to add these concepts to their application. Fortunately, third party libraries have filled in the need with support for strongly-typed units, measures, and calculations.

One of the most advanced of these libraries is JScience, which might someday be incorporated in Java Standard Edition. JScience aims to "provide the most comprehensive JavaTM library for the scientific community." It provides all the features mentioned in the previous paragraph and more, with Java 5-based type safety. Another important advantage to using JScience over rolling your own unit handling framework is that JScience is well tested.

Physical Units

For engineering and scientific applications, the core classes are SI and NonSI. SI contains the basic units defined as part of the International System of Units, which are commonly known as the metrics units, such as meters, seconds, grams, radians, and less common units like candelas, moles, and webers. NonSI contains British and other units like miles, pounds (both force and mass), faradays, light years, and horsepower, which are defined in terms of SI units.

In order to simplify the API, JScience includes base units, not multiplicative units like kilometer and centimeter. To create those units, SI provides methods to build composite units.

  1. import javax.units.SI;
  2. import javax.units.Unit;
  3. import javax.quantities.Length;
  4. import javax.quantities.Mass;
  5. import javax.quantities.Power;
  6. public class SIConversion {
  7. public static void main(String[] args) {
  8. Unit<Mass> centigram = SI.CENTI(SI.GRAM);
  9. Unit<Length> kilometer = SI.KILO(SI.METER);
  10. Unit<Power> megawatt = SI.MEGA(SI.WATT);
  11. }
  12. }

Of course, this can be simplified slightly using the static import feature added in Java 5. Below is the example from above using static imports. The rest of the examples in the article do not use this feature.

  1. import static javax.units.SI.*;
  2. import javax.units.Unit;
  3. import javax.quantities.Length;
  4. import javax.quantities.Mass;
  5. import javax.quantities.Power;
  6. public class SIConversion {
  7. public static void main(String[] args) {
  8. Unit<Mass> centigram = CENTI(GRAM);
  9. Unit<Length> kilometer = KILO(METER);
  10. Unit<Power> megawatt = MEGA(WATT);
  11. }
  12. }

Units are parameterized (Quantity >) to enforce compile-time checks of units/quantities consistency. We will see this in use later.

Length

With these basic units, let's see what we can do with units and measures of a basic type, Length. All length units are defined in terms of the SI unit of length, the meter. Because SI provides only the SI standard units, meter is the only length unit in the SI class. However, the NonSI provides several other length units based on meter:

Additionally, as mentioned above, there are methods on the SI class used to create derived units like kilometer and centimeter.

With these units, you can convert unit values, determine the type of a particular unit, to validate types, or create composite units by multiplication and division. Here is an example of how to use these methods and the results:

  1. import javax.quantities.Length;
  2. import javax.units.NonSI;
  3. import javax.units.SI;
  4. import javax.units.Unit;
  5. public class LengthUnits {
  6. public static void main(String[] args) {
  7. //Generate Units with scalar multiplication
  8. Unit<Length> FURLONG = NonSI.FOOT.times(660); // Ok
  9. // Unit<Length> FURLONG = SI.HOUR.times(60); // Compile error
  10. //Generate Units with prefixes
  11. Unit<Length> GIGAMETER = SI.GIGA(SI.METER); // Ok
  12. // Unit<Length> GIGAMETER = SI.GIGA(SI.NEWTON); // Compile error
  13. // Retrieval of the system unit (meter in this case)
  14. System.out.println(FURLONG.getSystemUnit());
  15. // Retrieval of the unit dimension (L represents length)
  16. System.out.println(GIGAMETER.getDimension());
  17. // Dimension checking (allows/disallows conversions)
  18. System.out.println(NonSI.LIGHT_YEAR.isCompatible(NonSI.PARSEC)); //legal
  19. System.out.println(NonSI.LIGHT_YEAR.isCompatible(SI.WATT)); //illegal
  20. System.out.println(NonSI.LIGHT_YEAR.isCompatible(NonSI.PARSEC.divide(SI.SECOND))); //illegal
  21. }
  22. }
m
[L]
true
false
false

The commented-out lines show a couple conversions that would cause compile-time errors when using Java 5 because of type discrepancies. JScience can be used with older versions of Java that do not have generics. With those JVMs, those lines (minus the parameterization) would compile but produce runtime errors.

Energy

Now let's look at a more complicated physical quantity, energy. The units of energy are composed of length, mass, and time. The base unit of energy is the SI unit is the joule (kg·m²/s²). NonSI provides the following other energy units based on the joule:

Surprisingly, the common unit of energy used in the United States, the BTU, is not defined. This might be because there are several slightly different versions of the BTU. However, let's see what's necessary to define the BTU.

  1. import javax.quantities.Energy;
  2. import javax.units.SI;
  3. import javax.units.Unit;
  4. public class EnergyExample {
  5. public static void main(String[] args) {
  6. double BTU_CONVERSION = 1055.05585262; // Conversion that uses the International
  7. //(Steam) Table calorie, defined as 4.1868 J
  8. Unit<Energy> BTU = SI.JOULE.times(BTU_CONVERSION);
  9.  
  10. System.out.println(BTU);
  11. System.out.println(BTU.getSystemUnit());
  12. System.out.println(BTU.getDimension());
  13. System.out.println(BTU.isCompatible(SI.JOULE));
  14. }
  15. }
[J*1055.05585262] //toString() shows how a unit is built from base units
J                 //getSystemUnit() shows what the base unit(s) are
[L]²*[M]/[T]²     //getDimension() shows that energy is composed of
                  //Length squared times Mass divided by Time squared
true             //isCompatible(SI.JOULE) shows that BTU and JOULE are
                  //of the same dimensions

Now, BTU can be used in calculations just like any other unit of energy.

Calculations

Now that we've defined the units and shown how to derive new units, let's look at how to use them in calculations. There are three basic ways to convert a value from one unit to another. The first is to ask the source unit for an appropriate converter to the destination unit and use the converter. The second is to create an instance of the Scalar class that contains both the type and the size, and have the Scalar convert the value. The third and most powerful approach is to generate an instance of the Measure class that contains both the type and the size, and have the Measure convert the value.

  1. import javax.quantities.Length;
  2. import javax.quantities.Quantity;
  3. import javax.quantities.Scalar;
  4. import javax.units.NonSI;
  5. import javax.units.SI;
  6. import javax.units.Unit;
  7. import org.jscience.physics.measures.Measure;
  8. public class LengthCalculation {
  9. public static void main(String[] args) {
  10. Unit<Length> FURLONG = NonSI.FOOT.times(660);
  11. Unit<Length> MICRON = SI.MICRO(NonSI.INCH);
  12. //Derive the converter from the Unit
  13. System.out.println(FURLONG.getConverterTo(MICRON).convert(2));
  14. // System.out.println(FURLONG.getConverterTo(SI.MICRO(SI.JOULE)).convert(2)); // Runtime error.
  15. //Build a Scalar and have it calculate
  16. Quantity<Length> furlongScalar = new Scalar<Length>(2, FURLONG); // Ok.
  17. System.out.println(furlongScalar.doubleValue(MICRON));
  18. //Build a Measure and have it calculate
  19. Quantity<Length> lengthInFurlong = Measure.valueOf(2, FURLONG);
  20. System.out.println(lengthInFurlong.doubleValue(MICRON));
  21. // long lengthInMicrons = furlongScalar.longValue(SI.JOULE); // Compile error.
  22. // Quantity<Length> badLength = new Scalar<Length>(2, SI.CELSIUS); // Compile error.
  23. }
  24. }
1.584E10
1.584E10
1.584E10

What is the difference between Scalar and Measure? Basically, Scalar is limited to performing conversions between units of the same basic type (between FURLONG and MICRON in this case, two units of Length). In contrast, Measure can be used to combine values of different units and to show error calculations.

Combining Units

  1. import javax.quantities.Acceleration;
  2. import javax.quantities.Force;
  3. import javax.quantities.Mass;
  4. import javax.units.NonSI;
  5. import javax.units.SI;
  6. import org.jscience.physics.measures.Measure;
  7. public class ExactForce {
  8. public static void main(String[] args) {
  9. Measure<Mass> mass = Measure.valueOf(5, SI.KILOGRAM);
  10. Measure<Acceleration> acceleration = Measure.valueOf(9, SI.METER_PER_SQUARE_SECOND);
  11. Measure<Force> force = mass.times(acceleration).to(SI.NEWTON);
  12. double pounds = force.doubleValue(NonSI.POUND_FORCE);
  13. Measure<Force> force2 = mass.times(acceleration).to(NonSI.POUND_FORCE);
  14. System.out.println("mass = " + mass);
  15. System.out.println("acceleration = " + acceleration);
  16. System.out.println("force = " + force);
  17. System.out.println("pounds = " + pounds);
  18. System.out.println("force2 = " + force2);
  19. }
  20. }
mass = 5 kg
acceleration = 9 m/s²
force = 45 N
pounds = 10.116402439486972
force2 = (10.1164024394869728 ± 1.8E-15) lbf

This example shows multiplying exactly 5 kg by exactly 9 m/s² to derive exactly 45 N. Then, we convert those 45 newtons to lbf and calculate the value. Finally, we multiply the inputs again and convert to lbf. This time however, the value is slightly different. What is going on?

Displaying Precision

Measure provides many ways both to specify precision of input values and to determine the precision of the calculated values. In the previous example, all the inputs were defined exactly because an int or long was passed into Measure.valueOf(). When a double is passed into those methods, the input is considered inexact, and the output is different.

  1. import javax.quantities.Acceleration;
  2. import javax.quantities.Force;
  3. import javax.quantities.Mass;
  4. import javax.units.NonSI;
  5. import javax.units.SI;
  6. import org.jscience.physics.measures.Measure;
  7. public class InexactForce {
  8. public static void main(String[] args) {
  9. Measure<Mass> mass = Measure.valueOf(5.0, SI.KILOGRAM);
  10. Measure<Acceleration> acceleration = Measure.valueOf(9.0, SI.METER_PER_SQUARE_SECOND);
  11. Measure<Force> force = mass.times(acceleration).to(SI.NEWTON);
  12. double pounds = force.doubleValue(NonSI.POUND_FORCE);
  13. Measure<Force> force2 = mass.times(acceleration).to(NonSI.POUND_FORCE);
  14. System.out.println("mass = " + mass);
  15. System.out.println("acceleration = " + acceleration);
  16. System.out.println("force = " + force);
  17. System.out.println("pounds = " + pounds);
  18. System.out.println("force2 = " + force2);
  19. }
  20. }
mass = (5.0 ± 8.9E-16) kg
acceleration = (9.0 ± 1.8E-15) m/s²
force = (45.0 ± 2.1E-14) N
pounds = 10.116402439486972
force2 = (10.1164024394869728 ± 7.1E-15) lbf

Because the double version of the methods was used, JScience calculates the imprecision built into Java's representation of double values and builds that imprecision into the measurement. So, the input values have explicit imprecision, and the calculated values have imprecision built in, too.

In the previous example, all the input values were exact because integer inputs are considered exact. However, the conversion from newtons to lbf introduces an imprecision due to a double-based multiplication, and that imprecision is carried forward.

In addition to showing the implicit imprecision of Java, JScience lets you define the known imprecision and uses it in calculations.

  1. import javax.quantities.Acceleration;
  2. import javax.quantities.Force;
  3. import javax.quantities.Mass;
  4. import javax.units.NonSI;
  5. import javax.units.SI;
  6. import org.jscience.physics.measures.Measure;
  7. public class ExplicitInexactForce {
  8. public static void main(String[] args) {
  9. Measure<Mass> mass = Measure.valueOf(5.0, 0.5, SI.KILOGRAM);
  10. Measure<Acceleration> acceleration = Measure.rangeOf(8.75, 9.25, SI.METER_PER_SQUARE_SECOND);
  11. Measure<Force> force = mass.times(acceleration).to(SI.NEWTON);
  12. double pounds = force.doubleValue(NonSI.POUND_FORCE);
  13. Measure<Force> force2 = mass.times(acceleration).to(NonSI.POUND_FORCE);
  14. System.out.println("mass = " + mass);
  15. System.out.println("acceleration = " + acceleration);
  16. System.out.println("force = " + force);
  17. System.out.println("pounds = " + pounds);
  18. System.out.println("force2 = " + force2);
  19. }
  20. }
mass = (5.0 ± 5.0E-1) kg
acceleration = (9.0 ± 2.5E-1) m/s²
force = (45.1 ± 5.8) N
pounds = 10.144503557374438
force2 = (10.1 ± 1.3) lbf

In this case, the mass is defined as being between 4.5 and 5.5 kg, and the acceleration is defined as being between 8.75 and 9.25 m/s², defined separately using valueOf() and rangeOf() methods. Additionally, the errors are combined when calculating the product, force.

You can use these error ranges to determine if two values are approximately equal. Explicitly, the comparison is whether the error ranges overlap at all. The following code snippet comes after the last line of ExplicitInexactForce, and it shows that the calculated pounds value is close to 10, but not close to 15.

  1. Measure<Force> approx1 = Measure.valueOf(10.0, NonSI.POUND_FORCE);
  2. Measure<Force> approx2 = Measure.valueOf(15.0, NonSI.POUND_FORCE);
  3. System.out.println("(approx1 ~= force2) = " + approx1.approximates(force2));
  4. System.out.println("(approx2 ~= force2) = " + approx2.approximates(force2));
>(approx1 ~= force2) = true
>(approx2 ~= force2) = false

By default, JScience displays error ranges using a '±' symbol combined with two digits of accuracy and scientific notation. There are other ways to display error ranges using the MeasureFormat class.

  1. import javax.quantities.Mass;
  2. import javax.units.SI;
  3. import org.jscience.physics.measures.Measure;
  4. import org.jscience.physics.measures.MeasureFormat;
  5. public class RangeDisplay {
  6. public static void main(String[] args) {
  7. Measure<Mass> mass = Measure.valueOf(100.0, SI.KILOGRAM).divide(3);
  8. System.out.println("mass = " + mass);
  9. MeasureFormat.setInstance(MeasureFormat.getPlusMinusErrorInstance(4));
  10. System.out.println("mass = " + mass);
  11. MeasureFormat.setInstance(MeasureFormat.getBracketErrorInstance(2));
  12. System.out.println("mass = " + mass);
  13. MeasureFormat.setInstance(MeasureFormat.getExactDigitsInstance());
  14. System.out.println("mass = " + mass);
  15. }
  16. }
mass = (33.333333333333336 ± 1.4E-14) kg
mass = (33.33333333333333504 ± 1.421E-14) kg
mass = 33.333333333333336[14] kg
mass = 33.333333333333 kg

The first output shows the default style. The second shows using the '±' symbol combined with four digits. The third shows the range of imprecision in brackets. The final output shows the calculation value limited to the digits that are known exactly.

Currency

JScience enables monetary calculations using its Currency class, which by default provides the Australian, Canadian, Chinese, European, British, Japanese, Korean, Taiwanese, and United States currencies. Currency is a derived Unit, similar to many of the physical units. Unlike the physical units, the conversions between the different instances fluctuate over time (the conversion rate between Dollars and Euros changes daily; the conversion rate between inches and centimeters is fixed). JScience allows you to define a conversion rate between different currencies and use that conversion for calculations. Here is an example of the cost of a car trip in the United States calculated for a German tourist. In the example, we combine a currency conversion ($1 = 0.78 €), the rental car's mileage (25 mi/gal), the price of gas ($2.75/gal), and the length of the drive (400 miles) to calculate the cost of the gasoline used, in Euros:

  1. import javax.quantities.Length;
  2. import javax.units.NonSI;
  3. import javax.units.UnitFormat;
  4. import org.jscience.economics.money.Currency;
  5. import org.jscience.economics.money.Money;
  6. import org.jscience.physics.measures.Measure;
  7. public class CurrencyExample {
  8. public static void main(String[] args) {
  9. // Changes the units for output
  10. UnitFormat.getStandardInstance().label(Currency.USD, "$");
  11. UnitFormat.getStandardInstance().label(Currency.EUR, "€");
  12. // Sets the exchange rate
  13. Currency.setReferenceCurrency(Currency.EUR);
  14. Currency.USD.setExchangeRate(0.78); // 0.78 € = $1
  15. // Calculates the trip cost
  16. Measure<?> carMileage = Measure.valueOf(25, NonSI.MILE.divide(NonSI.GALLON_LIQUID_US)); // 25 mi/gal
  17. Measure<?> gasPrice = Measure.valueOf(2.75, Currency.USD.divide(NonSI.GALLON_LIQUID_US)); // $2.75/gal
  18. Measure<Length> tripDistance = Measure.valueOf(400, NonSI.MILE); // 400 mi
  19. Measure<Money> tripCost = tripDistance.divide(carMileage).times(gasPrice).to(Currency.EUR);
  20. System.out.println("Trip cost = " + tripCost + " (" + tripCost.to(Currency.USD) + ")");
  21. }
  22. }
Trip cost = 34.32 € (44.00 $)

Other Packages

In addition to the Physical Units packages and the Money package, JScience provides several other interesting packages worth noting, but outside the scope of this document. 

According to the developers, several other packages are planned for inclusion in the project within the next year:

JSR 275

You may have noticed that some of the core JScience classes like SI, NonSI, Length, and Force are in subpackages of javax. This is true because the core of JScience has been accepted by the JCP committee for possible inclusion in Java. JSR 275 is an effort to refine JScience so that it will provide core support for Physical Units within Java.

This JSR is relatively early in the process, but its existence indicates that JScience is likely going to be the standard way of supporting conversions and calculations in the Java community.

Summary

Developing units systems for scientific, engineering, and mathematical applications is difficult, tedious, and error-prone. Fortunately, JScience provides a comprehensive, well-tested, and standard way for Java developers to support scientific, mathematical, and economic units. The JScience API uses generics to provide type-safety, and the core of JScience is under consideration for future include in Java SE.

If you are requested to add units-based functionality to your application, and you have considered rolling your own, you owe yourself to investigate JScience. If you decide to use it, you will likely save many hours of development and become familiar with future Java standard.

References

Lance Finney would like to thank Mario Aquino, Jeff Brown, Tom Wheeler, and Jean-Marie Dautelle for reviewing this article and providing useful suggestions.