Skip to content

Instantly share code, notes, and snippets.

@jonathanschilling
Last active May 19, 2022 20:11
Show Gist options
  • Save jonathanschilling/77bbf8b92d46b1eaef7237a97762bd81 to your computer and use it in GitHub Desktop.
Save jonathanschilling/77bbf8b92d46b1eaef7237a97762bd81 to your computer and use it in GitHub Desktop.
Convert IEEE754 double precision into mpmath arbitrary precision
import mpmath as mp
# default number of digits of precision for calculations
mp.mp.dps = 300
# frequently-used constants with arbitrary precision
zero = mp.mpf("0")
one = mp.mpf("1")
two = mp.mpf("2")
# constants used in the definition of IEEE754 double precision variables
exponentBias = mp.mpf("1023")
mantissaScale = mp.power(two, mp.mpf("52"))
def ieee754_to_arb(s, E, M):
'''
Given three integers, compute an arbitrary-precision equivalent
of the 64-bit double precision variable F
represented by s, E and M according to:
F = (-1)^s * 2^(E - 1023) * (1 + M/2^52)
Only one of the IEEE754 special cases is handled here,
which is an exact zero (s ignored, E=0, M=0).
Parameters:
s (unsigned int): 0 or 1; sign bit
E (unsigned int): 0, 1, ..., 2047; exponent (11 bit)
M (unsigned int): 0, 1, ... (2^52-1); mantissa (52-bit)
'''
# capture exact zero
if E == 0 and M == 0:
return zero
# parse sign bit
# 0 means positive, 1 means negative, as in (-1)^s
sign = None
if s == 0:
sign = one
else:
sign = -one
# compute exact representation of double precision variable
return sign * mp.power(two, E - exponentBias) * (one + M/mantissaScale)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment