[Tutor] converting decimals to fractions
Blake.Garretson@dana.com
Blake.Garretson@dana.com
Mon, 8 Oct 2001 14:37:12 -0400
Thanks, Tim! I have an uncanny knack for finding a brute force method even
if there is a more obvious and very elegant solution available. Thanks for
the great code.
Blake Garretson
"Tim Peters"
<tim.one@home To: <Blake.Garretson@dana.com>, <tutor@python.org>
.com> cc:
Subject: RE: [Tutor] converting decimals to fractions
10/08/2001
01:47 PM
>def tofrac(x, largest_denominator=32):
> """Return triple (i, j, k) where x ~= i + j/k.
>
> x >= 0 is required.
> i, j and k are integers >= 0, and k is > 0.
> j and k have no factors in common, unless j is 0.
>
> Optional argument largest_denominator (default 32) should be a
> power of 2, and is the largest value k can have.
> """
>
> if not x >= 0:
> raise ValueError("x must be >= 0")
> scaled = int(round(x * largest_denominator))
> whole, leftover = divmod(scaled, largest_denominator)
> if leftover:
> while leftover % 2 == 0:
> leftover >>= 1
> largest_denominator >>= 1
> return whole, leftover, largest_denominator