Correctly-rounded true division for integers.
(a, b)
| 83 | |
| 84 | # pure Python version of correctly-rounded true division |
| 85 | def truediv(a, b): |
| 86 | """Correctly-rounded true division for integers.""" |
| 87 | negative = a^b < 0 |
| 88 | a, b = abs(a), abs(b) |
| 89 | |
| 90 | # exceptions: division by zero, overflow |
| 91 | if not b: |
| 92 | raise ZeroDivisionError("division by zero") |
| 93 | if a >= DBL_MIN_OVERFLOW * b: |
| 94 | raise OverflowError("int/int too large to represent as a float") |
| 95 | |
| 96 | # find integer d satisfying 2**(d - 1) <= a/b < 2**d |
| 97 | d = a.bit_length() - b.bit_length() |
| 98 | if d >= 0 and a >= 2**d * b or d < 0 and a * 2**-d >= b: |
| 99 | d += 1 |
| 100 | |
| 101 | # compute 2**-exp * a / b for suitable exp |
| 102 | exp = max(d, DBL_MIN_EXP) - DBL_MANT_DIG |
| 103 | a, b = a << max(-exp, 0), b << max(exp, 0) |
| 104 | q, r = divmod(a, b) |
| 105 | |
| 106 | # round-half-to-even: fractional part is r/b, which is > 0.5 iff |
| 107 | # 2*r > b, and == 0.5 iff 2*r == b. |
| 108 | if 2*r > b or 2*r == b and q % 2 == 1: |
| 109 | q += 1 |
| 110 | |
| 111 | result = math.ldexp(q, exp) |
| 112 | return -result if negative else result |
| 113 | |
| 114 | |
| 115 | class LongTest(unittest.TestCase): |
no test coverage detected
searching dependent graphs…