# DMelt:Units/4 Calculations with Units

Limitted access. First login to DataMelt if you are a full DataMelt member. Then login to HandWiki as a user.

# Calculations with units

Calculations with units are performed using the Java class  jhplot.UCalc. Here is the example of such calculations:

from jhplot import *
u=UCalc()
s="2 hours + 23 min - 32 sec"
print s,"=",u.eval(s,"sec")  # "sec" is expected unit

You will the the output with the correct number of seconds hat follows this expression.

One can make quite complicated calculations using the following constants:

pi          ratio of circumference to diameter
c           speed of light
e           charge on an electron
h           Planck's constant

and the following functions:

ln        natural logarithm
log       base-10 logarithm
log2      base-2  logarithm
exp       exponential
sqrt      square root, sqrt(x) = x^(1/2)
cuberoot  cube root, cuberoot(x) = x^(1/3)

Exponents are specified using the operator ^ or .

Let us give a more complicated example:

from jhplot import *
u=UCalc()
print u.eval("sqrt(10*50ft/90 (cm/s^2))","s")

which will return "13.012814

Another example: let us find suppose you want to find the wavelength, in meters, of a 200 MHz radio wave. You can do it as:

from jhplot import *
u=UCalc()
print u.eval("c / 200 MHz","m")

which will print the correct wavelength.

## Values with units using VisAd

The Java package  VisAd contains powerful classes  visad.Real and  visad.Data to perform calculations with units and errors.

If your quantities are physical and have associated Units, then you might prefer to create a VisAD MathType that explicitly defines the metadata characteristics of your quantities. A MathType is used to define the kind of mathematical object that the Data object approximates. Every Data object in VisAD must have a MathType. In the previous examples, a default MathType with the name "Generic" was implicitly used for our Real objects.

In the simplest form for dealing with Units, the constructor for a MathType which defines Real values is:

RealType(String name, Unit u, Set s)

which allows you to assign a unique name to this MathType, a Unit for this, and define a default Set. In practice, the Set is seldom used and should just be passed as null in most cases. Here is an example using Java codding:

import visad.*;
Real t1,t2,sum;
RealType k = new RealType("kelvin",SI.kelvin,null);
t2 = new Real(k,273.);
t1 = new Real(k,255.);
System.out.println("sum = "+sum+" "+sum.getUnit());