Simplify one of the decimal recipes.

This commit is contained in:
Raymond Hettinger 2009-01-03 07:46:36 +00:00
parent fd6032d452
commit b3833ddecd

View file

@ -1880,13 +1880,13 @@ suggest, so we trap :const:`Inexact` to signal a need for more precision:
def float_to_decimal(f): def float_to_decimal(f):
"Convert a floating point number to a Decimal with no loss of information" "Convert a floating point number to a Decimal with no loss of information"
n, d = f.as_integer_ratio() n, d = f.as_integer_ratio()
with localcontext() as ctx: numerator, denominator = Decimal(n), Decimal(d)
ctx.traps[Inexact] = True ctx = Context(prec=60)
while True: result = ctx.divide(numerator, denominator)
try: while ctx.flags[Inexact]:
return Decimal(n) / Decimal(d) ctx.prec *= 2
except Inexact: result = ctx.divide(numerator, denominator)
ctx.prec += 1 return result
.. doctest:: .. doctest::