Created
September 20, 2012 10:28
-
-
Save rvause/3755131 to your computer and use it in GitHub Desktop.
Support for decimals where your target might be Python older than 2.7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| from decimal import * | |
| LT_27 = True if sys.version_info < (2, 7) else False | |
| def f2d(f): | |
| """ | |
| Convert a floating point number to a Decimal with no loss of information | |
| from http://docs.python.org/release/2.6.7/library/decimal.html#decimal-faq | |
| """ | |
| n, d = f.as_integer_ratio() | |
| numerator, denominator = Decimal(n), Decimal(d) | |
| ctx = Context(prec=60) | |
| result = ctx.divide(numerator, denominator) | |
| while ctx.flags[Inexact]: | |
| ctx.flags[Inexact] = False | |
| ctx.prec *= 2 | |
| result = ctx.divide(numerator, denominator) | |
| return result | |
| def d(f): | |
| return f2d(f) if LT_27 else f |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment