← Back to team overview

python-quantities-developers team mailing list archive

[Bug 386208] Re: Dimensionality comparison bug: unit^-1 = unit^-2 because of hash ambiguity

 

** Changed in: python-quantities
    Milestone: None => 0.5.0

-- 
Dimensionality comparison bug: unit^-1 = unit^-2 because of hash ambiguity
https://bugs.launchpad.net/bugs/386208
You received this bug notification because you are a member of Python
Quantities Development Team, which is subscribed to python-quantities.

Status in Physical Quantities for Python: Fix Committed

Bug description:
Dimensionality comparison is incorrect when comparing units raised to -1 and -2. Here's a simple example demonstrating the bug:

>>> import quantities as pq
>>> v = 1 * pq.m / pq.s
>>> v.units = pq.m / pq.s**2

This seems to stem from the fact that -1 and -2 have the same hash value. In other words:

>>> hash(-1)
-2
>>> hash(-2)
-2

I thought this was some weird error on my system until I saw the following description of python's hash algorithm for integers:
http://effbot.org/zone/python-hash.htm

I'm not sure what the appropriate fix is; shifting all negative numbers by -1 seems to work (see patch below).

Cheers,
-Tony

OS X 10.5.7
python 2.5.1
quantities 0.5b3


=== modified file 'quantities/dimensionality.py'
--- quantities/dimensionality.py	2009-02-22 22:58:09 +0000
+++ quantities/dimensionality.py	2009-06-12 03:39:40 +0000
@@ -53,6 +53,8 @@
         res = hash(unit_registry['dimensionless'])
         for key in sorted(self.keys(), key=operator.attrgetter('format_order')):
             val = self[key]
+            if val < 0:
+                val -= 1
             res ^= hash((key, val))
         return res