Python Rational Numbers PDF
Python Rational Numbers PDF
1 22
Ex: −
2 7
Any real number with a finite number of digits after the decimal point is also a rational number
45 123456789
0.45 → 0.123456789 →
100 109
Rational numbers can be represented in Python using the Fraction class in the fractions module
Fraction(numerator=0, denominator=1)
Fraction(other_fraction)
Fraction(float)
Fraction(decimal)
Fraction(string)
Fraction('10') → Fraction(10, 1)
Fraction('0.125') → Fraction(1, 8)
Fraction('22/7') → Fraction(22, 7)
Standard arithmetic operators are supported: +, -, *, /
and result in Fraction objects as well
2 1 2 1
× = = Fraction(2, 3) * Fraction(1, 2) → Fraction(1, 3)
3 2 6 3
2 1 4 3 7
+ = + = Fraction(2, 3) + Fraction(1, 2) → Fraction(7, 6)
3 2 6 6 6
x = Fraction(22, 7)
x.numerator → 22
x.denominator →7
float objects have finite precision ⇒ any float object can be written as a fraction!
Fraction(0.75) → Fraction(3, 4)
Fraction(1.375) → Fraction(11, 8)
import math
1
has an exact float representation
8
Fraction(0.125) → Fraction(1, 8)
3
does not have an exact float representation
10
x.limit_denominator(10) → Fraction(22, 7)
3.142857142857143