Reputation: 2918
I have the need to compute exactly in single precision floating points in Python.
The options I've tried are decimal.Decimal
and numpy.float32
. However Decimal
is not based on IEEE 754, and float32
cannot allow the use of rounding modes. It is surprising rounding modes are standard features of IEEE 754 but there exists no built-in implementation of it in Python.
Upvotes: 3
Views: 1220
Reputation: 11424
The gmpy2 library will do what you want.
>>> import gmpy2
>>> gmpy2.set_context(gmpy2.ieee(32))
>>> ctx=gmpy2.get_context()
>>> ctx
context(precision=24, real_prec=Default, imag_prec=Default,
round=RoundToNearest, real_round=Default, imag_round=Default,
emax=128, emin=-148,
subnormalize=True,
trap_underflow=False, underflow=False,
trap_overflow=False, overflow=False,
trap_inexact=False, inexact=False,
trap_invalid=False, invalid=False,
trap_erange=False, erange=False,
trap_divzero=False, divzero=False,
trap_expbound=False,
allow_complex=False)
>>> gmpy2.const_pi().digits(2)
('110010010000111111011011', 2, 24)
>>> ctx.round=gmpy2.RoundDown
>>> gmpy2.const_pi().digits(2)
('110010010000111111011010', 2, 24)
>>> ctx.round=gmpy2.RoundUp
>>> gmpy2.const_pi().digits(2)
('110010010000111111011011', 2, 24)
>>>
gmpy2 provides access to the GMP, MPFR, and MPC arbitrary-precision libraries. MPFR support correctly rounded arithmetic for user-definable precision and exponent limits.
Disclaimer: I maintain gmpy2.
Upvotes: 2