(x: Decimal, p: number)
| 73 | |
| 74 | //IMPL: Helper function to find n2, e2, and r2 using direct calculation |
| 75 | function findN2E2R2(x: Decimal, p: number) { |
| 76 | const maxN2 = getPowerOf10(p) |
| 77 | const minN2 = getPowerOf10(p - 1) |
| 78 | |
| 79 | // Direct calculation: similar to findN1E1R1 but with ceiling |
| 80 | const log10x = x.log(10) |
| 81 | let e2 = log10x.floor() |
| 82 | |
| 83 | // Calculate n2 and r2 from e2 |
| 84 | const divisor = getPowerOf10(e2.minus(p).plus(1)) |
| 85 | let n2 = x.div(divisor).ceil() |
| 86 | let r2 = n2.times(divisor) |
| 87 | |
| 88 | // Verify and adjust if n2 is out of bounds |
| 89 | if (n2.greaterThanOrEqualTo(maxN2)) { |
| 90 | e2 = e2.plus(1) |
| 91 | const newDivisor = getPowerOf10(e2.minus(p).plus(1)) |
| 92 | n2 = x.div(newDivisor).ceil() |
| 93 | r2 = n2.times(newDivisor) |
| 94 | } else if (n2.lessThan(minN2)) { |
| 95 | e2 = e2.minus(1) |
| 96 | const newDivisor = getPowerOf10(e2.minus(p).plus(1)) |
| 97 | n2 = x.div(newDivisor).ceil() |
| 98 | r2 = n2.times(newDivisor) |
| 99 | } |
| 100 | |
| 101 | // Final verification with fallback to iterative search if needed |
| 102 | if ( |
| 103 | r2.greaterThanOrEqualTo(x) && |
| 104 | n2.lessThan(maxN2) && |
| 105 | n2.greaterThanOrEqualTo(minN2) |
| 106 | ) { |
| 107 | return {n2, e2, r2} |
| 108 | } |
| 109 | |
| 110 | // Fallback: iterative search (should rarely be needed) |
| 111 | const minE2 = x.div(maxN2).log(10).plus(p).minus(1).floor() |
| 112 | let currentE2 = minE2 |
| 113 | while (true) { |
| 114 | const currentDivisor = getPowerOf10(currentE2.minus(p).plus(1)) |
| 115 | let currentN2 = x.div(currentDivisor).ceil() |
| 116 | if (currentN2.lessThan(maxN2) && currentN2.greaterThanOrEqualTo(minN2)) { |
| 117 | const currentR2 = currentN2.times(currentDivisor) |
| 118 | if (currentR2.greaterThanOrEqualTo(x)) { |
| 119 | return { |
| 120 | n2: currentN2, |
| 121 | e2: currentE2, |
| 122 | r2: currentR2, |
| 123 | } |
| 124 | } |
| 125 | } |
| 126 | currentE2 = currentE2.plus(1) |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | /** |
| 131 | * https://tc39.es/ecma402/#sec-torawprecision |
no test coverage detected