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

时间:2010-10-20 13:06:29

标签: python floating-point fractions

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

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)])

当我在bin_coeff上调用fractions.Fraction时,它会报告我这个错误:

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

如何将该表单中的float转换为Fraction对象?

是否有比以下更好的解决方案:

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

谢谢你,
魔方

P.S。 bin_coeff总是返回一个浮点数

2 个答案:

答案 0 :(得分:1)

我无法在py3k中重现您的错误,但您可以将您的浮动直接传递给from_float类方法:

>>> fractions.Fraction.from_float(1.05204948186e+12)
Fraction(1052049481860, 1)

答案 1 :(得分:1)

如果您感到好奇,这应该(正如您所料)到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)

与科学记数法中的浮点数不匹配。这在Python 2.7中有所改变(以下是3.1,因为我没有安装2.7):

_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)