# [Numpy-svn] r3641 - in trunk/numpy/core: . tests

numpy-svn@scip... numpy-svn@scip...
Mon Apr 2 07:06:10 CDT 2007

Author: cookedm
Date: 2007-04-02 07:06:06 -0500 (Mon, 02 Apr 2007)
New Revision: 3641

Modified:
trunk/numpy/core/numeric.py
trunk/numpy/core/tests/test_numeric.py
Log:
binary_repr handles negative numbers now, and takes an optional width argument.
base_repr raise ValueError if the number is negative or base > 36

Modified: trunk/numpy/core/numeric.py
===================================================================
--- trunk/numpy/core/numeric.py	2007-04-02 06:56:49 UTC (rev 3640)
+++ trunk/numpy/core/numeric.py	2007-04-02 12:06:06 UTC (rev 3641)
@@ -546,29 +546,44 @@
'F':'1111',
'L':''}

-def binary_repr(num):
+def binary_repr(num, width=None):
"""Return the binary representation of the input number as a string.

This is equivalent to using base_repr with base 2, but about 25x
faster.
+
+    For negative numbers, if width is not given, a - sign is added to the
+    front. If width is given, the two's complement of the number is
+    returned, with respect to that width.
"""
+    sign = ''
+    if num < 0:
+        if width is None:
+            sign = '-'
+            num = -num
+        else:
+            # replace num with its 2-complement
+            num = 2**width + num
+    elif num == 0:
+        return '0'
ostr = hex(num)
-    bin = ''
-    for ch in ostr[2:]:
-        bin += _lkup[ch]
-    if '1' in bin:
-        ind = 0
-        while bin[ind] == '0':
-            ind += 1
-        return bin[ind:]
-    else:
-        return '0'
+    bin = ''.join([_lkup[ch] for ch in ostr[2:]])
+    bin = bin.lstrip('0')
+    if width is not None:
+        bin = bin.zfill(width)
+    return sign + bin

-    """Return the representation of a number in any given base.
+    """Return the representation of a number in the given base.
+
+    Base can't be larger than 36.
"""
+    if number < 0:
+        raise ValueError("negative numbers not handled in base_repr")
+    if base > 36:
+        raise ValueError("bases greater than 36 not handled in base_repr")
+
chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-
import math
lnb = math.log(base)

Modified: trunk/numpy/core/tests/test_numeric.py
===================================================================
--- trunk/numpy/core/tests/test_numeric.py	2007-04-02 06:56:49 UTC (rev 3640)
+++ trunk/numpy/core/tests/test_numeric.py	2007-04-02 12:06:06 UTC (rev 3641)
@@ -248,6 +248,9 @@
def test_large(self):
assert_equal(binary_repr(10736848),'101000111101010011010000')

+    def test_negative(self):
+        assert_equal(binary_repr(-1), '-1')
+        assert_equal(binary_repr(-1, width=8), '11111111')

def assert_array_strict_equal(x, y):
assert_array_equal(x, y)