From 60a3edbaa944ce5a8fa71147e7441f58847540b7 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Sat, 17 Sep 2022 14:56:29 -0400 Subject: [PATCH] Further improvement to Complex.pow(_:Self,_:Self) edge cases. Bring pow(zero, w) in line with the behavior of pow for the underlying real type. --- .../ComplexModule/Complex+ElementaryFunctions.swift | 11 ++++++++--- Tests/ComplexTests/ElementaryFunctionTests.swift | 2 +- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Sources/ComplexModule/Complex+ElementaryFunctions.swift b/Sources/ComplexModule/Complex+ElementaryFunctions.swift index 49e4b30..f6ef2f4 100644 --- a/Sources/ComplexModule/Complex+ElementaryFunctions.swift +++ b/Sources/ComplexModule/Complex+ElementaryFunctions.swift @@ -413,16 +413,21 @@ extension Complex: ElementaryFunctions { } // MARK: - pow-like functions + /// `exp(w*log(z))` + /// + /// Edge cases for this function are defined according to the defining + /// expression exp(w log(z)), except that we define pow(0, w) to be 0 + /// instead of infinity when w is in the (strict) right half-plane, so that + /// we agree with RealType.pow on the positive real line. @inlinable public static func pow(_ z: Complex, _ w: Complex) -> Complex { + if z.isZero { return w.real > 0 ? zero : infinity } return exp(w * log(z)) } @inlinable public static func pow(_ z: Complex, _ n: Int) -> Complex { - if z.isZero { - return n < 0 ? .infinity : n == 0 ? .one : .zero - } + if z.isZero { return n < 0 ? infinity : n == 0 ? one : zero } // TODO: this implementation is not quite correct, because n may be // rounded in conversion to RealType. This only effects very extreme // cases, so we'll leave it alone for now. diff --git a/Tests/ComplexTests/ElementaryFunctionTests.swift b/Tests/ComplexTests/ElementaryFunctionTests.swift index d1db601..a8fd033 100644 --- a/Tests/ComplexTests/ElementaryFunctionTests.swift +++ b/Tests/ComplexTests/ElementaryFunctionTests.swift @@ -403,7 +403,7 @@ final class ElementaryFunctionTests: XCTestCase { func testPowR(_ type: T.Type) { XCTAssertEqual(Complex.pow(.zero, -.one), .infinity) XCTAssertEqual(Complex.pow(.zero, .zero), .infinity) - XCTAssertEqual(Complex.pow(.zero, +.one), .infinity) + XCTAssertEqual(Complex.pow(.zero, +.one), .zero) } func testPowN(_ type: T.Type) {