Asymptotically fast conversion of an 'int' to Decimal.
(n)
| 137 | _unbounded_dec_context.traps[decimal.Inexact] = 1 # sanity check |
| 138 | |
| 139 | def int_to_decimal(n): |
| 140 | """Asymptotically fast conversion of an 'int' to Decimal.""" |
| 141 | |
| 142 | # Function due to Tim Peters. See GH issue #90716 for details. |
| 143 | # https://github.com/python/cpython/issues/90716 |
| 144 | # |
| 145 | # The implementation in longobject.c of base conversion algorithms |
| 146 | # between power-of-2 and non-power-of-2 bases are quadratic time. |
| 147 | # This function implements a divide-and-conquer algorithm that is |
| 148 | # faster for large numbers. Builds an equal decimal.Decimal in a |
| 149 | # "clever" recursive way. If we want a string representation, we |
| 150 | # apply str to _that_. |
| 151 | |
| 152 | from decimal import Decimal as D |
| 153 | BITLIM = 200 |
| 154 | |
| 155 | # Don't bother caching the "lo" mask in this; the time to compute it is |
| 156 | # tiny compared to the multiply. |
| 157 | def inner(n, w): |
| 158 | if w <= BITLIM: |
| 159 | return D(n) |
| 160 | w2 = w >> 1 |
| 161 | hi = n >> w2 |
| 162 | lo = n & ((1 << w2) - 1) |
| 163 | return inner(lo, w2) + inner(hi, w - w2) * w2pow[w2] |
| 164 | |
| 165 | with decimal.localcontext(_unbounded_dec_context): |
| 166 | nbits = n.bit_length() |
| 167 | w2pow = compute_powers(nbits, D(2), BITLIM) |
| 168 | if n < 0: |
| 169 | negate = True |
| 170 | n = -n |
| 171 | else: |
| 172 | negate = False |
| 173 | result = inner(n, nbits) |
| 174 | if negate: |
| 175 | result = -result |
| 176 | return result |
| 177 | |
| 178 | def int_to_decimal_string(n): |
| 179 | """Asymptotically fast conversion of an 'int' to a decimal string.""" |
no test coverage detected
searching dependent graphs…