# `fractions` --- 有理数¶

`fractions` 模块支持分数运算。

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

The first version requires that numerator and denominator are instances of `numbers.Rational` and returns a new `Fraction` instance with value `numerator/denominator`. If denominator is `0`, it raises a `ZeroDivisionError`. The second version requires that other_fraction is an instance of `numbers.Rational` and returns a `Fraction` instance with the same value. The next two versions accept either a `float` or a `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 Floating-Point Arithmetic: Issues and Limitations), 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]
```

```>>> from fractions import Fraction
>>> Fraction(16, -10)
Fraction(-8, 5)
>>> Fraction(123)
Fraction(123, 1)
>>> Fraction()
Fraction(0, 1)
>>> Fraction('3/7')
Fraction(3, 7)
>>> Fraction(' -3/7 ')
Fraction(-3, 7)
>>> Fraction('1.414213 \t\n')
Fraction(1414213, 1000000)
>>> Fraction('-.125')
Fraction(-1, 8)
>>> Fraction('7e-6')
Fraction(7, 1000000)
>>> Fraction(2.25)
Fraction(9, 4)
>>> Fraction(1.1)
Fraction(2476979795053773, 2251799813685248)
>>> from decimal import Decimal
>>> Fraction(Decimal('1.1'))
Fraction(11, 10)
```

`Fraction` 类继承自抽象基类 `numbers.Rational`，并实现了该类的所有方法和操作。 `Fraction` 实例是 hashable 对象，并应当被视为不可变对象。 此外，`Fraction` 还具有以下特征属性和方法:

numerator

denominator

as_integer_ratio()

is_integer()

classmethod from_float(flt)

classmethod from_decimal(dec)

limit_denominator(max_denominator=1000000)

```>>> from fractions import Fraction
>>> Fraction('3.1415926535897932').limit_denominator(1000)
Fraction(355, 113)
```

```>>> from math import pi, cos
>>> Fraction(cos(pi/3))
Fraction(4503599627370497, 9007199254740992)
>>> Fraction(cos(pi/3)).limit_denominator()
Fraction(1, 2)
>>> Fraction(1.1).limit_denominator()
Fraction(11, 10)
```
__floor__()

```>>> from math import floor
>>> floor(Fraction(355, 113))
3
```
__ceil__()

__round__()
__round__(ndigits)

__format__(format_spec, /)

```>>> from fractions import Fraction
>>> format(Fraction(1, 7), '.40g')
'0.1428571428571428571428571428571428571429'
>>> format(Fraction('1234567.855'), '_.2f')
'1_234_567.86'
>>> f"{Fraction(355, 113):*>20.6e}"
'********3.141593e+00'
>>> old_price, new_price = 499, 672
>>> "{:.2%} price increase".format(Fraction(new_price, old_price) - 1)
'34.67% price increase'
```

`numbers` 模块