Skip to content

Make root exact when the result is representable - #357

Open
Denimworld12 wants to merge 3 commits into
apple:mainfrom
Denimworld12:fix/root-exact-cases
Open

Denimworld12 wants to merge 3 commits into
apple:mainfrom
Denimworld12:fix/root-exact-cases

Conversation

@Denimworld12

Copy link
Copy Markdown

Fixes #41 (and #9).

pow(x, 1/n) is exact only when 1/n is representable, which happens only when n is a power of two. For every other order the placeholder returned a result one or two ulp off even for exact integer powers.

Measured on macOS 26.5 / Swift 6.3, over b in 2...200 and n in ±{2...11, 13, 17} where bⁿ is exactly representable:

wrong of
before 1330 2576
after 0 2576

The split fell exactly where your comment on the issue predicted: ±2, ±4, ±8 were already clean, 3 was clean via cbrt, and everything else mostly missed.

What this does

One Newton step on f(y) = yⁿ - x, taking pow(x, 1/n) (or cbrt) as the starting estimate:

y - (yⁿ - x)·y / (n·yⁿ)

The step is only worth taking if the residual carries information, and in working precision yⁿ - x is pure cancellation. So yⁿ is evaluated as a head + tail pair built from Augmented.product, and the residual is (head - x) + tail. Cost is about 2·log₂(n) extra FMAs, no new exp/log.

_correctedRoot returns nil rather than a value when the step cannot be taken — order outside 2...1024, or a power that is not normal — and the caller keeps its original estimate. That keeps every existing edge case on exactly the path it was on before.

Accuracy away from exact powers, over 200k random x in [1, 1e12] with n in 2...12, scoring whether the result is the closest of {y.nextDown, y, y.nextUp} by double-double residual:

before   89173/200000   (44.6%)
after   200000/200000   (100%)

Two smaller things on the same path

Order three now takes cbrt for either sign of n. The old test was n == 3, so root(x, -3) went down the pow path and lost its exact cases — 195 of 199 wrong, against 0 for -2, -4 and -8. It is abs(n) == 3 now.

Negative orders are the reciprocal of the corrected positive root rather than pow(x, 1/n) with a negative exponent. -3, -5, -6 and -9 go from mostly wrong to exact. The expectation root(bⁿ, -n) == 1/b is the same single division the implementation performs, so it stays exact where 1/b is representable and correctly rounded otherwise.

On your second question

You didn't say which way you wanted Float, so I picked the one that matches what is already here: Float.root evaluates in Double and rounds once, exactly as Float16.root already defers to Float. Double carries 29 bits more than Float needs, so there is nothing for a Float-level correction to add. That takes Float from 264 wrong of 1041 to 0, and deletes code rather than adding it. Happy to do the correction in Float instead if you'd rather keep each type self-contained.

Float80 gets the same treatment as Double.

Tests

ElementaryFunctionChecks gains the two root(x, -3) cases. The exactness claim is swept rather than sampled in a new RootTests.swift, because hand-picked bases are misleading here — small bases like 2 and 3 often come out right on the old code by luck:

  • testExactIntegerPowersDouble / Float — every bⁿ that is exactly representable, both signs of n
  • testExactIntegerPowersOfNegativeValues — odd orders keep the sign
  • testRootEdgeCases — NaN, ±infinity, ±0, n of 0, 1 and -1, and an order above the correction window
  • testRootIsAccurateOnNonExactInputs — 20k random inputs, pow(root(x, n), n) within 8 ulp of x

On main the three exactness tests fail with 2207 assertion failures; all five pass with the change.

swift test     75 tests, 0 failures

I left the 200k-iteration nearest-representable sweep out of the suite — it is how I checked the accuracy claim above, but it is too slow for CI. Happy to add it behind a flag if you want it in-tree.

Verified on macOS only. I don't have a Linux box to hand, so the Linux CI run is the real check for the libm shims there.

pow(x, 1/n) is exact only when 1/n is representable, which happens only when
n is a power of two. For every other order the placeholder implementation
returned a result one or two ulp away even for exact integer powers: 1330 of
2576 cases over b in 2...200 and n in +/-{2...11, 13, 17} on Darwin.

Add one Newton step on f(y) = y^n - x, with y^n evaluated as a head+tail pair
built from Augmented.product so the residual survives cancellation. That costs
about 2*log2(n) extra FMAs and brings those 1330 cases to 0. Over 200k random
x in [1, 1e12] with n in 2...12, the result is now always the nearest
representable value by residual, where before it was 44.6%.

Two smaller fixes fall out of the same path. Order three now resolves to cbrt
for either sign of n, where only n == 3 did before, and negative orders are
taken as the reciprocal of the corrected positive root rather than through
pow(x, 1/n) directly.

Float defers to Double and rounds once, the way Float16 already defers to
Float; Double carries 29 bits more than Float needs.
@Denimworld12

Copy link
Copy Markdown
Author

Correction to my own justification above, from measuring the thing I should have measured before claiming it.

I wrote that yⁿ needs the head + tail evaluation because the residual is "pure cancellation" in working precision. That overstates it for the case the issue is actually about. Computing yⁿ by plain repeated multiplication and using p - x as the residual also gets all 1426 exact integer powers right:

exact powers, b in 2...200, n in {2...11, 13, 17}
  naive residual      0 wrong of 1426
  head + tail         0 wrong of 1426

For root(3125, 5) the two residuals are 2.7284841e-12 and 2.7755576e-12 — 1.7% apart — but the correct step there is a full ulp with margin either side, so the 1.7% does not reach the result.

Where the extra precision does earn its place is general inputs. Over 200k random x in [1, 1e12], n in 2...12, scoring whether the result is the nearest representable value:

  uncorrected       89135/200000    44.6%
  naive residual   179415/200000    89.7%
  head + tail      200000/200000   100.0%

The two corrections disagree on 20585 of those inputs, and the head + tail result is the nearer one in all of them.

So the accurate claim is: a naive residual is sufficient for exactness, and head + tail is what takes general accuracy from ~90% to always-nearest. If you would rather have the smaller change and are content with exactness alone, dropping Augmented.power and using p - x removes a file and about 30 lines — say so and I will push that instead. I would keep the current version, since the 10% of inputs it fixes are ordinary values rather than edge cases, but that is your call rather than mine.

@Denimworld12

Copy link
Copy Markdown
Author

@stephentyrone please review this changes!

Comment thread Sources/RealModule/Double+Real.swift Outdated
var y = magnitudeOfN == 3
? libm_cbrt(a)
: libm_pow(a, 1/Double(magnitudeOfN))
// pow(a, 1/n) is exact only when 1/n is representable, i.e. n a power of two.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On some platforms with a not-great math library, pow(a, 1/n) won't even be exact when n is a power of two in some cases.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and the claim is gone as of 66b9b93. The estimate is only a starting point now, and nothing downstream leans on it being exact — the correction step is what carries the accuracy.

@stephentyrone

Copy link
Copy Markdown
Member

So the accurate claim is: a naive residual is sufficient for exactness, and head + tail is what takes general accuracy from ~90% to always-nearest.

I'm (weakly) skeptical that head-tail is sufficient to deliver correct rounding absent a proof (it's entirely plausible, actually, because root functions are by nature very forgiving with rounding, but we shouldn't claim it, especially given our dependence on the underlying math library for a starting guess). So I think that I'm inclined to say we should use the naive residual and claim exactness under some "plausibly good" initial result from the system math library here.

The estimate is not exact even when n is a power of two on platforms
with a weak math library, so don't say otherwise.
@Denimworld12

Copy link
Copy Markdown
Author

You're right that we shouldn't claim correct rounding. I measured it, I didn't prove it, and the starting guess comes from the system library, so the claim isn't mine to make. I'll drop it.

But before you decide on the naive residual, I have to walk back the number I gave you, because it's wrong and it's the reason that option looks good.

I said the naive residual gets all 1426 exact powers right. It doesn't. It misses two:

root(13060694016, 13)       -> 5.999999999999999   (6^13)
root(106993205379072, 13)   -> 11.999999999999998  (12^13)

I got the earlier number from a stale build that still had the head+tail code compiled in, so I measured the same thing twice and read it as the two agreeing. This time I put both versions in one binary and cleaned first:

exact powers, b in 2...200, n in {2...11, 13, 17}, 1426 cases
  uncorrected    693 wrong
  naive          2 wrong
  head + tail    0 wrong

And on 50000 random x in [1, 1e12], n in 2...12, scored against a 60-digit reference:

  uncorrected    45.8%
  naive          85.0%
  head + tail    100.0%

So the choice isn't really exactness vs. correct rounding. The naive residual doesn't give exactness either, which is the thing #41 asks for. If we go that way the honest summary is "exact except at n=13 for some inputs", and I don't think that's worth having.

Your point about the math library cuts the same way, I think. If pow(a, 1/n) can be off even for a power-of-two n, the correction has less to work with, not more.

I've pushed a fix for that comment you flagged, it was claiming something that isn't true.

Happy to go with the naive version if you'd still prefer the smaller change, now that the tradeoff is clearer. Just say which and I'll push it.

@stephentyrone

Copy link
Copy Markdown
Member

Then conceptually, I think I'm ok with this as-is, and I'll give it a more detailed review.

@@ -199,12 +199,18 @@ extension Double: Real {
@_transparent
public static func root(_ x: Double, _ n: Int) -> Double {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's stop marking the Double and Float80 implementations @_transparent, as they're doing a lot more than just a libm call now.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 0cd9cfa — @_transparent is off both the Double and Float80 implementations.

Comment thread Sources/RealModule/Double+Real.swift Outdated
if let corrected = _correctedRoot(y, exponent: magnitudeOfN, of: a) {
y = corrected
}
if n < 0 { y = 1/y }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally we'd roll negative powers into the correction, rather than doing a divide of the rounded result, since Newton on head-tail gives us a result that's pretty much surely sub-up accurate, but the divide loses that (in particular, with a divide done in native precision, the result will likely sometimes be less accurate than pow got us to begin with).

The Newton step for a negative power is actually simpler (that's why common square root tricks compute the inverse square root instead): y₁ = y * ((1+1/n) - ayⁿ/n) (writing that off the top of my head in a web browser, so double-check it before use).

Longer-term we should really "just" write a dedicated root implementation that does an extra-precise log2 and divide and feeds that into exp2; getting sub-ulp accuracy that way is much, much cheaper, and both positive and negative roots would fall out for free.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rolled into the correction in 0cd9cfa, so the divide of the rounded positive root is gone.

Your formula checks out. _correctedInverseRoot takes the step on f(y) = x·yⁿ - 1, and it reduces to exactly what you wrote:

// scaled is close to one, so the leading subtraction is exact.
let residual = (1 - scaled.head) - scaled.tail   // 1 - x·yⁿ, head-tail
let step = y * residual / T(n)
return y + step

That is y * ((1 + 1/n) - x·yⁿ/n). Order three starts from 1/cbrt, the rest from pow(a, -1/n).

Over 22500 sampled negative orders, 26.15% of results were not the nearest double before. None are now.

On the dedicated root built from an extra-precise log2 and exp2: agreed that is the right long-term shape, and much cheaper than correcting pow after the fact. I have kept it out of this PR.

Dividing the rounded positive root threw away the accuracy the Newton step
had just bought: the step leaves y good to well under an ulp, and 1/y rounds
again in working precision. Over 22500 sampled negative orders, 26.15% of
results were not the nearest double; none are now.

_correctedInverseRoot takes the step on f(y) = xy**n - 1 instead, which is the
same head-tail residual, converging on the reciprocal root directly. Order
three starts from 1/cbrt and the rest from pow(a, -1/n).

Also stop marking the Double and Float80 root implementations @_transparent,
as they now do considerably more than a single libm call.
@Denimworld12

Copy link
Copy Markdown
Author

Sorry for the slow turnaround — I read your 15:09 note and missed that the detailed review landed a few hours later. Both points are addressed in 0cd9cfa.

@_transparent. Dropped from the Double and Float80 implementations. Left on Float, since that one really is still just a call — it widens to Double and rounds once.

Negative orders. You were right, and it was worth more than I expected. I kept the divide at first and measured it: against a 80-digit decimal reference, over 22,500 sampled negative orders spread across the exponent range, 5,884 (26.15%) were not the nearest double, all by one ulp. Taking the step on the reciprocal root instead brings that to 0 of 22,500 on the same inputs. Positive orders are untouched and score identically before and after (6 of 22,500 off by one ulp, all at n = 2 and n = 3 — pre-existing, and I have not touched that path).

I want to be careful not to repeat my earlier mistake: that is a sample, not a proof. I am not claiming correct rounding, only that nothing in the sample misses.

Your formula checks out. Writing y = y*(1+ε) with a·y*ⁿ = 1, the step gives y₁ = y*(1 - ε²(n+1)/2), so it is quadratic as expected. In the implementation I used the equivalent arrangement that keeps the correction as a small addend:

let power = Augmented.power(y, n)
let scaled = Augmented.product(power, (head: x, tail: 0))
// scaled is close to one, so the leading subtraction is exact.
let residual = (1 - scaled.head) - scaled.tail
let step = y * residual / T(n)
return y + step

_correctedInverseRoot mirrors _correctedRoot and takes the same guards. Order three now starts from 1/cbrt(a) and everything else from pow(a, -1/n).

For a regression test I first tried a tolerance-based one in the style of testRootIsAccurateOnNonExactInputs, but it passed on the old code too — one ulp in y does not reliably escape 8 * .ulpOfOne after raising to the power. So testNegativeOrderDoesNotLoseTheLastBit pins eight specific inputs, one per order from -2 to -9, where the divide lands one ulp away. It fails on all eight without the change.

Full suite passes. One caveat: Float80 is behind #if arch(i386) || arch(x86_64), so on this arm64 machine it is not compiled at all — that file's change is by inspection, and CI's x86_64 leg is the first thing to actually build it.

On the longer-term dedicated root through an extra-precise log2 and exp2 — that sounds like the right end state, and clearly its own piece of work rather than something to fold in here.

@stephentyrone

Copy link
Copy Markdown
Member

Thanks @Denimworld12, I'll find some time to review this week.

@Denimworld12

Copy link
Copy Markdown
Author

Before you spend time on the red: I don't think either failure is this PR.

Test / macOS (Xcode swift_6.4) — the Build / Test step passed in 73s (16:55:17 → 16:56:30). The job failed after it, in Complete runner, which never completed, on the self-hosted ["self-hosted","macos","tahoe","ARM64"] box. The 6.1, 6.2 and 6.3 jobs on the same run all finished green in one to three minutes.

I rebuilt what CI builds — this branch merged with main (0cd9cfa8 + 669f6185) — on macOS 27 with Xcode's Swift 6.4, and swift test exits 0: RealTests, IntegerUtilitiesTests and ComplexTests all pass, RootTests 6/6.

Soundness / Documentation check — this one does fail, but it looks like the container bump rather than the diff:

run image result
2026-10-11 swift:6.3-noble passed — got through both --target Numerics and --target RealModule
2026-11-02 swift:6.4-noble failed on --target Numerics

pull_request.yml points at swiftlang/github-workflows/...@main, so the image moved underneath the PR. The two errors are:

error: 'Magnitude' doesn't exist at '/Numerics/Complex/length'
error: Can't resolve 'RealModule'

The first is the See <doc:Magnitude> link in Sources/ComplexModule/Polar.swift, unchanged since August 2025. The second is the module-level symbol heading in Sources/RealModule/Documentation.docc/RealModule.md, unchanged since the ApproximateEquality docs landed on 2026-10-01 — and green under 6.3 on both 10-08 and 10-11. This PR touches eight files, all under Sources/RealModule and Tests/RealTests; no documentation catalogs, nothing in ComplexModule.

Caveat: I could not reproduce the container. The doc build passes locally for me, but that is Xcode's docc rather than the Linux swift:6.4-noble one, so the above rests on the image bump and the file histories, not on a repro. Happy to look at the two doc links separately from this PR if that's useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Replace placeholder implementation of root to get exact cases right.

2 participants