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
1 changed files with 7 additions and 7 deletions

View File

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