Guest User

Untitled

a guest
Oct 18th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.42 KB | None | 0 0
  1. def float_to_decimal(f):
  2. "Convert a floating point number to a Decimal with no loss of information"
  3. n, d = f.as_integer_ratio()
  4. numerator, denominator = Decimal(n), Decimal(d)
  5. ctx = Context(prec=60)
  6. result = ctx.divide(numerator, denominator)
  7. while ctx.flags[Inexact]:
  8. ctx.flags[Inexact] = False
  9. ctx.prec *= 2
  10. result = ctx.divide(numerator, denominator)
  11. return result
Add Comment
Please, Sign In to add comment