def __pow__(self, other): if self.offset != 0: raise TypeError("cannot exponentiate units with non-zero offset") if type(other) is int: return PhysicalUnit( other * self.names, pow(self.factor, other), #list(map(lambda x,p=other: x*p, self.powers))) [x * other for x in self.powers]) if type(other) is float: inv_exp = 1. / other rounded = int(umath.floor(inv_exp + 0.5)) if abs(inv_exp - rounded) < 1.e-10: if reduce(lambda a, b: a and b, map(lambda x, e=rounded: x % e == 0, self.powers)): f = pow(self.factor, other) p = [x / rounded for x in self.powers] if reduce( lambda a, b: a and b, map(lambda x, e=rounded: x % e == 0, self.names.values())): names = self.names / rounded else: names = numberdict.NumberDict(default=0) if f != 1.: names[str(f)] = 1 for i in range(len(p)): names[_base_names[i]] = p[i] return PhysicalUnit(names, f, p) else: raise TypeError('Illegal exponent') raise TypeError('Only integer and inverse integer exponents allowed')
def __init__(self, names, factor, powers, offset=0): if isinstance(names, basestring): self.names = numberdict.NumberDict(default=0) self.names[names] = 1 else: self.names = names self.factor = float(factor) self.offset = offset self.powers = powers
def __truediv__(self, other): if self.offset != 0 or (isPhysicalUnit(other) and other.offset != 0): raise TypeError("cannot divide units with non-zero offset") if isPhysicalUnit(other): return PhysicalUnit(self.names - other.names, self.factor / other.factor, list(map(lambda a,b: a - b, self.powers, other.powers))) else: return PhysicalUnit(self.names + numberdict.NumberDict({str(other): -1}, default=0), self.factor/float(other), self.powers)
def setName(self, name): self.names = numberdict.NumberDict(default=0) self.names[name] = 1