Added license info into the .py files.
[golden_search.git] / number.py
blob98f796f840932e8f694221b2662f943fd3e2c008
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 -*-
7 import math
9 from exc import IncompatibleUnits
10 import operators
12 def units_op(u1, u2, op):
13 u = {}
14 for k in u1.viewkeys() | u2.viewkeys():
15 v1, v2 = u1.get(k, 0), u2.get(k, 0)
16 v = op( v1, v2 )
17 if v != 0:
18 u[k] = v
19 return u
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)
27 class Number:
28 def __init__(self, value, sdsq=0, units=None, string='', parents=None):
29 if units == None:
30 units = {}
32 self.value = float(value)
33 self.sdsq = sdsq
34 self.units = units
35 self.string = string
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):
56 # TODO lip??
57 if self.getUnits() != other.getUnits():
58 raise IncompatibleUnits
60 assert self.sdsq == 0
62 diff = abs(1.0 - other.getValue() / self.getValue())
64 op = other.getSdPerc()
65 if diff < op:
66 return op
68 return diff
70 def getValue(self):
71 return self.value
73 def getSdSquare(self):
74 return self.sdsq
76 def getSd(self):
77 return math.sqrt(self.getSdSquare())
79 def getSdPerc(self):
80 return self.getSd() / abs(self.getValue())
82 def getUnits(self):
83 return self.units
85 def strUnits(self):
86 l=[]
87 for key in sorted(self.units.keys()):
88 l.append(key)
89 v = self.units[key]
90 if v != 1:
91 l.append( '^%d'%(v,))
92 return ''.join(l)
94 def longStr(self):
95 return self.headStr() + " = " + str(self)
97 def headStr(self):
98 return u'%.4f ± %.4f %s'%(self.getValue(), self.getSd(), self.strUnits())
100 def __str__(self):
101 s = self.string
102 if self.parents:
103 s += "(%s)"%(', '.join(map(str, self.parents), ), )
104 return s