MCPcopy Index your code
hub / github.com/python/cpython / from_number

Method from_number

Lib/fractions.py:314–333  ·  view source on GitHub ↗

Converts a finite real number to a rational number, exactly. Beware that Fraction.from_number(0.3) != Fraction(3, 10).

(cls, number)

Source from the content-addressed store, hash-verified

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):

Callers 4

checkMethod · 0.45
test_from_numberMethod · 0.45
checkMethod · 0.45
test_from_numberMethod · 0.45

Calls 2

_from_coprime_intsMethod · 0.80
as_integer_ratioMethod · 0.45

Tested by 4

checkMethod · 0.36
test_from_numberMethod · 0.36
checkMethod · 0.36
test_from_numberMethod · 0.36