Implementation limitations of float.as_integer_ratio()

后端 未结 3 635
情歌与酒
情歌与酒 2020-12-06 11:03

Recently, a correspondent mentioned float.as_integer_ratio(), new in Python 2.6, noting that typical floating point implementations are essentially rational approximations o

3条回答
  •  被撕碎了的回忆
    2020-12-06 11:59

    May I recommend gmpy's implementation of the Stern-Brocot tree:

    >>> import gmpy
    >>> import math
    >>> gmpy.mpq(math.pi)
    mpq(245850922,78256779)
    >>> x=_
    >>> float(x)
    3.1415926535897931
    >>> 
    

    again, the result is "correct within the precision of 64-bit floats" (53-bit "so-called" mantissas;-), but:

    >>> 245850922 + 78256779
    324107701
    >>> 884279719003555 + 281474976710656
    1165754695714211L
    >>> 428224593349304L + 136308121570117
    564532714919421L
    

    ...gmpy's precision is obtained so much cheaper (in terms of sum of numerator and denominator values) than Arima's, much less Python 2.6's!-)

提交回复
热议问题