divide a by b and round result to the nearest integer When the ratio is exactly half-way between two integers, the even integer is returned.
(a, b)
| 593 | ) |
| 594 | |
| 595 | def _divide_and_round(a, b): |
| 596 | """divide a by b and round result to the nearest integer |
| 597 | |
| 598 | When the ratio is exactly half-way between two integers, |
| 599 | the even integer is returned. |
| 600 | """ |
| 601 | # Based on the reference implementation for divmod_near |
| 602 | # in Objects/longobject.c. |
| 603 | q, r = divmod(a, b) |
| 604 | # round up if either r / b > 0.5, or r / b == 0.5 and q is odd. |
| 605 | # The expression r / b > 0.5 is equivalent to 2 * r > b if b is |
| 606 | # positive, 2 * r < b if b negative. |
| 607 | r *= 2 |
| 608 | greater_than_half = r > b if b > 0 else r < b |
| 609 | if greater_than_half or r == b and q % 2 == 1: |
| 610 | q += 1 |
| 611 | |
| 612 | return q |
| 613 | |
| 614 | |
| 615 | class timedelta: |
no test coverage detected