Skip to content

Commit

Permalink
Add bit_length emulator for python < 2.7
Browse files Browse the repository at this point in the history
  • Loading branch information
Vasiliy Evseenko committed Jun 3, 2014
1 parent bba717b commit d98f62a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
15 changes: 14 additions & 1 deletion hyperloglog/hll.py
Expand Up @@ -7,6 +7,19 @@
from const import rawEstimateData, biasData, tresholdData


def bit_length(w):
return w.bit_length()


def bit_length_emu(w):
return len(bin(w)) - 2 if w > 0 else 0


# Workaround for python < 2.7
if not hasattr(int, 'bit_length'):
bit_length = bit_length_emu


def get_treshold(p):
return tresholdData[p - 4]

Expand Down Expand Up @@ -40,7 +53,7 @@ def get_alpha(p):


def get_rho(w, max_width):
rho = max_width - w.bit_length() + 1
rho = max_width - bit_length(w) + 1

if rho <= 0:
raise ValueError('w overflow')
Expand Down
18 changes: 18 additions & 0 deletions hyperloglog/test/test_hll.py
Expand Up @@ -32,6 +32,24 @@ def test_rho(self):
self.assertEqual(get_rho(1 << 31, 32), 1)
self.assertRaises(ValueError, get_rho, 1 << 32, 32)

def test_rho_emu(self):
import hll
old = hll.bit_length
hll.bit_length = hll.bit_length_emu
try:
self.assertEqual(get_rho(0, 32), 33)
self.assertEqual(get_rho(1, 32), 32)
self.assertEqual(get_rho(2, 32), 31)
self.assertEqual(get_rho(3, 32), 31)
self.assertEqual(get_rho(4, 32), 30)
self.assertEqual(get_rho(5, 32), 30)
self.assertEqual(get_rho(6, 32), 30)
self.assertEqual(get_rho(7, 32), 30)
self.assertEqual(get_rho(1 << 31, 32), 1)
self.assertRaises(ValueError, get_rho, 1 << 32, 32)
finally:
hll.bit_length = old

def test_init(self):
s = HyperLogLog(0.05)
self.assertEqual(s.p, 9)
Expand Down

0 comments on commit d98f62a

Please sign in to comment.