Converts a finite real number to a rational number, exactly. Beware that Fraction.from_number(0.3) != Fraction(3, 10).
(cls, number)
| 312 | |
| 313 | @classmethod |
| 314 | def from_number(cls, number): |
| 315 | """Converts a finite real number to a rational number, exactly. |
| 316 | |
| 317 | Beware that Fraction.from_number(0.3) != Fraction(3, 10). |
| 318 | |
| 319 | """ |
| 320 | if type(number) is int: |
| 321 | return cls._from_coprime_ints(number, 1) |
| 322 | |
| 323 | elif isinstance(number, numbers.Rational): |
| 324 | return cls._from_coprime_ints(number.numerator, number.denominator) |
| 325 | |
| 326 | elif (isinstance(number, float) or |
| 327 | (not isinstance(number, type) and |
| 328 | hasattr(number, 'as_integer_ratio'))): |
| 329 | return cls._from_coprime_ints(*number.as_integer_ratio()) |
| 330 | |
| 331 | else: |
| 332 | raise TypeError("argument should be a Rational instance or " |
| 333 | "have the as_integer_ratio() method") |
| 334 | |
| 335 | @classmethod |
| 336 | def from_float(cls, f): |