From 97bab250eb6b46585b6b74cc65560a62c380d8a8 Mon Sep 17 00:00:00 2001 From: Steve Canon Date: Tue, 14 May 2024 10:24:31 -0400 Subject: [PATCH 1/7] WIP --- .../Complex+AlgebraicField.swift | 113 +++++++--- Tests/ComplexTests/ArithmeticTests.swift | 211 +++++++++++------- 2 files changed, 203 insertions(+), 121 deletions(-) diff --git a/Sources/ComplexModule/Complex+AlgebraicField.swift b/Sources/ComplexModule/Complex+AlgebraicField.swift index 4908b57..d3559d3 100644 --- a/Sources/ComplexModule/Complex+AlgebraicField.swift +++ b/Sources/ComplexModule/Complex+AlgebraicField.swift @@ -26,53 +26,96 @@ extension Complex: AlgebraicField { Complex(x, -y) } + @_transparent + public static func /=(z: inout Complex, w: Complex) { + z = z / w + } + @_transparent public static func /(z: Complex, w: Complex) -> Complex { - // Try the naive expression z/w = z*conj(w) / |w|^2; if we can compute - // this without over/underflow, everything is fine and the result is - // correct. If not, we have to rescale and do the computation carefully. + // Try the naive expression z/w = z * (conj(w) / |w|^2); if we can + // compute this without over/underflow, everything is fine and the + // result is correct. If not, we have to rescale and do the + // computation carefully (see below). let lenSq = w.lengthSquared guard lenSq.isNormal else { return rescaledDivide(z, w) } return z * (w.conjugate.divided(by: lenSq)) } - @_transparent - public static func /=(z: inout Complex, w: Complex) { - z = z / w - } - - @usableFromInline @_alwaysEmitIntoClient @inline(never) + @inline(never) + @_specialize(exported: true, where RealType == Float) + @_specialize(exported: true, where RealType == Double) + @usableFromInline internal static func rescaledDivide(_ z: Complex, _ w: Complex) -> Complex { if w.isZero { return .infinity } - if z.isZero || !w.isFinite { return .zero } - // TODO: detect when RealType is Float and just promote to Double, then - // use the naive algorithm. - let zScale = z.magnitude - let wScale = w.magnitude - let zNorm = z.divided(by: zScale) - let wNorm = w.divided(by: wScale) - let r = (zNorm * wNorm.conjugate).divided(by: wNorm.lengthSquared) - // At this point, the result is (r * zScale)/wScale computed without - // undue overflow or underflow. We know that r is close to unity, so - // the question is simply what order in which to do this computation - // to avoid spurious overflow or underflow. There are three options - // to choose from: + if !w.isFinite { return .zero } + // Scaling algorithm adapted from Doug Priest's "Efficient Scaling for + // Complex Division": // - // - r * (zScale / wScale) - // - (r * zScale) / wScale - // - (r / wScale) * zScale + // 1. Choose real scale s ≅ |w|^(-¾), an exact power of the radix. + // 2. wʹ ← sw + // 3. zʹ ← sz + // 4. return zʹ * (wʹ.conjugate / wʹ.lengthSquared) // - // The simplest case is when zScale / wScale is normal: - if (zScale / wScale).isNormal { - return r.multiplied(by: zScale / wScale) + // Why is this safe and accurate? First, observe that wʹ and zʹ are both + // computed exactly because: + // + // - s is an exact power of radix. + // - wʹ ~ |w|^(¼), and hence cannot overflow or underflow. + // - zʹ can overflow or underflow, but only if the final result also + // overflows or underflows (this is more subtle than it might + // appear at first; Priest has to be very careful about it + // because you get into trouble precisely in the case where + // |w| is very close to 1. However, if we were in that case, we would + // have just handled the division inline and never would have ended + // up here. + // + // Next observe that |wʹ.lengthSquared| ~ |w|^(½), so again this cannot + // overflow or underflow, and neither can + // (wʹ.conjugate / wʹ.lengthSquared) + + + // are of comparable + // magnitude, and in particular the exponents of their magnitudes have the + // same sign, so either both are a contraction or both are an expansion, + // so any intermediate overflow or underflow is deserved.² + // + // Note that because the scale factor is always a power of the radix, + // the rescaling does not affect rounding, and so this algorithm is scale- + // invariant compared to the mainline `/` implementation, up to the + // underflow boundary. + // + // ¹ This falls apart for formats where the number of significand bits is + // comparable to the exponent range (in particular Float16), because then + // the desired s is not representable. E.g. if w ~ .leastNonzeroMagnitude + // in Float16 (0x1p-24), we want to have s = 0x1p18, which is outside the + // range of representable values. This does not occur for any other types, + // so we just carry a special-case implementation for Float16 to fix it. + // + // Priest never had to worry about this because Float16 didn't really exist + // yet when he published and he was interested in double anyway. + // + // ² This WOULD NOT BE TRUE if we hadn't already handled well-scaled + // divisors in the mainline path for the `/` operator above; it only + // holds for sufficiently badly-scaled `w`. If the well-scaled cases + // were not already eliminated, it would be possible to have |wʹ| a + // little bigger than one and |wʺ| a bit smaller than one (or vice-versa), so + // that intermediate undeserved overflow or underflow might occur. Priest + // has to worry about this, but we do not. + if w.magnitude < RealType.leastNormalMagnitude { + let z = z.divided(by: RealType.leastNormalMagnitude) + let w = w.divided(by: RealType.leastNormalMagnitude) + return rescaledDivide(z, w) } - // Otherwise, we need to compute either rNorm * zScale or rNorm / wScale - // first. Choose the first if the first scaling behaves well, otherwise - // choose the other one. - if (r.magnitude * zScale).isNormal { - return r.multiplied(by: zScale).divided(by: wScale) - } - return r.divided(by: wScale).multiplied(by: zScale) + var exponent = -3 * w.magnitude.exponent / 4 + let s = RealType( + sign: .plus, + exponent: exponent, + significand: 1 + ) + let wʹ = w.multiplied(by: s) + let zʹ = z.multiplied(by: s) + return zʹ / wʹ } /// A normalized complex number with the same phase as this value. diff --git a/Tests/ComplexTests/ArithmeticTests.swift b/Tests/ComplexTests/ArithmeticTests.swift index a2ad64b..d0be893 100644 --- a/Tests/ComplexTests/ArithmeticTests.swift +++ b/Tests/ComplexTests/ArithmeticTests.swift @@ -30,10 +30,10 @@ func checkMultiply( ) -> Bool { let observed = a*b let rel = relativeError(observed, expected) - if rel > allowed { + guard rel <= allowed else { print("Over-large error in \(a)*\(b)") print("Expected: \(expected)\nObserved: \(observed)") - print("Relative error was \(rel) (tolerance: \(allowed).") + print("Relative error was \(rel) (tolerance: \(allowed)).") return true } return false @@ -44,10 +44,10 @@ func checkDivide( ) -> Bool { let observed = a/b let rel = relativeError(observed, expected) - if rel > allowed { + guard rel <= allowed else { print("Over-large error in \(a)/\(b)") print("Expected: \(expected)\nObserved: \(observed)") - print("Relative error was \(rel) (tolerance: \(allowed).") + print("Relative error was \(rel) (tolerance: \(allowed)).") return true } return false @@ -63,93 +63,99 @@ final class ArithmeticTests: XCTestCase { func testPolar(_ type: T.Type) where T: BinaryFloatingPoint, T: Real, T.Exponent: FixedWidthInteger, T.RawSignificand: FixedWidthInteger { - - // In order to support round-tripping from rectangular to polar coordinate - // systems, as a special case phase can be non-finite when length is - // either zero or infinity. - XCTAssertEqual(Complex(length: .zero, phase: .infinity), .zero) - XCTAssertEqual(Complex(length: .zero, phase:-.infinity), .zero) - XCTAssertEqual(Complex(length: .zero, phase: .nan ), .zero) - XCTAssertEqual(Complex(length: .infinity, phase: .infinity), .infinity) - XCTAssertEqual(Complex(length: .infinity, phase:-.infinity), .infinity) - XCTAssertEqual(Complex(length: .infinity, phase: .nan ), .infinity) - XCTAssertEqual(Complex(length:-.infinity, phase: .infinity), .infinity) - XCTAssertEqual(Complex(length:-.infinity, phase:-.infinity), .infinity) - XCTAssertEqual(Complex(length:-.infinity, phase: .nan ), .infinity) - let exponentRange = - (T.leastNormalMagnitude.exponent + T.Exponent(T.significandBitCount)) ... - T.greatestFiniteMagnitude.exponent - let inputs = (0..<100).map { _ in - Polar(length: T( - sign: .plus, - exponent: T.Exponent.random(in: exponentRange), - significand: T.random(in: 1 ..< 2) - ), phase: T.random(in: -.pi ... .pi)) - } - for p in inputs { - // first test that each value can round-trip between rectangular and - // polar coordinates with reasonable accuracy. We'll probably need to - // relax this for some platforms (currently we're using the default - // RNG, which means we don't get the same sequence of values each time; - // this is good--more test coverage!--and bad, because without tight - // bounds on every platform's libm, we can't get tight bounds on the - // accuracy of these operations, so we need to relax them gradually). - let z = Complex(length: p.length, phase: p.phase) - if !closeEnough(z.length, p.length, ulps: 16) { - print("p = \(p)\nz = \(z)\nz.length = \(z.length)") - XCTFail() - } - if !closeEnough(z.phase, p.phase, ulps: 16) { - print("p = \(p)\nz = \(z)\nz.phase = \(z.phase)") - XCTFail() - } - // Complex(length: -r, phase: θ) = -Complex(length: r, phase: θ). - let w = Complex(length: -p.length, phase: p.phase) - if w != -z { - print("p = \(p)\nw = \(w)\nz = \(z)") - XCTFail() - } - XCTAssertEqual(w, -z) - // if length*length is normal, it should be lengthSquared, up - // to small error. - if (p.length*p.length).isNormal { - if !closeEnough(z.lengthSquared, p.length*p.length, ulps: 16) { - print("p = \(p)\nz = \(z)\nz.lengthSquared = \(z.lengthSquared)") - XCTFail() + // In order to support round-tripping from rectangular to polar coordinate + // systems, as a special case phase can be non-finite when length is + // either zero or infinity. + XCTAssertEqual(Complex(length: .zero, phase: .infinity), .zero) + XCTAssertEqual(Complex(length: .zero, phase:-.infinity), .zero) + XCTAssertEqual(Complex(length: .zero, phase: .nan ), .zero) + XCTAssertEqual(Complex(length: .infinity, phase: .infinity), .infinity) + XCTAssertEqual(Complex(length: .infinity, phase:-.infinity), .infinity) + XCTAssertEqual(Complex(length: .infinity, phase: .nan ), .infinity) + XCTAssertEqual(Complex(length:-.infinity, phase: .infinity), .infinity) + XCTAssertEqual(Complex(length:-.infinity, phase:-.infinity), .infinity) + XCTAssertEqual(Complex(length:-.infinity, phase: .nan ), .infinity) + + let exponentRange = + T.leastNormalMagnitude.exponent ... T.greatestFiniteMagnitude.exponent + let inputs = (0..<100).map { _ in + Polar(length: T( + sign: .plus, + exponent: T.Exponent.random(in: exponentRange), + significand: T.random(in: 1 ..< 2) + ), phase: T.random(in: -.pi ... .pi)) + } + for p in inputs { + // first test that each value can round-trip between rectangular and + // polar coordinates with reasonable accuracy. We'll probably need to + // relax this for some platforms (currently we're using the default + // RNG, which means we don't get the same sequence of values each time; + // this is good--more test coverage!--and bad, because without tight + // bounds on every platform's libm, we can't get tight bounds on the + // accuracy of these operations, so we need to relax them gradually). + let z = Complex(length: p.length, phase: p.phase) + if !closeEnough(z.length, p.length, ulps: 16) { + print("p = \(p)\nz = \(z)\nz.length = \(z.length)") + XCTFail() + } + if !closeEnough(z.phase, p.phase, ulps: 16) { + print("p = \(p)\nz = \(z)\nz.phase = \(z.phase)") + XCTFail() + } + // Complex(length: -r, phase: θ) = -Complex(length: r, phase: θ). + let w = Complex(length: -p.length, phase: p.phase) + if w != -z { + print("p = \(p)\nw = \(w)\nz = \(z)") + XCTFail() + } + XCTAssertEqual(w, -z) + // if length*length is normal, it should be lengthSquared, up + // to small error. + if (p.length*p.length).isNormal { + if !closeEnough(z.lengthSquared, p.length*p.length, ulps: 16) { + print("p = \(p)\nz = \(z)\nz.lengthSquared = \(z.lengthSquared)") + XCTFail() + } + } + // Test reciprocal and normalized: + let r = Complex(length: 1/p.length, phase: -p.phase) + if r.isNormal { + if relativeError(r, z.reciprocal!) > 16 { + print("p = \(p)\nz = \(z)\nz.reciprocal = \(r)") + XCTFail() + } + } else { XCTAssertNil(z.reciprocal) } + let n = Complex(length: 1, phase: p.phase) + if relativeError(n, z.normalized!) > 16 { + print("p = \(p)\nz = \(z)\nz.normalized = \(n)") + XCTFail() + } + + // Now test multiplication and division using the polar inputs: + for q in inputs { + let w = Complex(length: q.length, phase: q.phase) + var product = Complex(length: p.length, phase: p.phase + q.phase) + product.real *= q.length + product.imaginary *= q.length + if checkMultiply(z, w, expected: product, ulps: 16) { XCTFail() } + var quotient = Complex(length: p.length, phase: p.phase - q.phase) + quotient.real /= q.length + quotient.imaginary /= q.length + if checkDivide(z, w, expected: quotient, ulps: 16) { XCTFail() } + } + } } - } - // Test reciprocal and normalized: - let r = Complex(length: 1/p.length, phase: -p.phase) - if r.isNormal { - if relativeError(r, z.reciprocal!) > 16 { - print("p = \(p)\nz = \(z)\nz.reciprocal = \(r)") - XCTFail() - } - } else { XCTAssertNil(z.reciprocal) } - let n = Complex(length: 1, phase: p.phase) - if relativeError(n, z.normalized!) > 16 { - print("p = \(p)\nz = \(z)\nz.normalized = \(n)") - XCTFail() - } - - // Now test multiplication and division using the polar inputs: - for q in inputs { - let w = Complex(length: q.length, phase: q.phase) - let product = Complex(length: p.length * q.length, phase: p.phase + q.phase) - if checkMultiply(z, w, expected: product, ulps: 16) { XCTFail() } - let quotient = Complex(length: p.length / q.length, phase: p.phase - q.phase) - if checkDivide(z, w, expected: quotient, ulps: 16) { XCTFail() } - } - } - } func testPolar() { +#if (arch(arm64)) + // testPolar(Float16.self) +#endif testPolar(Float.self) testPolar(Double.self) - #if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android) +#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android) testPolar(Float80.self) - #endif +#endif } func testBaudinSmith() { @@ -191,16 +197,49 @@ final class ArithmeticTests: XCTestCase { Complex(1.02951151789360578e-84, 6.97145987515076231e-220)), ] for test in vectors { - if checkDivide(test.a, test.b, expected: test.c, ulps: 0.5) { XCTFail() } + if checkDivide(test.a, test.b, expected: test.c, ulps: 1.0) { XCTFail() } if checkDivide(test.a, test.c, expected: test.b, ulps: 1.0) { XCTFail() } if checkMultiply(test.b, test.c, expected: test.a, ulps: 1.0) { XCTFail() } } } - + func testDivisionByZero() { XCTAssertFalse((Complex(0, 0) / Complex(0, 0)).isFinite) XCTAssertFalse((Complex(1, 1) / Complex(0, 0)).isFinite) XCTAssertFalse((Complex.infinity / Complex(0, 0)).isFinite) XCTAssertFalse((Complex.i / Complex(0, 0)).isFinite) + } + +#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64)) + + /* + @available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) + func testFloat16DivisionSemiExhaustive() { + func complex(bitPattern: UInt32) -> Complex { + Complex( + Float16(bitPattern: UInt16(truncatingIfNeeded: bitPattern)), + Float16(bitPattern: UInt16(truncatingIfNeeded: bitPattern >> 16)) + ) + } + for bits in 0 ... UInt32.max { + let a = complex(bitPattern: bits) + if bits & 0xfffff == 0 { print(a) } + let b = complex(bitPattern: UInt32.random(in: 0 ... .max)) + var q = Complex(a)/Complex(b) + if checkDivide(a, b, expected: Complex(q), ulps: 32) { XCTFail() } + q = Complex(b)/Complex(a) + if checkDivide(b, a, expected: Complex(q), ulps: 32) { XCTFail() } + } + } + */ + + @available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) + func testSpecificFloat16Value() { + let a = Complex(4.66, 3e-07) + let b = Complex(-4.32e-05, 4.977e-05) + let q = a / b + XCTAssertEqual(q, Complex(-46368.0, -53376.0)) + } +#endif } From 1ba2178227a8d09fb16a9d676039ef65a4aa79f1 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Tue, 14 May 2024 17:22:50 -0400 Subject: [PATCH 2/7] Further progress on complex division --- .../Complex+AlgebraicField.swift | 114 ++++++++---------- Tests/ComplexTests/ArithmeticTests.swift | 16 ++- 2 files changed, 56 insertions(+), 74 deletions(-) diff --git a/Sources/ComplexModule/Complex+AlgebraicField.swift b/Sources/ComplexModule/Complex+AlgebraicField.swift index d3559d3..b42ada7 100644 --- a/Sources/ComplexModule/Complex+AlgebraicField.swift +++ b/Sources/ComplexModule/Complex+AlgebraicField.swift @@ -39,83 +39,67 @@ extension Complex: AlgebraicField { // computation carefully (see below). let lenSq = w.lengthSquared guard lenSq.isNormal else { return rescaledDivide(z, w) } - return z * (w.conjugate.divided(by: lenSq)) + return z * w.conjugate.divided(by: lenSq) } - @inline(never) - @_specialize(exported: true, where RealType == Float) - @_specialize(exported: true, where RealType == Double) - @usableFromInline - internal static func rescaledDivide(_ z: Complex, _ w: Complex) -> Complex { + public static func rescaledDivide(_ z: Complex, _ w: Complex) -> Complex { if w.isZero { return .infinity } if !w.isFinite { return .zero } - // Scaling algorithm adapted from Doug Priest's "Efficient Scaling for - // Complex Division": + // Scaling algorithm adapted from Doug Priest's "Efficient Scaling for + // Complex Division": // - // 1. Choose real scale s ≅ |w|^(-¾), an exact power of the radix. - // 2. wʹ ← sw - // 3. zʹ ← sz - // 4. return zʹ * (wʹ.conjugate / wʹ.lengthSquared) + // 1. Choose real scale s ~ |w|^(-¾), an exact power of the radix. + // 2. wʹ ← sw + // 3. zʹ ← sz + // 4. return zʹ * (wʹ.conjugate / wʹ.lengthSquared) (i.e. zʹ/wʹ). // - // Why is this safe and accurate? First, observe that wʹ and zʹ are both - // computed exactly because: + // Why is this safe and accurate? First, observe that wʹ and zʹ are both + // computed exactly because: // - // - s is an exact power of radix. - // - wʹ ~ |w|^(¼), and hence cannot overflow or underflow. - // - zʹ can overflow or underflow, but only if the final result also - // overflows or underflows (this is more subtle than it might - // appear at first; Priest has to be very careful about it - // because you get into trouble precisely in the case where - // |w| is very close to 1. However, if we were in that case, we would - // have just handled the division inline and never would have ended - // up here. + // - s is an exact power of radix. + // - wʹ ~ |w|^(¼), and hence cannot overflow or underflow. + // - zʹ might overflow or underflow, but only if the final result also + // overflows or underflows. (This is more subtle than I make it + // sound. In particular, most of the fast ways one might try to + // compute s give rise to a situation where when |w| is close to + // one, multiplication by s is a dilation even though the actual + // division is a contraction or vice-versa, and thus intermediate + // computations might incorrectly overflow or underflow. Priest + // had to take some care to avoid this situation, but we do not, + // because we have already ruled out |w| ~ 1 before we call this + // function.) // - // Next observe that |wʹ.lengthSquared| ~ |w|^(½), so again this cannot - // overflow or underflow, and neither can - // (wʹ.conjugate / wʹ.lengthSquared) - - - // are of comparable - // magnitude, and in particular the exponents of their magnitudes have the - // same sign, so either both are a contraction or both are an expansion, - // so any intermediate overflow or underflow is deserved.² + // Next observe that |wʹ.lengthSquared| ~ |w|^(½), so again this cannot + // overflow or underflow, and neither can (wʹ.conjugate/wʹ.lengthSquared), + // which has magnitude like |w|^(-¼). // - // Note that because the scale factor is always a power of the radix, - // the rescaling does not affect rounding, and so this algorithm is scale- - // invariant compared to the mainline `/` implementation, up to the - // underflow boundary. + // Note that because the scale factor is always a power of the radix, + // the rescaling does not affect rounding, and so this algorithm is scale- + // invariant compared to the mainline `/` implementation, up to the + // underflow boundary. // - // ¹ This falls apart for formats where the number of significand bits is - // comparable to the exponent range (in particular Float16), because then - // the desired s is not representable. E.g. if w ~ .leastNonzeroMagnitude - // in Float16 (0x1p-24), we want to have s = 0x1p18, which is outside the - // range of representable values. This does not occur for any other types, - // so we just carry a special-case implementation for Float16 to fix it. - // - // Priest never had to worry about this because Float16 didn't really exist - // yet when he published and he was interested in double anyway. - // - // ² This WOULD NOT BE TRUE if we hadn't already handled well-scaled - // divisors in the mainline path for the `/` operator above; it only - // holds for sufficiently badly-scaled `w`. If the well-scaled cases - // were not already eliminated, it would be possible to have |wʹ| a - // little bigger than one and |wʺ| a bit smaller than one (or vice-versa), so - // that intermediate undeserved overflow or underflow might occur. Priest - // has to worry about this, but we do not. + // Another difference from Priest's algorithm is that he didn't have + // to worry about types like Float16, where the significand width is + // comparable to the exponent range, such that |leastNormalMagnitude|^(-¾) + // isn't representable (e.g. for Float16 it would want to be 2¹⁸, while + // the largest allowed exponent is 15). Note that it's critical to + // use zʹ/wʹ after rescaling to avoid this, rather than falling through + // into the normal rescaling, because otherwise we might end up back in + // the situation where |w| ~ 1. if w.magnitude < RealType.leastNormalMagnitude { - let z = z.divided(by: RealType.leastNormalMagnitude) - let w = w.divided(by: RealType.leastNormalMagnitude) - return rescaledDivide(z, w) + let wʹ = w.multiplied(by: 1/(2*RealType.leastNormalMagnitude)) + let zʹ = z.multiplied(by: 1/(2*RealType.leastNormalMagnitude)) + return zʹ/wʹ + } else { + let s = RealType( + sign: .plus, + exponent: -3*w.magnitude.exponent/4, + significand: 1 + ) + let wʹ = w.multiplied(by: s) + let zʹ = z.multiplied(by: s) + return zʹ * wʹ.conjugate.divided(by: wʹ.lengthSquared) } - var exponent = -3 * w.magnitude.exponent / 4 - let s = RealType( - sign: .plus, - exponent: exponent, - significand: 1 - ) - let wʹ = w.multiplied(by: s) - let zʹ = z.multiplied(by: s) - return zʹ / wʹ } /// A normalized complex number with the same phase as this value. diff --git a/Tests/ComplexTests/ArithmeticTests.swift b/Tests/ComplexTests/ArithmeticTests.swift index d0be893..387b24e 100644 --- a/Tests/ComplexTests/ArithmeticTests.swift +++ b/Tests/ComplexTests/ArithmeticTests.swift @@ -30,6 +30,9 @@ func checkMultiply( ) -> Bool { let observed = a*b let rel = relativeError(observed, expected) + // Even if the expected result is finite, we allow overflow if + // the two-norm of the expected result overflows. + if !expected.length.isFinite && !observed.isFinite { return false } guard rel <= allowed else { print("Over-large error in \(a)*\(b)") print("Expected: \(expected)\nObserved: \(observed)") @@ -44,6 +47,9 @@ func checkDivide( ) -> Bool { let observed = a/b let rel = relativeError(observed, expected) + // Even if the expected result is finite, we allow overflow if + // the two-norm of the expected result overflows. + if !expected.length.isFinite && !observed.isFinite { return false } guard rel <= allowed else { print("Over-large error in \(a)/\(b)") print("Expected: \(expected)\nObserved: \(observed)") @@ -149,7 +155,7 @@ final class ArithmeticTests: XCTestCase { func testPolar() { #if (arch(arm64)) - // testPolar(Float16.self) + testPolar(Float16.self) #endif testPolar(Float.self) testPolar(Double.self) @@ -233,13 +239,5 @@ final class ArithmeticTests: XCTestCase { } } */ - - @available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) - func testSpecificFloat16Value() { - let a = Complex(4.66, 3e-07) - let b = Complex(-4.32e-05, 4.977e-05) - let q = a / b - XCTAssertEqual(q, Complex(-46368.0, -53376.0)) - } #endif } From 3fa18ae9b5fa382b1d9565f315f0832c8e9de145 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Thu, 16 May 2024 08:39:12 -0400 Subject: [PATCH 3/7] Test improvements Improved how tolerance is applied close to infinity for complex division (this still could use a more principled approach, but at least we're in the right ballpark now). Tightened up the tolerance for semi-exhaustive testing too, since that can be done now. --- .../Complex+AlgebraicField.swift | 2 ++ Tests/ComplexTests/ArithmeticTests.swift | 29 ++++++++++++------- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/Sources/ComplexModule/Complex+AlgebraicField.swift b/Sources/ComplexModule/Complex+AlgebraicField.swift index b42ada7..57452a4 100644 --- a/Sources/ComplexModule/Complex+AlgebraicField.swift +++ b/Sources/ComplexModule/Complex+AlgebraicField.swift @@ -42,6 +42,8 @@ extension Complex: AlgebraicField { return z * w.conjugate.divided(by: lenSq) } + @_alwaysEmitIntoClient // specialization + @inline(never) public static func rescaledDivide(_ z: Complex, _ w: Complex) -> Complex { if w.isZero { return .infinity } if !w.isFinite { return .zero } diff --git a/Tests/ComplexTests/ArithmeticTests.swift b/Tests/ComplexTests/ArithmeticTests.swift index 387b24e..77ac681 100644 --- a/Tests/ComplexTests/ArithmeticTests.swift +++ b/Tests/ComplexTests/ArithmeticTests.swift @@ -13,11 +13,23 @@ import XCTest import ComplexModule import RealModule +func ulpsFromInfinity(_ a: T) -> T { + (.greatestFiniteMagnitude - a) / .greatestFiniteMagnitude.ulp + 1 +} + // TODO: improve this to be a general-purpose complex comparison with tolerance func relativeError(_ a: Complex, _ b: Complex) -> T { if a == b { return 0 } - let scale = max(a.magnitude, b.magnitude, T.leastNormalMagnitude).ulp - return (a - b).magnitude / scale + if a.isFinite && b.isFinite { + let scale = max(a.magnitude, b.magnitude, T.leastNormalMagnitude).ulp + return (a - b).magnitude / scale + } else { + if a.isFinite { + return ulpsFromInfinity(a.magnitude) + } else { + return ulpsFromInfinity(b.magnitude) + } + } } func closeEnough(_ a: T, _ b: T, ulps allowed: T) -> Bool { @@ -32,7 +44,7 @@ func checkMultiply( let rel = relativeError(observed, expected) // Even if the expected result is finite, we allow overflow if // the two-norm of the expected result overflows. - if !expected.length.isFinite && !observed.isFinite { return false } + if !observed.isFinite && !expected.length.isFinite { return false } guard rel <= allowed else { print("Over-large error in \(a)*\(b)") print("Expected: \(expected)\nObserved: \(observed)") @@ -49,7 +61,7 @@ func checkDivide( let rel = relativeError(observed, expected) // Even if the expected result is finite, we allow overflow if // the two-norm of the expected result overflows. - if !expected.length.isFinite && !observed.isFinite { return false } + if !observed.isFinite && !expected.length.isFinite { return false } guard rel <= allowed else { print("Over-large error in \(a)/\(b)") print("Expected: \(expected)\nObserved: \(observed)") @@ -217,9 +229,7 @@ final class ArithmeticTests: XCTestCase { } -#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64)) - - /* +#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64)) && LONG_TESTS @available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) func testFloat16DivisionSemiExhaustive() { func complex(bitPattern: UInt32) -> Complex { @@ -233,11 +243,10 @@ final class ArithmeticTests: XCTestCase { if bits & 0xfffff == 0 { print(a) } let b = complex(bitPattern: UInt32.random(in: 0 ... .max)) var q = Complex(a)/Complex(b) - if checkDivide(a, b, expected: Complex(q), ulps: 32) { XCTFail() } + if checkDivide(a, b, expected: Complex(q), ulps: 4) { XCTFail() } q = Complex(b)/Complex(a) - if checkDivide(b, a, expected: Complex(q), ulps: 32) { XCTFail() } + if checkDivide(b, a, expected: Complex(q), ulps: 4) { XCTFail() } } } - */ #endif } From 3d6de9f3ef7db927dfa0c3d38c5363db02d69dae Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Thu, 16 May 2024 15:44:11 -0400 Subject: [PATCH 4/7] Reworked complex divide scaling. --- .../Complex+AlgebraicField.swift | 62 +++++++++++-------- Tests/ComplexTests/ArithmeticTests.swift | 6 +- 2 files changed, 41 insertions(+), 27 deletions(-) diff --git a/Sources/ComplexModule/Complex+AlgebraicField.swift b/Sources/ComplexModule/Complex+AlgebraicField.swift index 57452a4..e359a5e 100644 --- a/Sources/ComplexModule/Complex+AlgebraicField.swift +++ b/Sources/ComplexModule/Complex+AlgebraicField.swift @@ -42,13 +42,27 @@ extension Complex: AlgebraicField { return z * w.conjugate.divided(by: lenSq) } - @_alwaysEmitIntoClient // specialization - @inline(never) - public static func rescaledDivide(_ z: Complex, _ w: Complex) -> Complex { + @usableFromInline @_alwaysEmitIntoClient @inline(never) + internal static func rescaledDivide(_ z: Complex, _ w: Complex) -> Complex { if w.isZero { return .infinity } if !w.isFinite { return .zero } // Scaling algorithm adapted from Doug Priest's "Efficient Scaling for // Complex Division": + if w.magnitude < .leastNormalMagnitude { + // A difference from Priest's algorithm is that he didn't have to worry + // about types like Float16, where the significand width is comparable + // to the exponent range, such that |leastNormalMagnitude|^(-¾) isn't + // representable (e.g. for Float16 it would want to be 2¹⁸, but the + // largest allowed exponent is 15). Note that it's critical to use zʹ/wʹ + // after rescaling to avoid this, rather than falling through into the + // normal rescaling, because otherwise we might end up back in the + // situation where |w| ~ 1. + let s = 1/(RealType(RealType.radix) * .leastNormalMagnitude) + let wʹ = w.multiplied(by: s) + let zʹ = z.multiplied(by: s) + return zʹ / wʹ + } + // Having handled that case, we proceed pretty similarly to Priest: // // 1. Choose real scale s ~ |w|^(-¾), an exact power of the radix. // 2. wʹ ← sw @@ -80,28 +94,26 @@ extension Complex: AlgebraicField { // invariant compared to the mainline `/` implementation, up to the // underflow boundary. // - // Another difference from Priest's algorithm is that he didn't have - // to worry about types like Float16, where the significand width is - // comparable to the exponent range, such that |leastNormalMagnitude|^(-¾) - // isn't representable (e.g. for Float16 it would want to be 2¹⁸, while - // the largest allowed exponent is 15). Note that it's critical to - // use zʹ/wʹ after rescaling to avoid this, rather than falling through - // into the normal rescaling, because otherwise we might end up back in - // the situation where |w| ~ 1. - if w.magnitude < RealType.leastNormalMagnitude { - let wʹ = w.multiplied(by: 1/(2*RealType.leastNormalMagnitude)) - let zʹ = z.multiplied(by: 1/(2*RealType.leastNormalMagnitude)) - return zʹ/wʹ - } else { - let s = RealType( - sign: .plus, - exponent: -3*w.magnitude.exponent/4, - significand: 1 - ) - let wʹ = w.multiplied(by: s) - let zʹ = z.multiplied(by: s) - return zʹ * wʹ.conjugate.divided(by: wʹ.lengthSquared) - } + // Note that our final assembly of the result is different from Priest; + // he applies s to w twice, instead of once to w and once to z, and + // does the product as (zw̅ʺ)*1/|wʹ|², while we do zʹ(w̅ʹ/|wʹ|²). We + // prefer our version for three reasons: + // + // 1. it extracts a little more ILP + // 2. it makes it so that we get exactly the same roundings on the + // rescaled divide path as on the fast path, so that z/w = tz/tw + // when tz and tw are computed exactly. + // 3. it unlocks a future optimization where we hoist s and + // (w̅ʹ/|wʹ|²) and make divisions all fast-path without perturbing + // rouding. + let s = RealType( + sign: .plus, + exponent: -3*w.magnitude.exponent/4, + significand: 1 + ) + let wʹ = w.multiplied(by: s) + let zʹ = z.multiplied(by: s) + return zʹ * wʹ.conjugate.divided(by: wʹ.lengthSquared) } /// A normalized complex number with the same phase as this value. diff --git a/Tests/ComplexTests/ArithmeticTests.swift b/Tests/ComplexTests/ArithmeticTests.swift index 77ac681..e36a095 100644 --- a/Tests/ComplexTests/ArithmeticTests.swift +++ b/Tests/ComplexTests/ArithmeticTests.swift @@ -41,10 +41,11 @@ func checkMultiply( _ a: Complex, _ b: Complex, expected: Complex, ulps allowed: T ) -> Bool { let observed = a*b - let rel = relativeError(observed, expected) + if observed == expected { return false } // Even if the expected result is finite, we allow overflow if // the two-norm of the expected result overflows. if !observed.isFinite && !expected.length.isFinite { return false } + let rel = relativeError(observed, expected) guard rel <= allowed else { print("Over-large error in \(a)*\(b)") print("Expected: \(expected)\nObserved: \(observed)") @@ -58,10 +59,11 @@ func checkDivide( _ a: Complex, _ b: Complex, expected: Complex, ulps allowed: T ) -> Bool { let observed = a/b - let rel = relativeError(observed, expected) + if observed == expected { return false } // Even if the expected result is finite, we allow overflow if // the two-norm of the expected result overflows. if !observed.isFinite && !expected.length.isFinite { return false } + let rel = relativeError(observed, expected) guard rel <= allowed else { print("Over-large error in \(a)/\(b)") print("Expected: \(expected)\nObserved: \(observed)") From a883d95a4dc9ac4892349f64cfb462f1b56b58ae Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Thu, 16 May 2024 15:50:32 -0400 Subject: [PATCH 5/7] Fixup guard on Float16 Complex divide tests. --- Tests/ComplexTests/ArithmeticTests.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Tests/ComplexTests/ArithmeticTests.swift b/Tests/ComplexTests/ArithmeticTests.swift index e36a095..cbefc68 100644 --- a/Tests/ComplexTests/ArithmeticTests.swift +++ b/Tests/ComplexTests/ArithmeticTests.swift @@ -168,8 +168,10 @@ final class ArithmeticTests: XCTestCase { } func testPolar() { -#if (arch(arm64)) - testPolar(Float16.self) +#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64)) + if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) { + testPolar(Float16.self) + } #endif testPolar(Float.self) testPolar(Double.self) From 84c41a0befd6d45016fc9ce174e75bd987fab4bc Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Thu, 16 May 2024 19:46:17 -0400 Subject: [PATCH 6/7] Update Sources/ComplexModule/Complex+AlgebraicField.swift Co-authored-by: Guillaume Lessard --- Sources/ComplexModule/Complex+AlgebraicField.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/ComplexModule/Complex+AlgebraicField.swift b/Sources/ComplexModule/Complex+AlgebraicField.swift index e359a5e..c3f775b 100644 --- a/Sources/ComplexModule/Complex+AlgebraicField.swift +++ b/Sources/ComplexModule/Complex+AlgebraicField.swift @@ -105,7 +105,7 @@ extension Complex: AlgebraicField { // when tz and tw are computed exactly. // 3. it unlocks a future optimization where we hoist s and // (w̅ʹ/|wʹ|²) and make divisions all fast-path without perturbing - // rouding. + // rounding. let s = RealType( sign: .plus, exponent: -3*w.magnitude.exponent/4, From 262cbea1f25f4ede2f0eaaea0e3495e6e0d5f327 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Thu, 16 May 2024 22:12:24 -0400 Subject: [PATCH 7/7] review feedback. --- .../Complex+AlgebraicField.swift | 4 +- Tests/ComplexTests/ArithmeticTests.swift | 167 +++++++++--------- 2 files changed, 85 insertions(+), 86 deletions(-) diff --git a/Sources/ComplexModule/Complex+AlgebraicField.swift b/Sources/ComplexModule/Complex+AlgebraicField.swift index c3f775b..42e847a 100644 --- a/Sources/ComplexModule/Complex+AlgebraicField.swift +++ b/Sources/ComplexModule/Complex+AlgebraicField.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Numerics open source project // -// Copyright (c) 2019-2021 Apple Inc. and the Swift Numerics project authors +// Copyright (c) 2019-2024 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 @@ -96,7 +96,7 @@ extension Complex: AlgebraicField { // // Note that our final assembly of the result is different from Priest; // he applies s to w twice, instead of once to w and once to z, and - // does the product as (zw̅ʺ)*1/|wʹ|², while we do zʹ(w̅ʹ/|wʹ|²). We + // does the product as (zw̅ʺ)*(1/|wʹ|²), while we do zʹ(w̅ʹ/|wʹ|²). We // prefer our version for three reasons: // // 1. it extracts a little more ILP diff --git a/Tests/ComplexTests/ArithmeticTests.swift b/Tests/ComplexTests/ArithmeticTests.swift index cbefc68..fd76bd2 100644 --- a/Tests/ComplexTests/ArithmeticTests.swift +++ b/Tests/ComplexTests/ArithmeticTests.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Numerics open source project // -// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors +// Copyright (c) 2019-2024 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 @@ -83,92 +83,91 @@ final class ArithmeticTests: XCTestCase { func testPolar(_ type: T.Type) where T: BinaryFloatingPoint, T: Real, T.Exponent: FixedWidthInteger, T.RawSignificand: FixedWidthInteger { - - // In order to support round-tripping from rectangular to polar coordinate - // systems, as a special case phase can be non-finite when length is - // either zero or infinity. - XCTAssertEqual(Complex(length: .zero, phase: .infinity), .zero) - XCTAssertEqual(Complex(length: .zero, phase:-.infinity), .zero) - XCTAssertEqual(Complex(length: .zero, phase: .nan ), .zero) - XCTAssertEqual(Complex(length: .infinity, phase: .infinity), .infinity) - XCTAssertEqual(Complex(length: .infinity, phase:-.infinity), .infinity) - XCTAssertEqual(Complex(length: .infinity, phase: .nan ), .infinity) - XCTAssertEqual(Complex(length:-.infinity, phase: .infinity), .infinity) - XCTAssertEqual(Complex(length:-.infinity, phase:-.infinity), .infinity) - XCTAssertEqual(Complex(length:-.infinity, phase: .nan ), .infinity) - - let exponentRange = - T.leastNormalMagnitude.exponent ... T.greatestFiniteMagnitude.exponent - let inputs = (0..<100).map { _ in - Polar(length: T( - sign: .plus, - exponent: T.Exponent.random(in: exponentRange), - significand: T.random(in: 1 ..< 2) - ), phase: T.random(in: -.pi ... .pi)) - } - for p in inputs { - // first test that each value can round-trip between rectangular and - // polar coordinates with reasonable accuracy. We'll probably need to - // relax this for some platforms (currently we're using the default - // RNG, which means we don't get the same sequence of values each time; - // this is good--more test coverage!--and bad, because without tight - // bounds on every platform's libm, we can't get tight bounds on the - // accuracy of these operations, so we need to relax them gradually). - let z = Complex(length: p.length, phase: p.phase) - if !closeEnough(z.length, p.length, ulps: 16) { - print("p = \(p)\nz = \(z)\nz.length = \(z.length)") - XCTFail() - } - if !closeEnough(z.phase, p.phase, ulps: 16) { - print("p = \(p)\nz = \(z)\nz.phase = \(z.phase)") - XCTFail() - } - // Complex(length: -r, phase: θ) = -Complex(length: r, phase: θ). - let w = Complex(length: -p.length, phase: p.phase) - if w != -z { - print("p = \(p)\nw = \(w)\nz = \(z)") - XCTFail() - } - XCTAssertEqual(w, -z) - // if length*length is normal, it should be lengthSquared, up - // to small error. - if (p.length*p.length).isNormal { - if !closeEnough(z.lengthSquared, p.length*p.length, ulps: 16) { - print("p = \(p)\nz = \(z)\nz.lengthSquared = \(z.lengthSquared)") - XCTFail() - } - } - // Test reciprocal and normalized: - let r = Complex(length: 1/p.length, phase: -p.phase) - if r.isNormal { - if relativeError(r, z.reciprocal!) > 16 { - print("p = \(p)\nz = \(z)\nz.reciprocal = \(r)") - XCTFail() - } - } else { XCTAssertNil(z.reciprocal) } - let n = Complex(length: 1, phase: p.phase) - if relativeError(n, z.normalized!) > 16 { - print("p = \(p)\nz = \(z)\nz.normalized = \(n)") - XCTFail() - } - - // Now test multiplication and division using the polar inputs: - for q in inputs { - let w = Complex(length: q.length, phase: q.phase) - var product = Complex(length: p.length, phase: p.phase + q.phase) - product.real *= q.length - product.imaginary *= q.length - if checkMultiply(z, w, expected: product, ulps: 16) { XCTFail() } - var quotient = Complex(length: p.length, phase: p.phase - q.phase) - quotient.real /= q.length - quotient.imaginary /= q.length - if checkDivide(z, w, expected: quotient, ulps: 16) { XCTFail() } - } - } + // In order to support round-tripping from rectangular to polar coordinate + // systems, as a special case phase can be non-finite when length is + // either zero or infinity. + XCTAssertEqual(Complex(length: .zero, phase: .infinity), .zero) + XCTAssertEqual(Complex(length: .zero, phase:-.infinity), .zero) + XCTAssertEqual(Complex(length: .zero, phase: .nan ), .zero) + XCTAssertEqual(Complex(length: .infinity, phase: .infinity), .infinity) + XCTAssertEqual(Complex(length: .infinity, phase:-.infinity), .infinity) + XCTAssertEqual(Complex(length: .infinity, phase: .nan ), .infinity) + XCTAssertEqual(Complex(length:-.infinity, phase: .infinity), .infinity) + XCTAssertEqual(Complex(length:-.infinity, phase:-.infinity), .infinity) + XCTAssertEqual(Complex(length:-.infinity, phase: .nan ), .infinity) + + let exponentRange = + T.leastNormalMagnitude.exponent ... T.greatestFiniteMagnitude.exponent + let inputs = (0..<100).map { _ in + Polar(length: T( + sign: .plus, + exponent: T.Exponent.random(in: exponentRange), + significand: T.random(in: 1 ..< 2) + ), phase: T.random(in: -.pi ... .pi)) + } + for p in inputs { + // first test that each value can round-trip between rectangular and + // polar coordinates with reasonable accuracy. We'll probably need to + // relax this for some platforms (currently we're using the default + // RNG, which means we don't get the same sequence of values each time; + // this is good--more test coverage!--and bad, because without tight + // bounds on every platform's libm, we can't get tight bounds on the + // accuracy of these operations, so we need to relax them gradually). + let z = Complex(length: p.length, phase: p.phase) + if !closeEnough(z.length, p.length, ulps: 16) { + print("p = \(p)\nz = \(z)\nz.length = \(z.length)") + XCTFail() + } + if !closeEnough(z.phase, p.phase, ulps: 16) { + print("p = \(p)\nz = \(z)\nz.phase = \(z.phase)") + XCTFail() + } + // Complex(length: -r, phase: θ) = -Complex(length: r, phase: θ). + let w = Complex(length: -p.length, phase: p.phase) + if w != -z { + print("p = \(p)\nw = \(w)\nz = \(z)") + XCTFail() + } + XCTAssertEqual(w, -z) + // if length*length is normal, it should be lengthSquared, up + // to small error. + if (p.length*p.length).isNormal { + if !closeEnough(z.lengthSquared, p.length*p.length, ulps: 16) { + print("p = \(p)\nz = \(z)\nz.lengthSquared = \(z.lengthSquared)") + XCTFail() } + } + // Test reciprocal and normalized: + let r = Complex(length: 1/p.length, phase: -p.phase) + if r.isNormal { + if relativeError(r, z.reciprocal!) > 16 { + print("p = \(p)\nz = \(z)\nz.reciprocal = \(r)") + XCTFail() + } + } else { XCTAssertNil(z.reciprocal) } + let n = Complex(length: 1, phase: p.phase) + if relativeError(n, z.normalized!) > 16 { + print("p = \(p)\nz = \(z)\nz.normalized = \(n)") + XCTFail() + } + + // Now test multiplication and division using the polar inputs: + for q in inputs { + let w = Complex(length: q.length, phase: q.phase) + var product = Complex(length: p.length, phase: p.phase + q.phase) + product.real *= q.length + product.imaginary *= q.length + if checkMultiply(z, w, expected: product, ulps: 16) { XCTFail() } + var quotient = Complex(length: p.length, phase: p.phase - q.phase) + quotient.real /= q.length + quotient.imaginary /= q.length + if checkDivide(z, w, expected: quotient, ulps: 16) { XCTFail() } + } + } + } func testPolar() { -#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64)) +#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64)) && LONG_TESTS if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) { testPolar(Float16.self) }