Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access rounding modes defined in IEEE 754 in python?

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.

like image 581
koo Avatar asked Mar 13 '26 07:03

koo


1 Answers

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.

like image 64
casevh Avatar answered Mar 15 '26 19:03

casevh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!