Alex
Alex

Reputation: 437

numpy array of arbitrary precision (10 bit int)

I need to simulate a piece of hardware that generates binary files where each word is 10 bits. How can I achieve this with a numpy array?

Something like:

outarray = np.zeros(512, dtype=np.int10)

Thanks!

Upvotes: 5

Views: 3585

Answers (2)

rwp
rwp

Reputation: 1886

Another option you could consider, if you're mainly interested in understanding the accuracy of arithmetic operations on 10-bit numbers, is to use the spfpm package. This will simulate the effect of fixed-point arithemetic operations, including multiplication, division, square-roots, trigonometric functions, etc., but doesn't currently support matrix operations.

Upvotes: 0

kuppern87
kuppern87

Reputation: 1135

Numpy doesn't have an uint10 type. But you can use uint16, and a bitmask to check for overflow. And use binary_rep to get the 10 bit binary representations:

import numpy as np

MAX_WORD = 2**10
unused_bits = ~np.array([MAX_WORD-1], dtype="uint16")  # Binary mask of the 6 unused_bits

words = np.random.randint(MAX_WORD, size=10, dtype="uint16")  #  Create 10 bit words
assert not np.any(words & unused_bits)  # Check for overflow
for word in words:
    print(word, np.binary_repr(word, width=10))  # Get 10 bit binary representation

binary_repr = "".join(np.binary_repr(word, width=10) for word in words)
print(binary_repr)  # Full binary representation

Upvotes: 3

Related Questions