问题
How to work with equivalent of __float128
in Python? What precision should I use for decimal.getcontext()
? I mean, is the precision specified in decimal places or bits?
from decimal import *
getcontext().prec = # 34 or 128 ?
Is it possible to set the precision "locally" for a given operation, rather than setting it "globally" with getcontext().prec
?
Per Simon Byrne comment, is it even possible to simulate __float128
as defined by IEEE 754 with Decimal
? What other options do I have in Python, if I wanted quadruple-precision?
回答1:
I'm the maintainer of gmpy2
. In addition to wrapping MPFR, gmpy2
also wraps GMP (for integer and rational numbers) and MPC (for complex arithmetic). Both MPFR and MPC use a binary representation compared to Decimal
which uses a decimal representation.
Here is a quick example showing use of the equivalent of float128
.
>>> import gmpy2
>>> gmpy2.set_context(gmpy2.ieee(128))
>>> gmpy2.get_context()
context(precision=113, real_prec=Default, imag_prec=Default,
round=RoundToNearest, real_round=Default, imag_round=Default,
emax=16384, emin=-16493,
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.sin(gmpy2.mpfr("1.2"))
mpfr('0.932039085967226349670134435494826026',113)
For the 2.0.x series, gmpy2.ieee()
only creates contexts for supporting 32, 64, or 128-bit formats. The development branch supports are wider range of precisions.
回答2:
Unfortunately, Python has native support for only one single floating point type, the double type of the underlying architecture.
Depending on the architecture, numpy can declare a float128, but it is known not to be consistently available.
If you need it outside of numpy, (or on a platform where numpy does not support it), you could have a look the the bigfloat package on pypi which is a wrapper around GNU MPFR library. But beware, it is currently declared at beta level and you must be prepared to build it from sources.
After @MarkDickinson's comment (he is the author of bigfloat), gmpy2 is another wrapper around MPFR which is declared stable on pypi and is both richer and better maintained.
来源:https://stackoverflow.com/questions/41975886/equivalent-of-float128