Skip to content

Instantly share code, notes, and snippets.

@Ming-Tang
Created May 30, 2010 17:57
Show Gist options
  • Save Ming-Tang/419200 to your computer and use it in GitHub Desktop.
Save Ming-Tang/419200 to your computer and use it in GitHub Desktop.
Dimensional analysis
#!/usr/bin/python
class Unit(object):
def __init__(self, value=0.0, unit={}):
self.value = value
self.unit = unit
@staticmethod
def check(unit1, unit2):
p1 = [ (name, unit1[name]) for name in sorted(unit1.keys()) ]
p2 = [ (name, unit2[name]) for name in sorted(unit2.keys()) ]
if len(p1) != len(p2):
return True
else:
for i in range(len(p1)):
if p1[i][0] != p2[i][0] or p1[i][1] != p2[i][1]:
return False
return True
@staticmethod
def union(u1, u2, increase=True):
result = u1.copy()
m = (-1, 1)[increase]
for name, exponent in u2.items():
if result.has_key(name):
result[name] += m * exponent
else:
result[name] = m * exponent
if result[name] == 0:
result.pop(name)
return result
def unit_name(self, joiner=' ', html=False):
return joiner.join([ "%s%s" % (name, (('^%r', '<sup>%r</sup>')[html] % exponent, '')[not not exponent == 1]) for name, exponent in sorted(self.unit.items(), lambda y, x : cmp(x[1], y[1])) ])
def __eq__(self, other):
if self.value != other.value:
return False
else:
return Unit.check(self.unit, other.unit)
def __add__(self, other):
if not Unit.check(self.unit, other.unit):
raise TypeError("Incompatible units.")
return Unit(self.value + other.value, self.unit)
def __sub__(self, other):
if not Unit.check(self.unit, other.unit):
raise TypeError("Incompatible units.")
return Unit(self.value - other.value, self.unit)
def __mul__(self, other):
return Unit(self.value * other.value, Unit.union(self.unit, other.unit))
def __div__(self, other):
return Unit(self.value / other.value, Unit.union(self.unit, other.unit, False))
def __repr__(self):
return "%r %s" % (self.value, self.unit_name())
print "1kWh =", Unit(1000, { 'J': 1, 's': -1 }) * Unit(3600, { 's': 1 })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment