Skip to content

Commit d34f563

Browse files
committed
Fix the edge-case handling of Complex.pow(.zero, <int>)
1 parent 2624562 commit d34f563

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

Sources/ComplexModule/Complex+ElementaryFunctions.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,9 @@ extension Complex: ElementaryFunctions {
420420

421421
@inlinable
422422
public static func pow(_ z: Complex, _ n: Int) -> Complex {
423-
if z.isZero { return .zero }
423+
if z.isZero {
424+
return n < 0 ? .infinity : n == 0 ? .one : .zero
425+
}
424426
// TODO: this implementation is not quite correct, because n may be
425427
// rounded in conversion to RealType. This only effects very extreme
426428
// cases, so we'll leave it alone for now.

Tests/ComplexTests/ElementaryFunctionTests.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,18 @@ final class ElementaryFunctionTests: XCTestCase {
399399
}
400400
}
401401
}
402+
403+
func testPowR<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
404+
XCTAssertEqual(Complex<T>.pow(.zero, -.one), .infinity)
405+
XCTAssertEqual(Complex<T>.pow(.zero, .zero), .infinity)
406+
XCTAssertEqual(Complex<T>.pow(.zero, +.one), .infinity)
407+
}
408+
409+
func testPowN<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
410+
XCTAssertEqual(Complex<T>.pow(.zero, -1), .infinity)
411+
XCTAssertEqual(Complex<T>.pow(.zero, 0), .one)
412+
XCTAssertEqual(Complex<T>.pow(.zero, +1), .zero)
413+
}
402414

403415
func testFloat() {
404416
testExp(Float.self)
@@ -411,6 +423,8 @@ final class ElementaryFunctionTests: XCTestCase {
411423
testAcosh(Float.self)
412424
testAsinh(Float.self)
413425
testAtanh(Float.self)
426+
testPowR(Float.self)
427+
testPowN(Float.self)
414428
}
415429

416430
func testDouble() {
@@ -424,6 +438,8 @@ final class ElementaryFunctionTests: XCTestCase {
424438
testAcosh(Double.self)
425439
testAsinh(Double.self)
426440
testAtanh(Double.self)
441+
testPowR(Double.self)
442+
testPowN(Double.self)
427443
}
428444

429445
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
@@ -438,6 +454,8 @@ final class ElementaryFunctionTests: XCTestCase {
438454
testAcosh(Float80.self)
439455
testAsinh(Float80.self)
440456
testAtanh(Float80.self)
457+
testPowR(Float80.self)
458+
testPowN(Float80.self)
441459
}
442460
#endif
443461
}

0 commit comments

Comments
 (0)