From 4db6faa3e7b7dc250ead8a9fcd60ac843a38552c Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Fri, 10 Apr 2020 10:08:59 -0400 Subject: [PATCH 1/9] Additional test coverage for pow with integer exponents. These cases expose a bug in the current implementation; because the split of the exponent into high and low parts may produce numbers with different signs, if both parts overflow or underflow, we can end up with 0 * infinity = NaN, when the result should actually be either zero or infinity. --- Tests/RealTests/IntegerExponentTests.swift | 71 ++++++++++++++-------- 1 file changed, 46 insertions(+), 25 deletions(-) diff --git a/Tests/RealTests/IntegerExponentTests.swift b/Tests/RealTests/IntegerExponentTests.swift index 0d8997b..fcf0011 100644 --- a/Tests/RealTests/IntegerExponentTests.swift +++ b/Tests/RealTests/IntegerExponentTests.swift @@ -12,7 +12,8 @@ import XCTest import RealModule -internal extension Real where Self: BinaryFloatingPoint { +internal extension Real where Self: BinaryFloatingPoint, + Self.RawSignificand: FixedWidthInteger { static func testIntegerExponentCommon() { // If x is -1, then the result is ±1 with sign chosen by parity of n. // Simply converting n to Real will flip parity when n is large, so @@ -27,12 +28,55 @@ internal extension Real where Self: BinaryFloatingPoint { XCTAssertEqual(Self.pow(-1, Int.max), -1) XCTAssertEqual(Self.pow(-1, -Int.max), -1) XCTAssertEqual(Self.pow(-1, Int.min), 1) + // Generate some random test values that definitely overflow or + // underflow; we want to be sure that we get the right ±0 or ±∞ + // result. + for _ in 0 ..< 10 { + let x = Self.random(in: 2 ..< 4) + let n = Int.random(in: 1 - Int(Self.leastNonzeroMagnitude.exponent) ..< .max) + let even = n & -2 + let odd = even | 1 + assertClose( .infinity, Self.pow(x, even)) + assertClose( .infinity, Self.pow(x, odd)) + assertClose( 0.0, Self.pow(1/x, even)) + assertClose( 0.0, Self.pow(1/x, odd)) + assertClose( .infinity, Self.pow(-x, even)) + assertClose(-.infinity, Self.pow(-x, odd)) + assertClose( 0.0, Self.pow(-1/x, even)) + assertClose(-0.0, Self.pow(-1/x, odd)) + assertClose( 0.0, Self.pow(x, -even)) + assertClose( 0.0, Self.pow(x, -odd)) + assertClose( .infinity, Self.pow(1/x, -even)) + assertClose( .infinity, Self.pow(1/x, -odd)) + assertClose( 0.0, Self.pow(-x, -even)) + assertClose(-0.0, Self.pow(-x, -odd)) + assertClose( .infinity, Self.pow(-1/x, -even)) + assertClose(-.infinity, Self.pow(-1/x, -odd)) + } + } + + static func testIntegerExponentDoubleAndSmaller() { + // max/min exponents, these always saturate, but this will reveal + // errors in some implementations that one could try. + let u = Self(1).nextUp + let d = Self(1).nextDown + assertClose( .infinity, Self.pow(-u, Int.max - 1)) + assertClose( 0.0, Self.pow(-d, Int.max - 1)) + assertClose( 0.0, Self.pow(-u, -Int.max + 1)) + assertClose( .infinity, Self.pow(-d, -Int.max + 1)) + assertClose(-.infinity, Self.pow(-u, Int.max)) + assertClose(-0.0, Self.pow(-d, Int.max)) + assertClose(-0.0, Self.pow(-u, -Int.max)) + assertClose(-.infinity, Self.pow(-d, -Int.max)) + assertClose( 0.0, Self.pow(-u, Int.min)) + assertClose( .infinity, Self.pow(-d, Int.min)) } } extension Float { static func testIntegerExponent() { testIntegerExponentCommon() + testIntegerExponentDoubleAndSmaller() let u = Float(1).nextUp let d = Float(1).nextDown // Smallest exponents not exactly representable as Float. @@ -52,24 +96,13 @@ extension Float { assertClose(-7.0064924138100205091278464932003585e-46, Float.pow(-d, 1744361943)) assertClose( 7.0064919961905290625123586120258840e-46, Float.pow(-d, 1744361944)) assertClose(-7.0064915785710625079583096856510544e-46, Float.pow(-d, 1744361945)) - // max/min exponents, these always saturate, but this will reveal - // errors in some implementations that one could try. - assertClose( .infinity, Self.pow(-u, Int.max - 1)) - assertClose( 0.0, Self.pow(-d, Int.max - 1)) - assertClose( 0.0, Self.pow(-u, -Int.max + 1)) - assertClose( .infinity, Self.pow(-d, -Int.max + 1)) - assertClose(-.infinity, Self.pow(-u, Int.max)) - assertClose(-0.0, Self.pow(-d, Int.max)) - assertClose(-0.0, Self.pow(-u, -Int.max)) - assertClose(-.infinity, Self.pow(-d, -Int.max)) - assertClose( 0.0, Self.pow(-u, Int.min)) - assertClose( .infinity, Self.pow(-d, Int.min)) } } extension Double { static func testIntegerExponent() { testIntegerExponentCommon() + testIntegerExponentDoubleAndSmaller() // Following tests only make sense (and are only necessary) on 64b platforms. #if arch(arm64) || arch(x86_64) let u: Double = 1.nextUp @@ -93,18 +126,6 @@ extension Double { assertClose(-2.4703282292062332640976590913373022e-324, Double.pow(-d, 6711563375777760775)) assertClose( 2.4703282292062329898361312467121758e-324, Double.pow(-d, 6711563375777760776)) assertClose(-2.4703282292062327155746034020870799e-324, Double.pow(-d, 6711563375777760777)) - // max/min exponents, these always saturate, but this will reveal - // errors in some implementations that one could try. - assertClose( .infinity, Self.pow(-u, Int.max - 1)) - assertClose( 0.0, Self.pow(-d, Int.max - 1)) - assertClose( 0.0, Self.pow(-u, -Int.max + 1)) - assertClose( .infinity, Self.pow(-d, -Int.max + 1)) - assertClose(-.infinity, Self.pow(-u, Int.max)) - assertClose(-0.0, Self.pow(-d, Int.max)) - assertClose(-0.0, Self.pow(-u, -Int.max)) - assertClose(-.infinity, Self.pow(-d, -Int.max)) - assertClose( 0.0, Self.pow(-u, Int.min)) - assertClose( .infinity, Self.pow(-d, Int.min)) #endif } } From ff6a0ff2a57c6ecfe28a5f28cf47e42c3610bb48 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Fri, 10 Apr 2020 11:46:22 -0400 Subject: [PATCH 2/9] Fix bug for very large exponents pow(Float/Double, Int). Just-added tests expose this issue, where the split of n into high/low parts could produce parts with different signs. If both x**high and x**low then overflow and underflow, the resulting computation would be 0*inf (or inf*0) and produce NaN instead of either zero or infinity. --- Sources/RealModule/Double+Real.swift | 42 ++++++++++++++++++++++------ Sources/RealModule/Float+Real.swift | 21 ++++++++++---- 2 files changed, 48 insertions(+), 15 deletions(-) diff --git a/Sources/RealModule/Double+Real.swift b/Sources/RealModule/Double+Real.swift index 05e44e9..38d07aa 100644 --- a/Sources/RealModule/Double+Real.swift +++ b/Sources/RealModule/Double+Real.swift @@ -158,16 +158,40 @@ extension Double: Real { // If n is exactly representable as Double, we can just call pow: // Note that all calls on a 32b platform go down this path. if let y = Double(exactly: n) { return libm_pow(x, y) } - // Otherwise, n is too large to losslessly represent as Double, so we - // just split it into two parts, high and low. This is always exact, - // so the only source of error is pow itself and the multiplication. + // n is not representable in Double, so we will split it into two parts, + // low and high, such that (high + low) = n, and use the identity: // - // mask constant is spelled in this funny way because if we just anded - // with the hex value, we'd get a compile error on 32b platforms, even - // though this whole branch is dead code on 32b. - let mask = Int(truncatingIfNeeded: 0x1f_ffff_ffff_ffff as UInt64) - let low = n & mask - let high = n - low + // x**(high + low) = x**high * x**low. + // + // We put the high-order 32 bits into high, and the remaining 32 bits + // in low. + // + // The exact split isn't important; all we need is that both pieces get + // less than 53 bits (so that they are exact) and that they both have + // the same sign as n. + // + // This second point is a little bit subtle--why is + // it necessary? Consider what would happen if we took x = 2 and + // n = Int.min + Int(UInt32.max), and simply naively split n without + // taking care with the sign. We would end up computing: + // + // 2**n = 2**Int.min * 2**UInt32.max + // + // The first exponent is negative, the second positive, so the first term + // underflows to zero, and the second overflows to infinity, so the final + // result is NaN, when it should be zero. In order to avoid this + // situation, we make sure that high contains n rounded *towards zero*, + // rather than using simple two's-complement truncation (which rounds + // down). + let mask = Int(truncatingIfNeeded: UInt32.max) + let round = n < 0 ? mask : 0 + // The addition and subtraction below cannot actually overflow (proof: + // round is positive if n is negative, and zero otherwise, so n + round + // is guaranteed to be representable, and n and high have the same sign, + // so n - high is also representable), but it's hard to tell the compiler + // that, so I'm using wrapping operations instead. + let high = (n &+ round) & ~mask + let low = n &- high return libm_pow(x, Double(low)) * libm_pow(x, Double(high)) } diff --git a/Sources/RealModule/Float+Real.swift b/Sources/RealModule/Float+Real.swift index b5df21f..83a0ab4 100644 --- a/Sources/RealModule/Float+Real.swift +++ b/Sources/RealModule/Float+Real.swift @@ -150,12 +150,21 @@ extension Float: Real { // The range of "interesting" n is -1488522191 ... 1744361944; outside // of this range, all x != 1 overflow or underflow, so only the parity // of x matters. We don't really care about the specific range at all, - // only that the bounds fit exactly into two Floats. Mask the low 24 - // bits of n, get pow with that exponent (this contains the parity), - // then get pow with the rest (this may round, but if it does we've - // saturated anyway, so it doesn't matter). - let low = n & 0xffffff - let high = n - low + // only that the bounds fit exactly into two Floats. + // + // We do, however, need to be careful that high and low both have the + // same sign as n (consult the Double implementation for details of why + // this matters), so we need to be a little bit careful constructing + // them. + // + // Unlike the Double implementation, when n is very large, high will + // get rounded here; that's OK because it does not change the sign or + // parity, which are the only two bits that matter for such large + // exponents in Float. + let mask = Int(truncatingIfNeeded: 0xffffff) + let round = n < 0 ? mask : 0 + let high = (n &+ round) & ~mask + let low = n &- high return libm_powf(x, Float(low)) * libm_powf(x, Float(high)) } From c14381db8c797de4ec195b28c10f04143dd635b6 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Mon, 13 Apr 2020 09:41:55 -0400 Subject: [PATCH 3/9] Add basic directions for adding a swiftpm dependency. --- README.md | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1f166c0..ca3b717 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ These modules fall broadly into two categories: There is some overlap between these two categories, and API that begins in the first category may migrate to the second as it matures and new uses are discovered. -Swift Numerics modules are fine-grained; if you need support for Complex numbers, you can import ComplexModule[1](#foot1) without pulling in everything else in the library as well: +Swift Numerics modules are fine-grained; if you need support for Complex numbers, you can import ComplexModule¹ without pulling in everything else in the library as well: ```swift import ComplexModule @@ -28,7 +28,21 @@ Future expansion may assume the availability of other standard interfaces such a Because we intend to make it possible to adopt Swift Numerics modules in the standard library at some future point, Swift Numerics uses the same license and contribution guidelines as the Swift project. -## Process +## Using Swift Numerics in your project +To use Swift Numerics in a SwiftPM project, add the following line to the dependencies in your `Package.swift` file: +```swift +.package(url: "https://github.com/apple/swift-numerics", from: "0.0.5"), +``` +add `Numerics` as a dependency for your target: +```swift +.target(name: "MyTarget", dependencies: [ + .product(name: "Numerics", package: "swift-numerics"), + "AnotherModule" +]), +``` +and finally, add `import Numerics` in your source code. + +## Contributing to Swift Numerics Swift Numerics is a standalone library separate from the core Swift project. In practice, it will act as a staging ground for some APIs that may eventually be incorporated into the Swift Standard Library, and when that happens such changes will be proposed to the Swift Standard Library using the established evolution process of the Swift project. @@ -62,7 +76,7 @@ Questions about how to use Swift Numerics modules, or issues that are not clearl 5. [Decimal Floating-point](https://github.com/apple/swift-numerics/issues/7) ## Notes -[1](#back1) Swift is currently unable to use the fully-qualified name for types when a type and module have the same name (discussion here: https://forums.swift.org/t/pitch-fully-qualified-name-syntax/28482). +¹ Swift is currently unable to use the fully-qualified name for types when a type and module have the same name (discussion here: https://forums.swift.org/t/pitch-fully-qualified-name-syntax/28482). This would prevent users of Swift Numerics who don't need generic types from doing things like: ```swift import Complex From 488e250259a8362408a4db5e07e182f314528fc5 Mon Sep 17 00:00:00 2001 From: Richard Wei Date: Sun, 19 Apr 2020 02:41:31 -0700 Subject: [PATCH 4/9] Make 'Complex' differentiable. * Conform `Complex` to `Differentiable`. * Define derivatives for `init(_:_:)`, `real`, `imaginary`, `conjugate`, `+(_:_:)`, `-(_:_:)`, `*(_:_:)`, `/(_:_:)`. Gated under `#if canImport(_Differentiation)`. --- Sources/ComplexModule/Differentiable.swift | 94 ++++++++++++++++++++ Tests/ComplexTests/DifferentiableTests.swift | 74 +++++++++++++++ 2 files changed, 168 insertions(+) create mode 100644 Sources/ComplexModule/Differentiable.swift create mode 100644 Tests/ComplexTests/DifferentiableTests.swift diff --git a/Sources/ComplexModule/Differentiable.swift b/Sources/ComplexModule/Differentiable.swift new file mode 100644 index 0000000..75883f7 --- /dev/null +++ b/Sources/ComplexModule/Differentiable.swift @@ -0,0 +1,94 @@ +//===--- Differentiable.swift ---------------------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if canImport(_Differentiation) +import _Differentiation + +extension Complex: Differentiable +where RealType: Differentiable, RealType.TangentVector == RealType { + public typealias TangentVector = Self +} + +extension Complex +where RealType: Differentiable, RealType.TangentVector == RealType { + @derivative(of: init(_:_:)) + @usableFromInline + static func _derivativeInit( + _ real: RealType, + _ imaginary: RealType + ) -> (value: Complex, pullback: (Complex) -> (RealType, RealType)) { + (value: .init(real, imaginary), pullback: { v in + (v.real, v.imaginary) + }) + } + + @derivative(of: real) + @usableFromInline + func _derivativeReal() -> (value: RealType, pullback: (RealType) -> Complex) { + (value: real, pullback: { v in + Complex(v, .zero) + }) + } + + @derivative(of: imaginary) + @usableFromInline + func _derivativeImaginary() -> ( + value: RealType, + pullback: (RealType) -> Complex + ) { + (value: real, pullback: { v in + Complex(.zero, v) + }) + } + + @derivative(of: +) + @usableFromInline + static func _derivativeAdd(lhs: Complex, rhs: Complex) + -> (value: Complex, pullback: (Complex) -> (Complex, Complex)) + { + (lhs + rhs, { v in (v, v) }) + } + + @derivative(of: -) + @usableFromInline + static func _derivativeSubtract(lhs: Complex, rhs: Complex) + -> (value: Complex, pullback: (Complex) -> (Complex, Complex)) + { + (lhs - rhs, { v in (v, -v) }) + } + + @derivative(of: *) + @usableFromInline + static func _derivativeMultiply(lhs: Complex, rhs: Complex) + -> (value: Complex, pullback: (Complex) -> (Complex, Complex)) + { + (lhs * rhs, { v in (rhs * v, lhs * v) }) + } + + @derivative(of: /) + @usableFromInline + static func _derivativeDivide(lhs: Complex, rhs: Complex) + -> (value: Complex, pullback: (Complex) -> (Complex, Complex)) + { + (lhs / rhs, { v in (v / rhs, -lhs / (rhs * rhs) * v) }) + } + + @derivative(of: conjugate) + @usableFromInline + func _derivativeConjugate() -> ( + value: Complex, + pullback: (Complex) -> Complex + ) { + (conjugate, { v in v.conjugate }) + } +} + +#endif diff --git a/Tests/ComplexTests/DifferentiableTests.swift b/Tests/ComplexTests/DifferentiableTests.swift new file mode 100644 index 0000000..0dc09df --- /dev/null +++ b/Tests/ComplexTests/DifferentiableTests.swift @@ -0,0 +1,74 @@ +//===--- DifferentiableTests.swift ----------------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if canImport(_Differentiation) + +import XCTest +import ComplexModule +import _Differentiation + +final class DifferentiableTests: XCTestCase { + func testComponentGetter() { + XCTAssertEqual( + gradient(at: Complex(5, 5)) { $0.real * 2 }, + Complex(2, 0)) + XCTAssertEqual( + gradient(at: Complex(5, 5)) { $0.imaginary * 2 }, + Complex(0, 2)) + XCTAssertEqual( + gradient(at: Complex(5, 5)) { $0.real * 5 + $0.imaginary * 2 }, + Complex(5, 2)) + } + + func testInitializer() { + let φ1 = pullback(at: 4, -3) { r, i in Complex(r, i) } + let tan1 = φ1(Complex(-1, 2)) + XCTAssertEqual(tan1.0, -1) + XCTAssertEqual(tan1.1, 2) + + let φ2 = pullback(at: 4, -3) { r, i in Complex(r * r, i + i) } + let tan2 = φ2(Complex(-1, 1)) + XCTAssertEqual(tan2.0, -8) + XCTAssertEqual(tan2.1, 2) + } + + func testConjugate() { + let φ = pullback(at: Complex(20, -4)) { x in x.conjugate } + XCTAssertEqual(φ(Complex(1, 0)), Complex(1, 0)) + XCTAssertEqual(φ(Complex(0, 1)), Complex(0, -1)) + XCTAssertEqual(φ(Complex(-1, 1)), Complex(-1, -1)) + } + + func testArithmetics() { + let φAdd = pullback(at: Complex(2, 3)) { x in + x + Complex(5, 6) + } + XCTAssertEqual(φAdd(Complex(1, 1)), Complex(1, 1)) + + let φSubtract = pullback(at: Complex(2, 3)) { x in + Complex(5, 6) - x + } + XCTAssertEqual(φSubtract(Complex(1, 1)), Complex(-1, -1)) + + let φMultiply = pullback(at: Complex(2, 3)) { x in x * x } + XCTAssertEqual(φMultiply(Complex(1, 0)), Complex(4, 6)) + XCTAssertEqual(φMultiply(Complex(0, 1)), Complex(-6, 4)) + XCTAssertEqual(φMultiply(Complex(1, 1)), Complex(-2, 10)) + + let φDivide = pullback(at: Complex(20, -4)) { x in + x / Complex(2, 2) + } + XCTAssertEqual(φDivide(Complex(1, 0)), Complex(0.25, -0.25)) + XCTAssertEqual(φDivide(Complex(0, 1)), Complex(0.25, 0.25)) + } +} + +#endif From 750170404ad62d735cc5df9fb320799f9e52aab5 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Fri, 1 May 2020 08:50:32 -0400 Subject: [PATCH 5/9] The derivative of Complex.init(_:_:) is broken with the current Xcode toolchain. Remove it for now; it'll still be present on the -5.3 branch, so we'll pick it up again when we're able to. --- Sources/ComplexModule/Differentiable.swift | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/Sources/ComplexModule/Differentiable.swift b/Sources/ComplexModule/Differentiable.swift index 75883f7..443a1d5 100644 --- a/Sources/ComplexModule/Differentiable.swift +++ b/Sources/ComplexModule/Differentiable.swift @@ -19,16 +19,6 @@ where RealType: Differentiable, RealType.TangentVector == RealType { extension Complex where RealType: Differentiable, RealType.TangentVector == RealType { - @derivative(of: init(_:_:)) - @usableFromInline - static func _derivativeInit( - _ real: RealType, - _ imaginary: RealType - ) -> (value: Complex, pullback: (Complex) -> (RealType, RealType)) { - (value: .init(real, imaginary), pullback: { v in - (v.real, v.imaginary) - }) - } @derivative(of: real) @usableFromInline From c111cd001e40992dea1e85019957bbb12d267c72 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Fri, 1 May 2020 08:58:47 -0400 Subject: [PATCH 6/9] Also remove tests for broken derivative. --- Tests/ComplexTests/DifferentiableTests.swift | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/Tests/ComplexTests/DifferentiableTests.swift b/Tests/ComplexTests/DifferentiableTests.swift index 0dc09df..4ade368 100644 --- a/Tests/ComplexTests/DifferentiableTests.swift +++ b/Tests/ComplexTests/DifferentiableTests.swift @@ -28,18 +28,6 @@ final class DifferentiableTests: XCTestCase { Complex(5, 2)) } - func testInitializer() { - let φ1 = pullback(at: 4, -3) { r, i in Complex(r, i) } - let tan1 = φ1(Complex(-1, 2)) - XCTAssertEqual(tan1.0, -1) - XCTAssertEqual(tan1.1, 2) - - let φ2 = pullback(at: 4, -3) { r, i in Complex(r * r, i + i) } - let tan2 = φ2(Complex(-1, 1)) - XCTAssertEqual(tan2.0, -8) - XCTAssertEqual(tan2.1, 2) - } - func testConjugate() { let φ = pullback(at: Complex(20, -4)) { x in x.conjugate } XCTAssertEqual(φ(Complex(1, 0)), Complex(1, 0)) From 4297fbee6a208f05f6f1987c328f2a3ffd467538 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Tue, 5 May 2020 15:13:47 -0400 Subject: [PATCH 7/9] Remove complex benchmarks from tests for now I'm going to reinstate this as a binary executable target, so that we can ensure it only runs in release (and add some useful command line options via the argument parser). In the short-term, I want to unblock @compnerd's work on supporting Windows, so I'm preemtively removing the test (these tests cannot run on Windows). --- .../_NumericsShims/include/_NumericsShims.h | 6 + .../ArithmeticBenchmarkTests.swift | 180 ------------------ 2 files changed, 6 insertions(+), 180 deletions(-) delete mode 100644 Tests/ComplexTests/ArithmeticBenchmarkTests.swift diff --git a/Sources/_NumericsShims/include/_NumericsShims.h b/Sources/_NumericsShims/include/_NumericsShims.h index 4e1b40b..47148da 100644 --- a/Sources/_NumericsShims/include/_NumericsShims.h +++ b/Sources/_NumericsShims/include/_NumericsShims.h @@ -383,6 +383,10 @@ HEADER_SHIM long double libm_lgammal(long double x, int *signp) { #endif // MARK: - shims to import C complex operations for timing purposes +#if !defined _WIN32 +// Clang doesn't have support for complex arithmetic on Windows, so +// it doesn't make sense to benchmark against it (and these will +// fail to link if used there). typedef struct { double real; double imag; } CComplex; @@ -399,3 +403,5 @@ HEADER_SHIM CComplex libm_cmul(CComplex z, CComplex w) { double _Complex c = a*b; return (CComplex){ __real__ c, __imag__ c }; } + +#endif diff --git a/Tests/ComplexTests/ArithmeticBenchmarkTests.swift b/Tests/ComplexTests/ArithmeticBenchmarkTests.swift deleted file mode 100644 index 6b2d94d..0000000 --- a/Tests/ComplexTests/ArithmeticBenchmarkTests.swift +++ /dev/null @@ -1,180 +0,0 @@ -//===--- ArithmeticBenchmarkTests.swift -----------------------*- swift -*-===// -// -// This source file is part of the Swift Numerics open source project -// -// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -import XCTest -import ComplexModule - -// For CComplex and shims -import _NumericsShims - -extension Complex where RealType == Double { - @_transparent - init(_ other: CComplex) { - self = unsafeBitCast(other, to: Complex.self) - } - @_transparent - var ctype: CComplex { - unsafeBitCast(self, to: CComplex.self) - } -} - -let wellScaledDoubles: [Complex] = (0 ..< 1024).map { _ in - Complex(length: Double.random(in: 0.5 ..< 2.0), - phase: Double.random(in: -.pi ..< .pi)) -} - -let poorlyScaledDoubles: [Complex] = (0 ..< 1024).map { _ in - Complex( - length: Double(sign: .plus, - exponent: .random(in: -970 ... 1023), - significand: .random(in: 1 ..< 2)), - phase: Double.random(in: -.pi ..< .pi) - ) -} - -final class ArithmeticBenchmarkTests: XCTestCase { - - let iters = 1000 - - func testDivisionByConstant() { - let divisor = wellScaledDoubles[0] - var sum = Complex.zero - measure { - for _ in 0 ..< iters { - sum = wellScaledDoubles.reduce(into: sum) { $0 += $1 / divisor } - } - } - print(sum) - } - - func testReciprocal() { - let recip = wellScaledDoubles[0].reciprocal! - var sum = Complex.zero - measure { - for _ in 0 ..< iters { - sum = wellScaledDoubles.reduce(into: sum) { $0 += $1 * recip } - } - } - print(sum) - } - - func testDivisionByConstantC() { - let divisor = wellScaledDoubles[0].ctype - var sum = Complex.zero - measure { - for _ in 0 ..< iters { - sum = wellScaledDoubles.reduce(into: sum) { - $0 += Complex(libm_cdiv($1.ctype, divisor)) - } - } - } - print(sum) - } - - func testMultiplication() { - let multiplicand = wellScaledDoubles[0] - var sum = Complex.zero - measure { - for _ in 0 ..< iters { - sum = wellScaledDoubles.reduce(into: sum) { $0 += $1 * multiplicand } - } - } - print(sum) - } - - func testMultiplicationC() { - let multiplicand = wellScaledDoubles[0].ctype - var sum = Complex.zero - measure { - for _ in 0 ..< iters { - sum = wellScaledDoubles.reduce(into: sum) { - $0 += Complex(libm_cmul($1.ctype, multiplicand)) - } - } - } - print(sum) - } - - func testDivision() { - var sum = Complex.zero - measure { - for o in 0 ..< iters { - for i in 0 ..< 1024 { - sum += wellScaledDoubles[i] / wellScaledDoubles[(i &- o) & 1023] - } - } - } - print(sum) - } - - func testDivisionC() { - var sum = Complex.zero - measure { - for o in 0 ..< iters { - for i in 0 ..< 1024 { - sum += Complex(libm_cdiv(wellScaledDoubles[i].ctype, - wellScaledDoubles[(i &- o) & 1023].ctype)) - } - } - } - print(sum) - } - - func testDivisionPoorScaling() { - var sum = Complex.zero - measure { - for o in 0 ..< iters { - for i in 0 ..< 1024 { - sum += poorlyScaledDoubles[i] / poorlyScaledDoubles[(i &- o) & 1023] - } - } - } - print(sum) - } - - func testDivisionPoorScalingC() { - var sum = Complex.zero - measure { - for o in 0 ..< iters { - for i in 0 ..< 1024 { - sum += Complex(libm_cdiv(poorlyScaledDoubles[i].ctype, - poorlyScaledDoubles[(i &- o) & 1023].ctype)) - } - } - } - print(sum) - } - - func testMultiplicationPoorScaling() { - var sum = Complex.zero - measure { - for o in 0 ..< iters { - for i in 0 ..< 1024 { - sum += poorlyScaledDoubles[i] * poorlyScaledDoubles[(i &- o) & 1023] - } - } - } - print(sum) - } - - func testMultiplicationPoorScalingC() { - var sum = Complex.zero - measure { - for o in 0 ..< iters { - for i in 0 ..< 1024 { - sum += Complex(libm_cmul(poorlyScaledDoubles[i].ctype, - poorlyScaledDoubles[(i &- o) & 1023].ctype)) - } - } - } - print(sum) - } -} From 5f09b7ef22fbc282643f4b7ffb21cc2613c56bed Mon Sep 17 00:00:00 2001 From: Markus Winter Date: Tue, 26 May 2020 15:44:47 +0200 Subject: [PATCH 8/9] Update documentation in ComplexModule Replace the now deprecated unsafeLengthSquared reference with the newer lengthSquared in the README.md of the Complex module. --- Sources/ComplexModule/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/ComplexModule/README.md b/Sources/ComplexModule/README.md index a8b3370..dd758d3 100644 --- a/Sources/ComplexModule/README.md +++ b/Sources/ComplexModule/README.md @@ -60,7 +60,7 @@ Because of this, the ∞-norm is the obvious alternative; it gives the nicest AP - The ∞-norm is heavily used in other computational libraries; for example, it is used by the `izamax` and `icamax` functions in BLAS. The 2-norm still needs to be available, of course, because sometimes you need it. -This functionality is accessed via the `.length` and `.unsafeLengthSquared` properties. +This functionality is accessed via the `.length` and `.lengthSquared` properties. ### Accuracy of division and multiplication This library attempts to provide robust division and multiplication operations, with small relative error in a complex norm. It is a non-goal to deliver small componentwise errors. From 86f0b33c65c4efc77fe71fe31eaa160d777b5a55 Mon Sep 17 00:00:00 2001 From: Dan Zheng Date: Mon, 8 Jun 2020 15:57:41 -0700 Subject: [PATCH 9/9] Define `Complex.zeroTangentVectorInitializer`. The `Differentiable.zeroTangentVectorInitializer` protocol requirement is a closure producing a zero tangent vector, capturing minimal information from `self`. Fixes the `Complex: Differentiable` conformance for master toolchains. --- Sources/ComplexModule/Differentiable.swift | 5 +++++ Tests/ComplexTests/DifferentiableTests.swift | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/Sources/ComplexModule/Differentiable.swift b/Sources/ComplexModule/Differentiable.swift index 443a1d5..5e2f304 100644 --- a/Sources/ComplexModule/Differentiable.swift +++ b/Sources/ComplexModule/Differentiable.swift @@ -15,6 +15,11 @@ import _Differentiation extension Complex: Differentiable where RealType: Differentiable, RealType.TangentVector == RealType { public typealias TangentVector = Self + + @inlinable + public var zeroTangentVectorInitializer: () -> Self { + { Complex.zero } + } } extension Complex diff --git a/Tests/ComplexTests/DifferentiableTests.swift b/Tests/ComplexTests/DifferentiableTests.swift index 4ade368..31759ac 100644 --- a/Tests/ComplexTests/DifferentiableTests.swift +++ b/Tests/ComplexTests/DifferentiableTests.swift @@ -57,6 +57,10 @@ final class DifferentiableTests: XCTestCase { XCTAssertEqual(φDivide(Complex(1, 0)), Complex(0.25, -0.25)) XCTAssertEqual(φDivide(Complex(0, 1)), Complex(0.25, 0.25)) } + + func testZeroTangentVectorInitializer() { + XCTAssertEqual(Complex(-5, 5).zeroTangentVector, Complex(0, 0)) + } } #endif