[Edu-sig] Basic dictionary question
Kirby Urner
urnerk at qwest.net
Sun Oct 9 06:23:27 CEST 2005
So here's my situation. I have a set of XYZ tuples that'll come very close
to matching, most of them in pairs, but thanks to floating point, I can only
rely on "fuzzy equality" i.e. within a tolerance of say |e| per each x,y,z.
In other words, for all intents and purposes, I could consider (1.0, 0.0,
0.0) and (1.001, 0.0, 0.0) to be the same.
My thought was to use a dictionary, indexing with these tuples. Except they
wouldn't be primitive tuples, I'd define an object with fuzzy equality
implemented as __eq__. Then (1.0, 0.0, 0.0) and (1.001, 0.0, 0.0) would
both key to the same value, cuz they're equal i.e. are both the same key,
right?
Wrong I think, per the session below. The one object (1.0, 0.0, 0.0) is
"in" a list of other objects (o1), thanks to fuzzy equality, but in adding
to a dictionary, they key separately. Instead of figuring it all out, lemme
just put this out and there see if I fish up any expert patter.
Kirby
>> class Sometuple(object):
e = 0.01
def __init__(self,value):
self.thetuple = value
def __eq__(self, other):
if abs(self.thetuple[0]-other.thetuple[0])<self.e \
and abs(self.thetuple[1]-other.thetuple[1])<self.e \
and abs(self.thetuple[2]-other.thetuple[2])<self.e :
return True
else:
return False
>>> o0 = Sometuple((1,0,0))
>>> o1 = Sometuple((1.001,0,0))
>>> o0==o1
True
>>> thedict = {o0:'a'}
>>> thedict
{<__main__.Sometuple object at 0x00C93B90>: 'a'}
>>> thedict[o1]='b'
>>> thedict
{<__main__.Sometuple object at 0x00C93B90>: 'a', <__main__.Sometuple object
at 0x00C93D10>: 'b'}
>>> o0 in [o1,o1,01]
True
>>> o0 in [o1,o1,o1]
True
>>> o1 in thedict.keys()
True
>>> o0 in thedict.keys()
True
More information about the Edu-sig
mailing list