Inspect binary float scale with Python frexp and ldexp
When numeric diagnostics need a value’s binary scale, separate its fraction from its power-of-two exponent. This avoids formatting a decimal string and then guessing which part describes the stored float.
Run the example
Tested on Linux with Python 3.12.14. No third-party packages are required. In one Bash session, create a disposable directory:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Save this as demo_python_frexp_ldexp_binary_scaling.py. Use that filename to avoid shadowing a standard-library module.
from math import frexp, ldexp
for value in (0.0, 12.0, -0.125, 0.1):
fraction, exponent = frexp(value)
restored = ldexp(fraction, exponent)
print(f"{value!r}: fraction={fraction!r}, exponent={exponent}, restored={restored == value}")
print("12 scaled down by 8:", ldexp(12.0, -3))
print("0.1 stored as:", (0.1).hex())Run it:
python3 demo_python_frexp_ldexp_binary_scaling.pyOutput:
0.0: fraction=0.0, exponent=0, restored=True
12.0: fraction=0.75, exponent=4, restored=True
-0.125: fraction=-0.5, exponent=-2, restored=True
0.1: fraction=0.8, exponent=-3, restored=True
12 scaled down by 8: 1.5
0.1 stored as: 0x1.999999999999ap-4The decomposition reconstructs the stored finite value. For a nonzero finite value, the absolute fraction is at least one half and less than one. The last line makes the binary representation of the decimal input visible; reconstruction does not imply that the input decimal was represented exactly.
Input policy and limits
Keep this technique separate from decimal digit extraction. Validate finite inputs before interpreting the exponent. Scaling by large powers can overflow, and scaling very small values downward can lose information through underflow; the exact reconstruction shown here uses each value’s own decomposition.
Clean up
In the same Bash session, remove the source file and the empty working directory:
rm -- demo_python_frexp_ldexp_binary_scaling.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirIf the directory is not empty, inspect its contents before deleting anything else.
References
Acknowledgements
This post was created with assistance from AI.