Last active
November 10, 2021 16:36
-
-
Save llandsmeer/ac33eef8c2bcd1d9eac312fddf550c21 to your computer and use it in GitHub Desktop.
Stupid float implementation from uint8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def to_float32(exponent, significand): | |
assert exponent.dtype == np.uint8 | |
assert significand.dtype == np.uint8 | |
negative = ((exponent & 128) >> 7) == 1 | |
exponent = (exponent & 127).astype(float)-64 | |
value = 2.0**exponent * (1.0 + significand.astype(float) / 256.0) | |
value[negative] *= -1 | |
return value | |
def from_float32(value): | |
sign = (128 * (value < 0)).astype(np.uint8) | |
value = abs(value) | |
exponent = np.floor(np.log2(value)) | |
if (exponent >= 64).any() or (exponent <= -65).any(): | |
raise ValueError('doesnt fit in exponent') | |
significand = (value / 2**exponent - 1) * 256 | |
exponent = ((exponent+64).astype(np.uint8)) | sign | |
significand = significand.astype(np.uint8) | |
return exponent, significand | |
es = np.arange(256*256, dtype=np.uint16) | |
e, s = (es >> 8).astype(np.uint8), (es & 255).astype(np.uint8) | |
v = to_float32(e, s) | |
e2, s2 = from_float32(v) | |
v2 = to_float32(e2, s2) | |
print('exp ok?', (e2 == e).mean()) | |
print('sig ok?', (s2 == s).mean()) | |
print('v ok?', (v2 == v).mean()) | |
print('order+ ok?', (np.diff(v[v>0]) > 0).mean()) | |
print('order- ok?', (np.diff(v[v<0]) < 0).mean()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment