1 # For licensing info see the included LICENSE file
3 # Josef Moudrik, <J dot Moudrik at standard google mail ending>, 2012
5 # -*- coding: utf-8 -*-
9 from exc
import IncompatibleUnits
12 def units_op(u1
, u2
, op
):
14 for k
in u1
.viewkeys() | u2
.viewkeys():
15 v1
, v2
= u1
.get(k
, 0), u2
.get(k
, 0)
21 def units_diff(u1
, u2
):
22 return units_op(u1
, u2
, lambda x
, y
: x
- y
)
24 def units_join(u1
, u2
):
25 return units_op(u1
, u2
, lambda x
, y
: x
+ y
)
28 def __init__(self
, value
, sdsq
=0, units
=None, string
='', parents
=None):
32 self
.value
= float(value
)
36 self
.parents
= parents
38 def __add__(self
, other
):
39 return operators
.Plus()((self
, other
))
41 def __sub__(self
, other
):
42 return operators
.Minus()((self
, other
))
44 def __mul__(self
, other
):
45 return operators
.Mult()((self
, other
))
47 def __rmul__(self
, other
):
48 assert isinstance(other
, int) or isinstance(other
, float)
50 return operators
.Times(other
)((self
,))
52 def __div__(self
, other
):
53 return operators
.Div()((self
, other
))
55 def getDifference(self
, other
):
57 if self
.getUnits() != other
.getUnits():
58 raise IncompatibleUnits
62 diff
= abs(1.0 - other
.getValue() / self
.getValue())
64 op
= other
.getSdPerc()
73 def getSdSquare(self
):
77 return math
.sqrt(self
.getSdSquare())
80 return self
.getSd() / abs(self
.getValue())
87 for key
in sorted(self
.units
.keys()):
95 return self
.headStr() + " = " + str(self
)
98 return u
'%.4f ± %.4f %s'%(self
.getValue(), self
.getSd(), self
.strUnits())
103 s
+= "(%s)"%(', '.join(map(str, self
.parents
), ), )