1 # -*- coding: utf-8 -*-
5 from exc
import IncompatibleUnits
8 def units_op(u1
, u2
, op
):
10 for k
in u1
.viewkeys() | u2
.viewkeys():
11 v1
, v2
= u1
.get(k
, 0), u2
.get(k
, 0)
17 def units_diff(u1
, u2
):
18 return units_op(u1
, u2
, lambda x
, y
: x
- y
)
20 def units_join(u1
, u2
):
21 return units_op(u1
, u2
, lambda x
, y
: x
+ y
)
24 def __init__(self
, value
, sdsq
=0, units
=None, string
='', parents
=None):
28 self
.value
= float(value
)
32 self
.parents
= parents
34 def __add__(self
, other
):
35 return operators
.Plus()((self
, other
))
37 def __sub__(self
, other
):
38 return operators
.Minus()((self
, other
))
40 def __mul__(self
, other
):
41 return operators
.Mult()((self
, other
))
43 def __rmul__(self
, other
):
44 assert isinstance(other
, int) or isinstance(other
, float)
46 return operators
.Times(other
)((self
,))
48 def __div__(self
, other
):
49 return operators
.Div()((self
, other
))
51 def getDifference(self
, other
):
53 if self
.getUnits() != other
.getUnits():
54 raise IncompatibleUnits
58 diff
= abs(1.0 - other
.getValue() / self
.getValue())
60 op
= other
.getSdPerc()
69 def getSdSquare(self
):
73 return math
.sqrt(self
.getSdSquare())
76 return self
.getSd() / abs(self
.getValue())
83 for key
in sorted(self
.units
.keys()):
91 return self
.headStr() + " = " + str(self
)
94 return u
'%.4f ± %.4f %s'%(self
.getValue(), self
.getSd(), self
.strUnits())
99 s
+= "(%s)"%(', '.join(map(str, self
.parents
), ), )