Square root of n/m as a Decimal, correctly rounded.
(n: int, m: int)
| 1728 | |
| 1729 | |
| 1730 | def _decimal_sqrt_of_frac(n: int, m: int) -> Decimal: |
| 1731 | """Square root of n/m as a Decimal, correctly rounded.""" |
| 1732 | # Premise: For decimal, computing (n/m).sqrt() can be off |
| 1733 | # by 1 ulp from the correctly rounded result. |
| 1734 | # Method: Check the result, moving up or down a step if needed. |
| 1735 | if n <= 0: |
| 1736 | if not n: |
| 1737 | return Decimal('0.0') |
| 1738 | n, m = -n, -m |
| 1739 | |
| 1740 | root = (Decimal(n) / Decimal(m)).sqrt() |
| 1741 | nr, dr = root.as_integer_ratio() |
| 1742 | |
| 1743 | plus = root.next_plus() |
| 1744 | np, dp = plus.as_integer_ratio() |
| 1745 | # test: n / m > ((root + plus) / 2) ** 2 |
| 1746 | if 4 * n * (dr*dp)**2 > m * (dr*np + dp*nr)**2: |
| 1747 | return plus |
| 1748 | |
| 1749 | minus = root.next_minus() |
| 1750 | nm, dm = minus.as_integer_ratio() |
| 1751 | # test: n / m < ((root + minus) / 2) ** 2 |
| 1752 | if 4 * n * (dr*dm)**2 < m * (dr*nm + dm*nr)**2: |
| 1753 | return minus |
| 1754 | |
| 1755 | return root |
| 1756 | |
| 1757 | |
| 1758 | def _mean_stdev(data): |
no test coverage detected
searching dependent graphs…