<p>我先从<code>sig2int</code>。。从符号表示转换为二进制</p>
<pre><code>>>> a
array([ 1., -1., 1., -1.])
>>> (a + 1) / 2
array([ 1., 0., 1., 0.])
>>>
</code></pre>
<p>然后你可以简单地创建一个2的幂的数组,乘以二进制数,然后求和。在</p>
^{pr2}$
<p>然后通过添加轴信息并依赖广播使其对行进行操作。在</p>
<pre><code>def sign2int(a):
# powers of two
powers = np.arange(a.shape[-1])[::-1]
np.power(2, powers, powers)
# sign to "binary" - add one and divide by two
np.add(a, 1, a)
np.divide(a, 2, a)
# scale by powers of two and sum
np.multiply(a, powers, a)
return np.sum(a, axis = -1)
>>> b = np.array([a, a, a, a, a])
>>> sign2int(b)
array([ 11., 11., 11., 11., 11.])
>>>
</code></pre>
<p>我在一个4乘100位的数组上尝试过,它看起来很快</p>
<pre><code>>>> a = a.repeat(100)
>>> b = np.array([a, a, a, a, a])
>>> b
array([[ 1., 1., 1., ..., 1., 1., 1.],
[ 1., 1., 1., ..., 1., 1., 1.],
[ 1., 1., 1., ..., 1., 1., 1.],
[ 1., 1., 1., ..., 1., 1., 1.],
[ 1., 1., 1., ..., 1., 1., 1.]])
>>> sign2int(b)
array([ 2.58224988e+120, 2.58224988e+120, 2.58224988e+120,
2.58224988e+120, 2.58224988e+120])
>>>
</code></pre>
<hr/>
<p>如果我能想到的话,我会加上相反的。-我所能做的最好的方法就是使用一些没有任何numpy向量化魔法的纯Python,除了一次迭代并转换一个int之外,我还不知道如何使它与一系列int一起工作,但是时间似乎还是可以接受的。在</p>
<pre><code>def foo(n):
'''yields bits in increasing powers of two
bit sequence from lsb --> msb
'''
while n > 0:
n, r = divmod(n, 2)
yield r
def int2sign(n):
n = int(n)
a = np.fromiter(foo(n), dtype = np.int8, count = n.bit_length())
np.multiply(a, 2, a)
np.subtract(a, 1, a)
return a[::-1]
</code></pre>
<p>1324工程:</p>
<pre><code>>>> bin(1324)
'0b10100101100'
>>> a = int2sign(1324)
>>> a
array([ 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, -1], dtype=int8)
</code></pre>
<p>似乎适用于1.2e305:</p>
<pre><code>>>> n = int(1.2e305)
>>> n.bit_length()
1014
>>> a = int2sign(n)
>>> a.shape
(1014,)
>>> s = bin(n)
>>> s = s[2:]
>>> all(2 * int(x) -1 == y for x, y in zip(s, a))
True
>>>
</code></pre>