Round a rational number to the nearest multiple of a given power of 10. Rounds the rational number n/d to the nearest integer multiple of 10**exponent, rounding to the nearest even integer multiple in the case of a tie. Returns a pair (sign: bool, significand: int) representing the
(n, d, exponent, no_neg_zero=False)
| 71 | # Helpers for formatting |
| 72 | |
| 73 | def _round_to_exponent(n, d, exponent, no_neg_zero=False): |
| 74 | """Round a rational number to the nearest multiple of a given power of 10. |
| 75 | |
| 76 | Rounds the rational number n/d to the nearest integer multiple of |
| 77 | 10**exponent, rounding to the nearest even integer multiple in the case of |
| 78 | a tie. Returns a pair (sign: bool, significand: int) representing the |
| 79 | rounded value (-1)**sign * significand * 10**exponent. |
| 80 | |
| 81 | If no_neg_zero is true, then the returned sign will always be False when |
| 82 | the significand is zero. Otherwise, the sign reflects the sign of the |
| 83 | input. |
| 84 | |
| 85 | d must be positive, but n and d need not be relatively prime. |
| 86 | """ |
| 87 | if exponent >= 0: |
| 88 | d *= 10**exponent |
| 89 | else: |
| 90 | n *= 10**-exponent |
| 91 | |
| 92 | # The divmod quotient is correct for round-ties-towards-positive-infinity; |
| 93 | # In the case of a tie, we zero out the least significant bit of q. |
| 94 | q, r = divmod(n + (d >> 1), d) |
| 95 | if r == 0 and d & 1 == 0: |
| 96 | q &= -2 |
| 97 | |
| 98 | sign = q < 0 if no_neg_zero else n < 0 |
| 99 | return sign, abs(q) |
| 100 | |
| 101 | |
| 102 | def _round_to_figures(n, d, figures): |
no test coverage detected
searching dependent graphs…