代码之家  ›  专栏  ›  技术社区  ›  rubik

如何将特殊浮点转换为分数对象

  •  0
  • rubik  · 技术社区  · 15 年前

    我在另一个函数中有这个函数:

    def _sum(k):
            return sum([(-1) ** v * fractions.Fraction(str(bin_coeff(k, v))) * fractions.Fraction((n + v) ** m, k + 1) for v in xrange(k + 1)])
    

    当我调用fractions.Fraction on bin_coeff时,它会报告我以下错误:

    ValueError: Invalid literal for Fraction: '1.05204948186e+12'
    

    我怎样才能把这种形式的浮点数转换成分数对象呢?

    fractions.Fraction(*bin_coeff(k, v).as_integer_ratio())
    

    谢谢您,
    鲁比克

    P、 S.binúcoeff总是返回一个float

    2 回复  |  直到 14 年前
        1
  •  1
  •   SilentGhost    15 年前

    我无法重现你在py3k中的错误,但你可以把你的浮球直接传给 from_float 类方法:

    >>> fractions.Fraction.from_float(1.05204948186e+12)
    Fraction(1052049481860, 1)
    
        2
  •  1
  •   Katriel    15 年前

    如果你好奇,这是(正如你所料)由于 Fraction fractions.py :

    _RATIONAL_FORMAT = re.compile(r"""
        \A\s*                      # optional whitespace at the start, then
        (?P<sign>[-+]?)            # an optional sign, then
        (?=\d|\.\d)                # lookahead for digit or .digit
        (?P<num>\d*)               # numerator (possibly empty)
        (?:                        # followed by an optional
           /(?P<denom>\d+)         # / and denominator
        |                          # or
           \.(?P<decimal>\d*)      # decimal point and fractional part
        )?
        \s*\Z                      # and optional whitespace to finish
    """, re.VERBOSE)
    

    _RATIONAL_FORMAT = re.compile(r"""
        \A\s*                      # optional whitespace at the start, then
        (?P<sign>[-+]?)            # an optional sign, then
        (?=\d|\.\d)                # lookahead for digit or .digit
        (?P<num>\d*)               # numerator (possibly empty)
        (?:                        # followed by
           (?:/(?P<denom>\d+))?    # an optional denominator
        |                          # or
           (?:\.(?P<decimal>\d*))? # an optional fractional part
           (?:E(?P<exp>[-+]?\d+))? # and optional exponent
        )
        \s*\Z                      # and optional whitespace to finish
    """, re.VERBOSE | re.IGNORECASE)