fractions — 有理数

源代码: Lib/fractions.py


The fractions 模块提供有理数算术支持。

Fraction 实例可以构造自一对整数、另一有理数或字符串。

class fractions. Fraction ( numerator = 0 , denominator = 1 )
class fractions. Fraction ( other_fraction )
class fractions. Fraction ( float )
class fractions. Fraction ( decimal )
class fractions. Fraction ( string )

第 1 个版本要求 numerator and denominator 是实例化的 numbers.Rational 并返回新的 Fraction 实例采用值 numerator/denominator 。若 denominator is 0 ,引发 ZeroDivisionError 。第 2 个版本要求 other_fraction 是实例化的 numbers.Rational 并返回 Fraction instance with the same value. The next two versions accept either a float decimal.Decimal instance, and return a Fraction instance with exactly the same value. Note that due to the usual issues with binary floating point (see 浮点算术:问题和局限性 ), the argument to Fraction(1.1) is not exactly equal to 11/10, and so Fraction(1.1) does not return Fraction(11, 10) as one might expect. (But see the documentation for the limit_denominator() method below.) The last version of the constructor expects a string or unicode instance. The usual form for this instance is:

[sign] numerator ['/' denominator]