0

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

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'

如何将这种形式的浮点数转换为 Fraction 对象?

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

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

谢谢你,
魔方

PS bin_coeff 总是返回一个浮点数

4

2 回答 2

1

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

>>> fractions.Fraction.from_float(1.05204948186e+12)
Fraction(1052049481860, 1)
于 2010-10-20T13:10:23.280 回答
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)
于 2010-10-20T13:46:02.133 回答