7 Commits
Author SHA1 Message Date
Stephen Canon 2b63fc844e Merge pull request #78 from stephentyrone/lengthSquared
Rename unsafeLengthSquared -> lengthSquared
2019-11-20 16:27:40 -05:00
Stephen Canon f6c2c34910 Rename unsafeLengthSquared -> lengthSquared
Also further tweak polar init for Complex to allow (-infinity, θ) when θ is not finite.
2019-11-20 16:15:10 -05:00
Stephen Canon f1d78c4d98 Merge pull request #77 from stephentyrone/zero-length-polar-init
Address behavior of Complex.init(length:phase:)
2019-11-20 16:03:09 -05:00
Stephen CanonandRichard Wei 5931d036ab Update Sources/Complex/Complex.swift
Co-Authored-By: Richard Wei <rxrwei@gmail.com>
2019-11-20 14:56:31 -05:00
Stephen Canon 565839d673 Address behavior of Complex.init(length:phase:)
Instead of being failable, adopt the following policy:
- If length is zero or infinity, the phase does not matter.
- Otherwise, the phase must be finite or a precondition failure occurs.

Discussion here: https://github.com/apple/swift-numerics/issues/51
2019-11-20 14:32:19 -05:00
Stephen Canon f96c6c2066 Rename swift.yml to macos.yml 2019-11-18 16:34:11 -05:00
Stephen Canon ee54cc2075 Let's tryout workflows 2019-11-13 17:17:32 -05:00
5 changed files with 84 additions and 32 deletions

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
name: Swift
on: [push]
jobs:
build:
runs-on: macOS-latest
steps:
- uses: actions/checkout@v1
- name: Build
run: swift build -v
- name: Run tests
run: swift test -v -c release
+4 -4
View File
@@ -73,9 +73,9 @@ extension Complex: Numeric {
// 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.
let lengthSquared = w.unsafeLengthSquared
guard lengthSquared.isNormal else { return rescaledDivide(z, w) }
return z * (w.conjugate.divided(by: lengthSquared))
let lenSq = w.lengthSquared
guard lenSq.isNormal else { return rescaledDivide(z, w) }
return z * (w.conjugate.divided(by: lenSq))
}
@_transparent
@@ -98,7 +98,7 @@ extension Complex: Numeric {
let wScale = w.magnitude
let zNorm = z.divided(by: zScale)
let wNorm = w.divided(by: wScale)
let r = (zNorm * wNorm.conjugate).divided(by: wNorm.unsafeLengthSquared)
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
+33 -17
View File
@@ -208,7 +208,7 @@ extension Complex {
/// The ∞-norm of the value (`max(abs(real), abs(imaginary))`).
///
/// If you need the euclidean norm (a.k.a. 2-norm) use the `length` or `unsafeLengthSquared`
/// If you need the euclidean norm (a.k.a. 2-norm) use the `length` or `lengthSquared`
/// properties instead.
///
/// Edge cases:
@@ -220,7 +220,7 @@ extension Complex {
/// See also:
/// -
/// - `.length`
/// - `.unsafeLengthSquared`
/// - `.lengthSquared`
@_transparent
public var magnitude: RealType {
guard isFinite else { return .infinity }
@@ -394,13 +394,13 @@ extension Complex {
/// See also:
/// -
/// - `.magnitude`
/// - `.unsafeLengthSquared`
/// - `.lengthSquared`
/// - `.phase`
/// - `.polar`
/// - `init(r:θ:)`
@_transparent
public var length: RealType {
let naive = unsafeLengthSquared
let naive = lengthSquared
guard naive.isNormal else { return carefulLength }
return .sqrt(naive)
}
@@ -419,7 +419,7 @@ extension Complex {
///
/// This property is more efficient to compute than `length`, but is
/// highly prone to overflow or underflow; for finite values that are
/// not well-scaled, `unsafeLengthSquared` is often either zero or
/// not well-scaled, `lengthSquared` is often either zero or
/// infinity, even when `length` is a finite number. Use this property
/// only when you are certain that this value is well-scaled.
///
@@ -431,10 +431,13 @@ extension Complex {
/// - `.length`
/// - `.magnitude`
@_transparent
public var unsafeLengthSquared: RealType {
public var lengthSquared: RealType {
x*x + y*y
}
@available(*, unavailable, renamed: "lengthSquared")
public var unsafeLengthSquared: RealType { lengthSquared }
/// The phase (angle, or "argument").
///
/// Returns the angle (measured above the real axis) in radians. If
@@ -472,26 +475,39 @@ extension Complex {
(length, phase)
}
/// Constructs a complex value from polar coordinates.
/// Creates a complex value specified with polar coordinates.
///
/// Edge cases:
/// -
/// If the phase is non-finite, but length is finite, this initializer
/// fails and returns nil. In all other cases, a non-nil value is constructed.
/// - Negative lengths are interpreted as reflecting the point through the origin, i.e.:
/// ```
/// Complex(length: -r, phase: θ) == -Complex(length: r, phase: θ)
/// ```
/// - For any `θ`, even `.infinity` or `.nan`:
/// ```
/// Complex(length: .zero, phase: θ) == .zero
/// ```
/// - For any `θ`, even `.infinity` or `.nan`, if `r` is infinite then:
/// ```
/// Complex(length: r, phase: θ) == .infinity
/// ```
/// - Otherwise, `θ` must be finite, or a precondition failure occurs.
///
/// See also:
/// -
/// - `.length`
/// - `.phase`
/// - `.polar`
public init?(length: RealType, phase: RealType) {
guard phase.isFinite else {
// There's no way to make sense of finite magnitude and non-finite phase.
if length.isFinite { return nil }
// r is infinite so phase doesn't matter.
self = .infinity
return
@inlinable
public init(length: RealType, phase: RealType) {
if phase.isFinite {
self = Complex(.cos(phase), .sin(phase)).multiplied(by: length)
} else {
precondition(
length.isZero || length.isInfinite,
"Either phase must be finite, or length must be zero or infinite."
)
self = Complex(length)
}
self.init(length * .cos(phase), length * .sin(phase))
}
}
@@ -28,7 +28,7 @@ extension Complex where RealType == Double {
let wellScaledDoubles: [Complex<Double>] = (0 ..< 1024).map { _ in
Complex(length: Double.random(in: 0.5 ..< 2.0),
phase: Double.random(in: -.pi ..< .pi))!
phase: Double.random(in: -.pi ..< .pi))
}
let poorlyScaledDoubles: [Complex<Double>] = (0 ..< 1024).map { _ in
@@ -37,7 +37,7 @@ let poorlyScaledDoubles: [Complex<Double>] = (0 ..< 1024).map { _ in
exponent: .random(in: -970 ... 1023),
significand: .random(in: 1 ..< 2)),
phase: Double.random(in: -.pi ..< .pi)
)!
)
}
final class ArithmeticBenchmarkTests: XCTestCase {
+30 -9
View File
@@ -63,6 +63,20 @@ final class ArithmeticTests: XCTestCase {
func testPolar<T>(_ 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<T>(length: .zero, phase: .infinity), .zero)
XCTAssertEqual(Complex<T>(length: .zero, phase:-.infinity), .zero)
XCTAssertEqual(Complex<T>(length: .zero, phase: .nan ), .zero)
XCTAssertEqual(Complex<T>(length: .infinity, phase: .infinity), .infinity)
XCTAssertEqual(Complex<T>(length: .infinity, phase:-.infinity), .infinity)
XCTAssertEqual(Complex<T>(length: .infinity, phase: .nan ), .infinity)
XCTAssertEqual(Complex<T>(length:-.infinity, phase: .infinity), .infinity)
XCTAssertEqual(Complex<T>(length:-.infinity, phase:-.infinity), .infinity)
XCTAssertEqual(Complex<T>(length:-.infinity, phase: .nan ), .infinity)
let exponentRange =
(T.leastNormalMagnitude.exponent + T.Exponent(T.significandBitCount)) ...
T.greatestFiniteMagnitude.exponent
@@ -81,7 +95,7 @@ final class ArithmeticTests: XCTestCase {
// 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)!
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()
@@ -90,23 +104,30 @@ final class ArithmeticTests: XCTestCase {
print("p = \(p)\nz = \(z)\nz.phase = \(z.phase)")
XCTFail()
}
// if length*length is normal, it should be unsafeLengthSquared, up
// 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.unsafeLengthSquared, p.length*p.length, ulps: 16) {
print("p = \(p)\nz = \(z)\nz.unsafeLengthSquared = \(z.unsafeLengthSquared)")
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)!
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)!
let n = Complex(length: 1, phase: p.phase)
if relativeError(n, z.normalized!) > 16 {
print("p = \(p)\nz = \(z)\nz.normalized = \(n)")
XCTFail()
@@ -114,10 +135,10 @@ final class ArithmeticTests: XCTestCase {
// 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)!
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)!
let quotient = Complex(length: p.length / q.length, phase: p.phase - q.phase)
if checkDivide(z, w, expected: quotient, ulps: 16) { XCTFail() }
}
}