Repository navigation
Make root exact when the result is representable - #357
Denimworld12 wants to merge 3 commits into
Conversation
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.
|
Correction to my own justification above, from measuring the thing I should have measured before claiming it. I wrote that For Where the extra precision does earn its place is general inputs. Over 200k random The two corrections disagree on 20585 of those inputs, and the So the accurate claim is: a naive residual is sufficient for exactness, and |
|
@stephentyrone please review this changes! |
| 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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.
|
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: 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: And on 50000 random x in [1, 1e12], n in 2...12, scored against a 60-digit reference: 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 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. |
|
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 { | |||
There was a problem hiding this comment.
Let's stop marking the Double and Float80 implementations @_transparent, as they're doing a lot more than just a libm call now.
There was a problem hiding this comment.
Done in 0cd9cfa — @_transparent is off both the Double and Float80 implementations.
| if let corrected = _correctedRoot(y, exponent: magnitudeOfN, of: a) { | ||
| y = corrected | ||
| } | ||
| if n < 0 { y = 1/y } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 + stepThat 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.
|
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
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 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 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
For a regression test I first tried a tolerance-based one in the style of Full suite passes. One caveat: On the longer-term dedicated |
|
Thanks @Denimworld12, I'll find some time to review this week. |
|
Before you spend time on the red: I don't think either failure is this PR.
I rebuilt what CI builds — this branch merged with
The first is the Caveat: I could not reproduce the container. The doc build passes locally for me, but that is Xcode's docc rather than the Linux |
Fixes #41 (and #9).
pow(x, 1/n)is exact only when1/nis representable, which happens only whennis 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
bin 2...200 andnin ±{2...11, 13, 17} wherebⁿis exactly representable:The split fell exactly where your comment on the issue predicted:
±2,±4,±8were already clean,3was clean viacbrt, and everything else mostly missed.What this does
One Newton step on
f(y) = yⁿ - x, takingpow(x, 1/n)(orcbrt) as the starting estimate:The step is only worth taking if the residual carries information, and in working precision
yⁿ - xis pure cancellation. Soyⁿis evaluated as ahead + tailpair built fromAugmented.product, and the residual is(head - x) + tail. Cost is about 2·log₂(n) extra FMAs, no newexp/log._correctedRootreturnsnilrather 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
xin [1, 1e12] withnin 2...12, scoring whether the result is the closest of{y.nextDown, y, y.nextUp}by double-double residual:Two smaller things on the same path
Order three now takes
cbrtfor either sign ofn. The old test wasn == 3, soroot(x, -3)went down thepowpath and lost its exact cases — 195 of 199 wrong, against 0 for-2,-4and-8. It isabs(n) == 3now.Negative orders are the reciprocal of the corrected positive root rather than
pow(x, 1/n)with a negative exponent.-3,-5,-6and-9go from mostly wrong to exact. The expectationroot(bⁿ, -n) == 1/bis the same single division the implementation performs, so it stays exact where1/bis 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.rootevaluates inDoubleand rounds once, exactly asFloat16.rootalready defers toFloat. Double carries 29 bits more thanFloatneeds, so there is nothing for aFloat-level correction to add. That takesFloatfrom 264 wrong of 1041 to 0, and deletes code rather than adding it. Happy to do the correction inFloatinstead if you'd rather keep each type self-contained.Float80gets the same treatment asDouble.Tests
ElementaryFunctionChecksgains the tworoot(x, -3)cases. The exactness claim is swept rather than sampled in a newRootTests.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— everybⁿthat is exactly representable, both signs ofntestExactIntegerPowersOfNegativeValues— odd orders keep the signtestRootEdgeCases— NaN, ±infinity, ±0,nof 0, 1 and -1, and an order above the correction windowtestRootIsAccurateOnNonExactInputs— 20k random inputs,pow(root(x, n), n)within 8 ulp ofxOn
mainthe three exactness tests fail with 2207 assertion failures; all five pass with the change.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
libmshims there.