Unit balancing
Tim Chase
python.list at tim.thechases.com
Wed Sep 13 11:26:10 EDT 2006
> I am working with a researcher who would be very happy if he
> could include units in his calculations. Then, if his
> complicated expression didn't result in "kg/yr" the program
> would stop and point out his error.
>
> Does Python (or SciPy or ..) offer this feature?
Well, it's a bit of a hack, but you could try something like
###########################################
class InvalidUnits(Exception): pass
class Unit(object):
def __init__(self, value, units = ''):
self.value = value
self.units = units
def __sub__(self, other):
if isinstance(other, Unit):
if self.units <> other.units:
raise InvalidUnits
return Unit(self.value - other.value, self.units)
return Unit(self.value - other, self.units)
def __add__(self, other):
if isinstance(other, Unit):
if self.units <> other.units:
raise InvalidUnits
return Unit(self.value + other.value, self.units)
return Unit(self.value + other, self.units)
def __mul__(self, other):
if isinstance(other, Unit):
return Unit(self.value * other.value,
"(%s)%s" % (self.units, other.units))
else:
return Unit(self.value * other, self.units)
def __div__(self, other):
if isinstance(other, Unit):
return Unit(self.value / other.value,
"%s/%s" % (self.units, other.units))
else:
return Unit(self.value / other, self.units)
def __radd__(self, other): return self.__add__(other)
def __rsub__(self, other): return self.__sub__(other)
def __rmul__(self, other): return self.__mul__(other)
def __rdiv__(self, other): return self.__div__(other)
def __repr__(self):
return '%i %s' % (self.value, self.units)
def __str__(self): return repr(self)
############################################################
which allows you to do things like
distance = Unit(80, 'm')
print "Distance: %s" % distance
time = Unit(2, 'h')
print "Time: %s" % time
speed = distance/time
print "Speed: %s" % speed
speed = 3 * speed
print "Speed: %s" % speed
print "Error:",
# can't add dissimilar units
print distance + time
I'm sure there are loads of other edge cases one would want to
consider, such as analyzing and trimming redundant units, but
that should give a pretaste of what could be done.
-tkc
More information about the Python-list
mailing list