Skip to content

Instantly share code, notes, and snippets.

@deckar01
Created June 29, 2025 23:42
Show Gist options
  • Save deckar01/3f93802329debe116b0c3570bed65de2 to your computer and use it in GitHub Desktop.
Save deckar01/3f93802329debe116b0c3570bed65de2 to your computer and use it in GitHub Desktop.
What if float32 had 31 exponent bits and no mantissa?
import matplotlib.pyplot as plt
import numpy as np
def bits_to_float32(n, E=8, M=23):
sign = (n >> (E + M)) & 1
exponent = ((n >> M) & (2 ** E - 1)) - (2 ** (E - 1) - 1)
exponent *= 2 ** (8 - E)
mantissa = n & (2 ** M - 1)
return ((-1) ** sign) * (1 + mantissa / (2 ** M)) * (2 ** exponent)
stride = 2**12
bins = np.linspace(-4, 4, 2 ** 10)
dist32f = [bits_to_float32(n) for n in range(0, 2**32, stride)]
dist32c = [bits_to_float32(n, 31, 0) for n in range(0, 2**32, stride)]
plt.style.use('dark_background')
plt.hist(
[dist32c, dist32f],
bins,
label=['Exp-8', '32-bit Float'],
color=['red', 'blue',],
alpha=0.75,
histtype="step",
)
plt.xlim(bins[0], bins[-1])
plt.yscale('log')
plt.xlabel('Amplitude')
plt.ylabel('Resolution')
plt.legend()
plt.title('Audio Bit Depth')
plt.show()
@deckar01
Copy link
Author

Screenshot 2025-06-29 at 6 39 45 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment