Skip to content

Commit 4b5a85a

Browse files
committed
Fix a bug in root and add a test case for it.
For odd roots of negative values, we need to take the root of the *magnitude* of the number to avoid a NaN from the platform's implementation of `pow`, then restore the sign afterwards. We had the basic logic in place already, but were missing the step of taking the magnitude first. Also modified a test case to find this error.
1 parent 165fc40 commit 4b5a85a

File tree

2 files changed

+2
-2
lines changed

2 files changed

+2
-2
lines changed

stdlib/public/core/MathFunctions.swift.gyb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ extension ${Self}: ElementaryFunctions {
9595
guard x >= 0 || n % 2 != 0 else { return .nan }
9696
// TODO: this implementation isn't quite right for n so large that
9797
// the conversion to `${Self}` rounds.
98-
return ${Self}(signOf: x, magnitudeOf: pow(x, 1/${Self}(n)))
98+
return ${Self}(signOf: x, magnitudeOf: pow(x.magnitude, 1/${Self}(n)))
9999
}
100100

101101
@_alwaysEmitIntoClient

test/stdlib/MathFunctions.swift.gyb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ internal extension ElementaryFunctions where Self: BinaryFloatingPoint {
7272
expectEqualWithTolerance(-1.415037499278843818546261056052183491, Self.log2(0.375))
7373
expectEqualWithTolerance(0.3184537311185346158102472135905995955, Self.log1p(0.375))
7474
expectEqualWithTolerance(-0.425968732272281148346188780918363771, Self.log10(0.375))
75-
expectEqualWithTolerance(0.7211247851537041911608191553900547941, Self.root(0.375, 3))
75+
expectEqualWithTolerance(-0.7211247851537041911608191553900547941, Self.root(-0.375, 3))
7676
expectEqualWithTolerance(0.6123724356957945245493210186764728479, Self.sqrt(0.375))
7777
expectEqualWithTolerance(0.54171335479545025876069682133938570, Self.pow(0.375, 0.625))
7878
expectEqualWithTolerance(-0.052734375, Self.pow(-0.375, 3))

0 commit comments

Comments
 (0)