Author SHA1 Message Date
Stephen Canon 876f439c4a Merge pull request #309 from stephentyrone/actions-1.0 2025-05-28 19:30:04 -04:00
Stephen Canon 96df03d007 Merge pull request #280 from MaxDesiatov/patch-1
Remove unused `LinuxMain.swift` and `WindowsMain.swift`
2025-05-28 16:19:24 -04:00
Stephen Canon f412cea212 Manual cherry-pick of Add support for GitHub Actions #301 from main. 2025-05-28 15:55:17 -04:00
Stephen Canon 8b28aba874 Cherry-pick "Add extern "C" to shim header file" #307 to 1.0.x 2025-05-28 15:44:01 -04:00
Stephen Canon e29c31deb4 Fix-up availability for Float16 in tests for tvOS and watchOS. 2025-03-04 15:39:32 -05:00
Stephen Canon e0ec0f5f3a Cherry-pick pow edge case fixes from main. 2025-03-03 11:13:12 -05:00
Stephen Canon aa76ee5658 Link the system math library explicitly when building for Android and Linux 2025-02-25 15:17:29 -05:00
Stephen Canon d42ab140f7 Merge pull request #299 from stephentyrone/sendable-minimum-swift
Restrict sendable conformance for Complex to 5.5 and higher.
2025-02-20 17:40:06 -05:00
Stephen Canon 77b98fab75 Merge branch 'release/1.0' into sendable-minimum-swift 2025-02-20 17:39:57 -05:00
Stephen Canon ba43341621 Add explicit import of RealModule to support Swift 6. 2025-02-20 17:39:20 -05:00
Stephen Canon 6a3ecdb480 Restrict sendable conformance for Complex to 5.5 and higher. 2025-02-20 17:26:04 -05:00
Stephen Canon 803aae1ef0 Conditionally conform Complex to Sendable. 2025-02-20 16:59:36 -05:00
Stephen Canon db4ef5686a Merge pull request #270 from stephentyrone/fix-tvOS-availability-1.0
Correct tvOS availability for Float16 in _TestSupport.
2023-09-28 14:55:25 -04:00
Stephen Canon a85dd8c2bb Correct tvOS availability for Float16 in _TestSupport. 2023-09-20 09:59:46 -04:00
Stephen Canon 0a5bc04095 Merge pull request #215 from stephentyrone/arm64-mac-cmake-1.0
add arm64 support for M1 Mac
2021-11-18 09:21:09 -05:00
bob a6bea6639c add arm64 support for M1 Mac 2021-11-18 09:18:40 -05:00
Stephen Canon 0a23770641 Merge pull request #198 from stephentyrone/clarify-stability-differentiable
Clarify that differentaible API is not stable.
2021-08-31 16:29:00 -04:00
Stephen Canon d560765047 Clarify that differentaible API is not stable. 2021-08-31 16:26:17 -04:00
Stephen Canon 1e5cbc4e21 Merge pull request #195 from stephentyrone/readme-semver-1.0
Update README for 1.0.0.
2021-08-31 11:34:42 -04:00
Stephen Canon b4ec7556e9 Update README for 1.0.0. 2021-08-31 11:31:30 -04:00
Stephen Canon 79f6025798 Merge pull request #193 from stephentyrone/cherry-pick-doc-changes-from-main
Cherry pick doc changes from main
2021-08-27 09:38:44 -04:00
Stephen Canon 03c5840722 Merge pull request #194 from stephentyrone/source-stability-api
Add notes about what the public API is.
2021-08-27 09:38:19 -04:00
Stephen Canon ed66862a2c Add notes about what the public API is. 2021-08-27 09:36:56 -04:00
Stephen Canon bcde4bc513 Comment cleanups. 2021-08-27 09:25:57 -04:00
Stephen Canon 58f95289a0 Merge pull request #185 from stephentyrone/reciprocal-documentation
Further expand documentation of `reciprocal` with some example use.
2021-08-27 09:09:21 -04:00
Stephen Canon 832dac1ef8 Merge pull request #184 from stephentyrone/document-real-reciprocal-1.0
Merge pull request #182 from stephentyrone/more-documentation-for-1.0
2021-08-19 19:41:47 -04:00
Stephen Canon 419caa222f Merge pull request #182 from stephentyrone/more-documentation-for-1.0
Add some documentation for AlgebraicField ops, minor fix for Augmented.
2021-08-19 19:38:54 -04:00
Stephen Canon 5a0aedbccd Merge pull request #183 from stephentyrone/deprecations-for-1.0
Add deprecation warnings for old Augmented names in release/1.0
2021-08-19 19:38:17 -04:00
Stephen Canon 8e3d889b5f Add deprecation warnings for old Augmented names in release/1.0 2021-08-19 19:35:06 -04:00
Stephen Canon 92f0095962 Document the Augmented enum in RealModule in advance of 1.0 2021-08-19 14:08:22 -04:00
68 changed files with 1598 additions and 3330 deletions

No files matched your search

-8
View File
@@ -1,8 +1,5 @@
name: Pull request
permissions:
contents: read
on:
pull_request:
types: [opened, reopened, synchronize]
@@ -11,11 +8,6 @@ jobs:
tests:
name: Test
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
with:
enable_macos_checks: true
windows_exclude_swift_versions: '[{"swift_version": "5.9"}]'
enable_wasm_sdk_build: true
wasm_sdk_build_command: swift build --target Numerics
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
-4
View File
@@ -1,4 +0,0 @@
version: 1
builder:
configs:
- documentation_targets: [Numerics, RealModule, ComplexModule]
+1 -1
View File
@@ -11,7 +11,7 @@ cmake_minimum_required(VERSION 3.16)
project(swift-numerics
LANGUAGES Swift)
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/modules)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
+14 -40
View File
@@ -1,9 +1,9 @@
// swift-tools-version:5.9
// swift-tools-version:5.2
//===--- Package.swift ----------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
// 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
@@ -12,8 +12,6 @@
import PackageDescription
let excludedFilenames = ["CMakeLists.txt", "README.md"]
let package = Package(
name: "swift-numerics",
@@ -24,51 +22,27 @@ let package = Package(
],
targets: [
// MARK: - Public API
.target(
name: "ComplexModule",
dependencies: ["RealModule"],
exclude: excludedFilenames
),
.target(
name: "Numerics",
dependencies: ["ComplexModule", "RealModule"],
exclude: excludedFilenames
),
// User-facing modules
.target(name: "ComplexModule", dependencies: ["RealModule"]),
.target(name: "Numerics", dependencies: ["ComplexModule", "RealModule"]),
.target(
name: "RealModule",
dependencies: ["_NumericsShims"],
exclude: excludedFilenames,
linkerSettings: [
.linkedLibrary("m", .when(platforms: [.linux, .android]))
]
),
// MARK: - Implementation details
.target(
name: "_NumericsShims",
exclude: excludedFilenames
),
// Implementation details
.target(name: "_NumericsShims", dependencies: []),
.target(name: "_TestSupport", dependencies: ["Numerics"]),
.target(
name: "_TestSupport",
dependencies: ["Numerics"],
exclude: ["CMakeLists.txt"]
),
// Unit test bundles
.testTarget(name: "ComplexTests", dependencies: ["_TestSupport"]),
.testTarget(name: "RealTests", dependencies: ["_TestSupport"]),
// MARK: - Unit test bundles
.testTarget(
name: "ComplexTests",
dependencies: ["_TestSupport"],
exclude: ["CMakeLists.txt"]
),
.testTarget(
name: "RealTests",
dependencies: ["_TestSupport"],
exclude: ["CMakeLists.txt"]
)
// Test executables
.target(name: "ComplexLog", dependencies: ["Numerics", "_TestSupport"], path: "Tests/Executable/ComplexLog"),
.target(name: "ComplexLog1p", dependencies: ["Numerics", "_TestSupport"], path: "Tests/Executable/ComplexLog1p")
]
)
+46
View File
@@ -0,0 +1,46 @@
// swift-tools-version:5.0
//===--- Package@swift-5.0.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 PackageDescription
let package = Package(
name: "swift-numerics",
products: [
.library(name: "ComplexModule", targets: ["ComplexModule"]),
.library(name: "Numerics", targets: ["Numerics"]),
.library(name: "RealModule", targets: ["RealModule"]),
],
targets: [
// User-facing modules
.target(name: "ComplexModule", dependencies: ["RealModule"]),
.target(name: "Numerics", dependencies: ["ComplexModule", "RealModule"]),
.target(
name: "RealModule",
dependencies: ["_NumericsShims"],
linkerSettings: [ .linkedLibrary("m", .when(platforms: [.linux])) ]
),
// Implementation details
.target(name: "_NumericsShims", dependencies: []),
.target(name: "_TestSupport", dependencies: ["Numerics"]),
// Unit test bundles
.testTarget(name: "ComplexTests", dependencies: ["_TestSupport"]),
.testTarget(name: "RealTests", dependencies: ["_TestSupport"]),
// Test executables
.target(name: "ComplexLog", dependencies: ["Numerics", "_TestSupport"], path: "Tests/Executable/ComplexLog"),
.target(name: "ComplexLog1p", dependencies: ["Numerics", "_TestSupport"], path: "Tests/Executable/ComplexLog1p")
]
)
+26 -24
View File
@@ -11,7 +11,7 @@ These modules fall broadly into two categories:
There is some overlap between these two categories, and an API that begins in the first category may migrate into the second as it matures and new uses are discovered.
Swift Numerics modules are fine-grained.
For example, if you need support for Complex numbers, you can import ComplexModule[^1] as a standalone module:
For example, if you need support for Complex numbers, you can import ComplexModule¹ as a standalone module:
```swift
import ComplexModule
@@ -42,7 +42,7 @@ To use Swift Numerics in a SwiftPM project:
1. Add the following line to the dependencies in your `Package.swift` file:
```swift
.package(url: "https://github.com/apple/swift-numerics", from: "1.1.0"),
.package(url: "https://github.com/apple/swift-numerics", from: "1.0.0"),
```
2. Add `Numerics` as a dependency for your target:
@@ -59,7 +59,7 @@ To use Swift Numerics in a SwiftPM project:
## Source stability
The Swift Numerics package is source stable; version numbers follow [Semantic Versioning](https://semver.org).
The public API of the `swift-numerics` package consists of non-underscored declarations that are marked either `public` or `usableFromInline` in modules re-exported by the top-level `Numerics` module.
The public API of the `swift-numerics` package consists of non-underscored declarations that are marked either `public` or `usableFromInline` in modules re-exported by the top-level `Numerics` module, *excepting any API that involves a conformance to Differentiable (because Differentiable itself is not stable in Swift)*.
Interfaces that aren't part of the public API may continue to change in any release, including patch releases.
Note that contents of the `_NumericsShims` and `_TestSupport` modules, as well as contents of the `Tests` directory, explicitly are not public API.
@@ -113,26 +113,28 @@ Questions about how to use Swift Numerics modules, or issues that are not clearl
3. [Shaped Arrays](https://github.com/apple/swift-numerics/issues/6)
4. [Decimal Floating-point](https://github.com/apple/swift-numerics/issues/7)
[^1]: The module is named `ComplexModule` instead of `Complex` because 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 such as:
## Notes
```swift
import Complex
// I know I only ever want Complex<Double>, so I shouldn't need the generic parameter.
typealias Complex = Complex.Complex<Double> // This doesn't work, because name lookup fails.
```
For this reason, modules that would have this ambiguity are suffixed with `Module` within Swift Numerics:
```swift
import ComplexModule
// I know I only ever want Complex<Double>, so I shouldn't need the generic parameter.
typealias Complex = ComplexModule.Complex<Double>
// But I can still refer to the generic type by qualifying the name if I need it occasionally:
let a = ComplexModule.Complex<Float>
```
¹ 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 such as:
The `Real` module does not contain a `Real` type, but does contain a `Real` protocol.
Users may want to define their own `Real` type (and possibly re-export the `Real` module)--that is why the suffix is also applied there.
New modules have to evaluate this decision carefully, but can err on the side of adding the suffix.
It's expected that most users will simply `import Numerics`, so this isn't an issue for them.
```swift
import Complex
// I know I only ever want Complex<Double>, so I shouldn't need the generic parameter.
typealias Complex = Complex.Complex<Double> // This doesn't work, because name lookup fails.
```
For this reason, modules that would have this ambiguity are suffixed with `Module` within Swift Numerics:
```swift
import ComplexModule
// I know I only ever want Complex<Double>, so I shouldn't need the generic parameter.
typealias Complex = ComplexModule.Complex<Double>
// But I can still refer to the generic type by qualifying the name if I need it occasionally:
let a = ComplexModule.Complex<Float>
```
The `Real` module does not contain a `Real` type, but does contain a `Real` protocol.
Users may want to define their own `Real` type (and possibly re-export the `Real` module)--that is why the suffix is also applied there.
New modules have to evaluate this decision carefully, but can err on the side of adding the suffix.
It's expected that most users will simply `import Numerics`, so this isn't an issue for them.
+1 -1
View File
@@ -1,7 +1,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 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
+193
View File
@@ -0,0 +1,193 @@
//===--- Arithmetic.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 RealModule
// MARK: - Additive structure
extension Complex: AdditiveArithmetic {
@_transparent
public static func +(z: Complex, w: Complex) -> Complex {
return Complex(z.x + w.x, z.y + w.y)
}
@_transparent
public static func -(z: Complex, w: Complex) -> Complex {
return Complex(z.x - w.x, z.y - w.y)
}
@_transparent
public static func +=(z: inout Complex, w: Complex) {
z = z + w
}
@_transparent
public static func -=(z: inout Complex, w: Complex) {
z = z - w
}
}
// MARK: - Vector space structure
//
// Policy: deliberately not using the * and / operators for these at the
// moment, because then there's an ambiguity in expressions like 2*z; is
// that Complex(2) * z or is it RealType(2) * z? This is especially
// problematic in type inference: suppose we have:
//
// let a: RealType = 1
// let b = 2*a
//
// what is the type of b? If we don't have a type context, it's ambiguous.
// If we have a Complex type context, then b will be inferred to have type
// Complex! Obviously, that doesn't help anyone.
//
// TODO: figure out if there's some way to avoid these surprising results
// and turn these into operators if/when we have it.
// (https://github.com/apple/swift-numerics/issues/12)
extension Complex {
/// `self` scaled by `a`.
@usableFromInline @_transparent
internal func multiplied(by a: RealType) -> Complex {
// This can be viewed in two different ways, which are mathematically
// equivalent: either we are computing `self * Complex(a)` (i.e.
// converting `a` to be a complex value, and then using the complex
// multiplication) or we are using the scalar product of the vector
// space structure: `Complex(a*real, a*imaginary)`.
//
// Although these two interpretations are _mathematically_ equivalent,
// they will generate different representations of the point at
// infinity in general. For example, suppose `self` is represented by
// `(infinity, 0)`. Then `self * Complex(1)` would evaluate as
// `(1*infinity - 0*0, 0*infinity + 1*0) = (infinity, nan)`, but
// the vector space interpretation produces `(infinity, 0)`. This does
// not matter much, because these are two representations of the same
// semantic value, but note that one requires four multiplies and two
// additions, while the one we use requires only two real multiplications.
Complex(x*a, y*a)
}
/// `self` unscaled by `a`.
@usableFromInline @_transparent
internal func divided(by a: RealType) -> Complex {
// See implementation notes for `multiplied` above.
Complex(x/a, y/a)
}
}
// MARK: - Multiplicative structure
extension Complex: AlgebraicField {
@_transparent
public static func *(z: Complex, w: Complex) -> Complex {
return Complex(z.x*w.x - z.y*w.y, z.x*w.y + z.y*w.x)
}
@_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.
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
}
@_transparent
public static func /=(z: inout Complex, w: Complex) {
z = z / w
}
@usableFromInline @_alwaysEmitIntoClient @inline(never)
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:
//
// - r * (zScale / wScale)
// - (r * zScale) / wScale
// - (r / wScale) * zScale
//
// The simplest case is when zScale / wScale is normal:
if (zScale / wScale).isNormal {
return r.multiplied(by: zScale / wScale)
}
// 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)
}
/// A normalized complex number with the same phase as this value.
///
/// If such a value cannot be produced (because the phase of zero and
/// infinity is undefined), `nil` is returned.
@inlinable
public var normalized: Complex? {
if length.isNormal {
return self.divided(by: length)
}
if isZero || !isFinite {
return nil
}
return self.divided(by: magnitude).normalized
}
/// The reciprocal of this value, if it can be computed without undue
/// overflow or underflow.
///
/// If z.reciprocal is non-nil, you can safely replace division by z with
/// multiplication by this value. It is not advantageous to do this for an
/// isolated division, but if you are dividing many values by a single
/// denominator, this may sometimes be a significant performance win.
///
/// A typical use case looks something like this:
/// ```
/// func divide<T: Real>(data: [Complex<T>], by divisor: Complex<T>) -> [Complex<T>] {
/// // If divisor is well-scaled, multiply by reciprocal.
/// if let recip = divisor.reciprocal {
/// return data.map { $0 * recip }
/// }
/// // Fallback on using division.
/// return data.map { $0 / divisor }
/// }
/// ```
///
/// Error Bounds:
///
/// Unlike real types, when working with complex types, multiplying by the
/// reciprocal instead of dividing cannot change the result. If the
/// reciprocal is non-nil, the two computations are always equivalent.
@inlinable
public var reciprocal: Complex? {
let recip = 1/self
if recip.isNormal || isZero || !isFinite {
return recip
}
return nil
}
}
+3 -10
View File
@@ -8,17 +8,10 @@ See https://swift.org/LICENSE.txt for license information
#]]
add_library(ComplexModule
Arithmetic.swift
Complex.swift
Complex+AdditiveArithmetic.swift
Complex+AlgebraicField.swift
Complex+Codable.swift
Complex+ElementaryFunctions.swift
Complex+Hashable.swift
Complex+IntegerLiteral.swift
Complex+Numeric.swift
Complex+StringConvertible.swift
Polar.swift
Scale.swift)
Differentiable.swift
ElementaryFunctions.swift)
set_target_properties(ComplexModule PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
target_link_libraries(ComplexModule PUBLIC
@@ -1,42 +0,0 @@
//===--- Complex+AdditiveArithmetic.swift ---------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 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 RealModule
extension Complex: AdditiveArithmetic {
/// The additive identity, with real and imaginary parts both zero.
///
/// See also: ``one``, ``i``, ``infinity``
@_transparent
public static var zero: Complex {
Complex(0, 0)
}
@_transparent
public static func +(z: Complex, w: Complex) -> Complex {
return Complex(z.x + w.x, z.y + w.y)
}
@_transparent
public static func -(z: Complex, w: Complex) -> Complex {
return Complex(z.x - w.x, z.y - w.y)
}
@_transparent
public static func +=(z: inout Complex, w: Complex) {
z = z + w
}
@_transparent
public static func -=(z: inout Complex, w: Complex) {
z = z - w
}
}
@@ -1,190 +0,0 @@
//===--- Complex+AlgebraicField.swift -------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 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 RealModule
extension Complex: AlgebraicField {
/// The multiplicative identity `1 + 0i`.
///
/// See also: ``zero``, ``i``, ``infinity``
@_transparent
public static var one: Complex {
Complex(1, 0)
}
/// The [complex conjugate][conj] of this value.
///
/// [conj]: https://en.wikipedia.org/wiki/Complex_conjugate
@_transparent
public var conjugate: Complex {
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 (see below).
let lenSq = w.lengthSquared
guard lenSq.isNormal else { return rescaledDivide(z, w) }
return z * w.conjugate.divided(by: lenSq)
}
@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
// 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:
//
// - 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),
// 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 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
// rounding.
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.
///
/// If such a value cannot be produced (because the phase of zero and
/// infinity is undefined), `nil` is returned.
@inlinable
public var normalized: Complex? {
if length.isNormal {
return self.divided(by: length)
}
if isZero || !isFinite {
return nil
}
return self.divided(by: magnitude).normalized
}
/// The reciprocal of this value, if it can be computed without undue
/// overflow or underflow.
///
/// If z.reciprocal is non-nil, you can safely replace division by z with
/// multiplication by this value. It is not advantageous to do this for an
/// isolated division, but if you are dividing many values by a single
/// denominator, this will often be a significant performance win.
///
/// A typical use case looks something like this:
/// ```
/// func divide<T: Real>(data: [Complex<T>], by divisor: Complex<T>) -> [Complex<T>] {
/// // If divisor is well-scaled, multiply by reciprocal.
/// if let recip = divisor.reciprocal {
/// return data.map { $0 * recip }
/// }
/// // Fallback on using division.
/// return data.map { $0 / divisor }
/// }
/// ```
///
/// Error Bounds:
///
/// Unlike real types, with Complex types, _if no underflow occurs in
/// computing the reciprocal_, replacing division with multiplication by
/// this value does not perturb the result. Note that this condition is
/// not the same as `reciprocal` returning a non-nil value. If the `real`
/// and `imaginary` components are poorly scaled with respect to each other,
/// one component of `reciprocal` may underflow while the other component
/// is normal, resulting in a non-nil `reciprocal`.
///
/// We return a non-nil reciprocal in this case because it still
/// satisfies the accuracy expectations of `reciprocal` in any Complex
/// norm (but not componentwise).
@inlinable
public var reciprocal: Complex? {
let recip = 1/self
if recip.isNormal || isZero || !isFinite {
return recip
}
return nil
}
@_transparent
public static func _relaxedAdd(_ a: Self, _ b: Self) -> Self {
Complex(Relaxed.sum(a.x, b.x), Relaxed.sum(a.y, b.y))
}
@_transparent
public static func _relaxedMul(_ a: Self, _ b: Self) -> Self {
Complex(
Relaxed.sum(Relaxed.product(a.x, b.x), -Relaxed.product(a.y, b.y)),
Relaxed.sum(Relaxed.product(a.x, b.y), Relaxed.product(a.y, b.x))
)
}
}
@@ -1,36 +0,0 @@
//===--- Complex+Codable.swift --------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 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 RealModule
// FloatingPoint does not refine Codable, so this is a conditional conformance.
#if compiler(>=6.0)
@_unavailableInEmbedded
#endif
extension Complex: Decodable where RealType: Decodable {
public init(from decoder: Decoder) throws {
var unkeyedContainer = try decoder.unkeyedContainer()
let x = try unkeyedContainer.decode(RealType.self)
let y = try unkeyedContainer.decode(RealType.self)
self.init(x, y)
}
}
#if compiler(>=6.0)
@_unavailableInEmbedded
#endif
extension Complex: Encodable where RealType: Encodable {
public func encode(to encoder: Encoder) throws {
var unkeyedContainer = encoder.unkeyedContainer()
try unkeyedContainer.encode(x)
try unkeyedContainer.encode(y)
}
}
@@ -1,42 +0,0 @@
//===--- Complex+Hashable.swift -------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 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 RealModule
extension Complex: Hashable {
@_transparent
public static func ==(a: Complex, b: Complex) -> Bool {
// Identify all numbers with either component non-finite as a single
// "point at infinity".
guard a.isFinite || b.isFinite else { return true }
// For finite numbers, equality is defined componentwise. Cases where
// only one of a or b is infinite fall through to here as well, but this
// expression correctly returns false for them so we don't need to handle
// them explicitly.
return a.x == b.x && a.y == b.y
}
@_transparent
public func hash(into hasher: inout Hasher) {
// There are two equivalence classes to which we owe special attention:
// All zeros should hash to the same value, regardless of sign, and all
// non-finite numbers should hash to the same value, regardless of
// representation. The correct behavior for zero falls out for free from
// the hash behavior of floating-point, but we need to use a
// representative member for any non-finite values.
if isFinite {
hasher.combine(x)
hasher.combine(y)
} else {
hasher.combine(RealType.infinity)
}
}
}
@@ -1,19 +0,0 @@
//===--- Complex+IntegerLiteral.swift -------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 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
//
//===----------------------------------------------------------------------===//
extension Complex: ExpressibleByIntegerLiteral {
public typealias IntegerLiteralType = RealType.IntegerLiteralType
@inlinable
public init(integerLiteral value: IntegerLiteralType) {
self.init(RealType(integerLiteral: value))
}
}
@@ -1,59 +0,0 @@
//===--- Complex+Numeric.swift --------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 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
//
//===----------------------------------------------------------------------===//
extension Complex: Numeric {
@_transparent
public static func *(z: Complex, w: Complex) -> Complex {
return Complex(z.x*w.x - z.y*w.y, z.x*w.y + z.y*w.x)
}
@_transparent
public static func *=(z: inout Complex, w: Complex) {
z = z * w
}
/// The complex number with specified real part and zero imaginary part.
///
/// Equivalent to `Complex(RealType(real), 0)`.
@inlinable
public init<Other: BinaryInteger>(_ real: Other) {
self.init(RealType(real), 0)
}
/// The complex number with specified real part and zero imaginary part,
/// if it can be constructed without rounding.
@inlinable
public init?<Other: BinaryInteger>(exactly real: Other) {
guard let real = RealType(exactly: real) else { return nil }
self.init(real, 0)
}
/// The infinity-norm of the value (a.k.a. "maximum norm" or "Чебышёв
/// [Chebyshev] norm").
///
/// Equal to `max(abs(real), abs(imaginary))`.
///
/// If you need to work with the Euclidean norm (a.k.a. 2-norm) instead,
/// use the ``length`` or ``lengthSquared`` properties. If you just need
/// to know "how big" a number is, use this property.
///
/// **Edge cases:**
///
/// - If `z` is not finite, `z.magnitude` is infinity.
/// - If `z` is zero, `z.magnitude` is zero.
/// - Otherwise, `z.magnitude` is finite and non-zero.
@_transparent
public var magnitude: RealType {
guard isFinite else { return .infinity }
return max(abs(x), abs(y))
}
}
@@ -1,26 +0,0 @@
//===--- Complex+StringConvertible.swift ----------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 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
//
//===----------------------------------------------------------------------===//
extension Complex: CustomStringConvertible {
public var description: String {
guard isFinite else { return "inf" }
return "(\(x), \(y))"
}
}
#if compiler(>=6.0)
@_unavailableInEmbedded
#endif
extension Complex: CustomDebugStringConvertible {
public var debugDescription: String {
"Complex<\(RealType.self)>(\(String(reflecting: x)), \(String(reflecting: y)))"
}
}
+355 -30
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
// 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
@@ -11,8 +11,39 @@
import RealModule
// A [complex number](https://en.wikipedia.org/wiki/Complex_number).
// See Documentation.docc/Complex.md for more details.
/// A complex number represented by real and imaginary parts.
///
/// TODO: introductory text on complex numbers
///
/// Implementation notes:
/// -
/// This type does not provide heterogeneous real/complex arithmetic,
/// not even the natural vector-space operations like real * complex.
/// There are two reasons for this choice: first, Swift broadly avoids
/// mixed-type arithmetic when the operation can be adequately expressed
/// by a conversion and homogeneous arithmetic. Second, with the current
/// typechecker rules, it would lead to undesirable ambiguity in common
/// expressions (see README.md for more details).
///
/// Unlike C's `_Complex` and C++'s `std::complex<>` types, we do not
/// attempt to make meaningful semantic distinctions between different
/// representations of infinity or NaN. Any Complex value with at least
/// one non-finite component is simply "non-finite". In as much as
/// possible, we use the semantics of the point at infinity on the
/// Riemann sphere for such values. This approach simplifies the number of
/// edge cases that need to be considered for multiplication, division, and
/// the elementary functions considerably.
///
/// `.magnitude` does not return the Euclidean norm; it uses the "infinity
/// norm" (`max(|real|,|imaginary|)`) instead. There are two reasons for this
/// choice: first, it's simply faster to compute on most hardware. Second,
/// there exist values for which the Euclidean norm cannot be represented
/// (consider a number with `.real` and `.imaginary` both equal to
/// `RealType.greatestFiniteMagnitude`; the Euclidean norm would be
/// `.sqrt(2) * .greatestFiniteMagnitude`, which overflows). Using
/// the infinity norm avoids this problem entirely without significant
/// downsides. You can access the Euclidean norm using the `length`
/// property.
@frozen
public struct Complex<RealType> where RealType: Real {
// A note on the `x` and `y` properties
@@ -22,11 +53,11 @@ public struct Complex<RealType> where RealType: Real {
// `.real` and `.imaginary` properties, which wrap this storage and
// fixup the semantics for non-finite values.
/// The storage for the real component of the value.
/// The real component of the value.
@usableFromInline @inline(__always)
internal var x: RealType
/// The storage for the imaginary part of the value.
/// The imaginary part of the value.
@usableFromInline @inline(__always)
internal var y: RealType
@@ -38,7 +69,9 @@ public struct Complex<RealType> where RealType: Real {
}
}
#if swift(>=5.5)
extension Complex: Sendable where RealType: Sendable { }
#endif
// MARK: - Basic properties
extension Complex {
@@ -64,32 +97,37 @@ extension Complex {
set { y = newValue }
}
/// The raw representation of the value.
/// The additive identity, with real and imaginary parts both zero.
///
/// Use this when you need the underlying RealType values,
/// without fixup for NaN or infinity.
public var rawStorage: (x: RealType, y: RealType) {
@_transparent
get { (x, y) }
@_transparent
set { (x, y) = newValue }
/// See also:
/// -
/// - .one
/// - .i
/// - .infinity
@_transparent
public static var zero: Complex {
Complex(0, 0)
}
/// The raw representation of the real part of this value.
@available(*, deprecated, message: "Use rawStorage")
/// The multiplicative identity, with real part one and imaginary part zero.
///
/// See also:
/// -
/// - .zero
/// - .i
/// - .infinity
@_transparent
public var _rawX: RealType { x }
public static var one: Complex {
Complex(1, 0)
}
/// The raw representation of the imaginary part of this value.
@available(*, deprecated, message: "Use rawStorage")
@_transparent
public var _rawY: RealType { y }
}
extension Complex {
/// The imaginary unit.
///
/// See also ``zero``, ``one`` and ``infinity``.
/// See also:
/// -
/// - .zero
/// - .one
/// - .infinity
@_transparent
public static var i: Complex {
Complex(0, 1)
@@ -97,17 +135,31 @@ extension Complex {
/// The point at infinity.
///
/// See also ``zero``, ``one`` and ``i``.
/// See also:
/// -
/// - .zero
/// - .one
/// - .i
@_transparent
public static var infinity: Complex {
Complex(.infinity, 0)
}
/// The complex conjugate of this value.
@_transparent
public var conjugate: Complex {
Complex(x, -y)
}
/// True if this value is finite.
///
/// A complex value is finite if neither component is an infinity or nan.
///
/// See also ``isNormal``, ``isSubnormal`` and ``isZero``.
/// See also:
/// -
/// - `.isNormal`
/// - `.isSubnormal`
/// - `.isZero`
@_transparent
public var isFinite: Bool {
x.isFinite && y.isFinite
@@ -120,7 +172,11 @@ extension Complex {
/// one of the components is normal if its exponent allows a full-precision
/// representation.
///
/// See also ``isFinite``, ``isSubnormal`` and ``isZero``.
/// See also:
/// -
/// - `.isFinite`
/// - `.isSubnormal`
/// - `.isZero`
@_transparent
public var isNormal: Bool {
isFinite && (x.isNormal || y.isNormal)
@@ -132,7 +188,11 @@ extension Complex {
/// When the result of a computation is subnormal, underflow has occurred and
/// the result generally does not have full precision.
///
/// See also ``isFinite``, ``isNormal`` and ``isZero``.
/// See also:
/// -
/// - `.isFinite`
/// - `.isNormal`
/// - `.isZero`
@_transparent
public var isSubnormal: Bool {
isFinite && !isNormal && !isZero
@@ -143,12 +203,37 @@ extension Complex {
/// A complex number is zero if *both* the real and imaginary components
/// are zero.
///
/// See also ``isFinite``, ``isNormal`` and ``isSubnormal``.
/// See also:
/// -
/// - `.isFinite`
/// - `.isNormal`
/// - `.isSubnormal`
@_transparent
public var isZero: Bool {
x == 0 && y == 0
}
/// 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
/// `lengthSquared` properties instead.
///
/// Edge cases:
/// -
/// - If `z` is not finite, `z.magnitude` is `.infinity`.
/// - If `z` is zero, `z.magnitude` is `0`.
/// - Otherwise, `z.magnitude` is finite and non-zero.
///
/// See also:
/// -
/// - `.length`
/// - `.lengthSquared`
@_transparent
public var magnitude: RealType {
guard isFinite else { return .infinity }
return max(abs(x), abs(y))
}
/// A "canonical" representation of the value.
///
/// For normal complex numbers with a RealType conforming to
@@ -182,13 +267,36 @@ extension Complex {
self.init(real, 0)
}
/// The complex number with zero real part and specified imaginary part.
/// The complex number with specified imaginary part and zero real part.
///
/// Equivalent to `Complex(0, imaginary)`.
@inlinable
public init(imaginary: RealType) {
self.init(0, imaginary)
}
/// The complex number with specified real part and zero imaginary part.
///
/// Equivalent to `Complex(RealType(real), 0)`.
@inlinable
public init<Other: BinaryInteger>(_ real: Other) {
self.init(RealType(real), 0)
}
/// The complex number with specified real part and zero imaginary part,
/// if it can be constructed without rounding.
@inlinable
public init?<Other: BinaryInteger>(exactly real: Other) {
guard let real = RealType(exactly: real) else { return nil }
self.init(real, 0)
}
public typealias IntegerLiteralType = Int
@inlinable
public init(integerLiteral value: Int) {
self.init(RealType(value))
}
}
extension Complex where RealType: BinaryFloatingPoint {
@@ -206,3 +314,220 @@ extension Complex where RealType: BinaryFloatingPoint {
self.init(x, y)
}
}
// MARK: - Conformance to Hashable and Equatable
//
// The Complex type identifies all non-finite points (waving hands slightly,
// we identify all NaNs and infinites as the point at infinity on the Riemann
// sphere).
extension Complex: Hashable {
@_transparent
public static func ==(a: Complex, b: Complex) -> Bool {
// Identify all numbers with either component non-finite as a single
// "point at infinity".
guard a.isFinite || b.isFinite else { return true }
// For finite numbers, equality is defined componentwise. Cases where
// only one of a or b is infinite fall through to here as well, but this
// expression correctly returns false for them so we don't need to handle
// them explicitly.
return a.x == b.x && a.y == b.y
}
@_transparent
public func hash(into hasher: inout Hasher) {
// There are two equivalence classes to which we owe special attention:
// All zeros should hash to the same value, regardless of sign, and all
// non-finite numbers should hash to the same value, regardless of
// representation. The correct behavior for zero falls out for free from
// the hash behavior of floating-point, but we need to use a
// representative member for any non-finite values.
if isFinite {
hasher.combine(x)
hasher.combine(y)
} else {
hasher.combine(RealType.infinity)
}
}
}
// MARK: - Conformance to Codable
// FloatingPoint does not refine Codable, so this is a conditional conformance.
extension Complex: Decodable where RealType: Decodable {
public init(from decoder: Decoder) throws {
var unkeyedContainer = try decoder.unkeyedContainer()
let x = try unkeyedContainer.decode(RealType.self)
let y = try unkeyedContainer.decode(RealType.self)
self.init(x, y)
}
}
extension Complex: Encodable where RealType: Encodable {
public func encode(to encoder: Encoder) throws {
var unkeyedContainer = encoder.unkeyedContainer()
try unkeyedContainer.encode(x)
try unkeyedContainer.encode(y)
}
}
// MARK: - Formatting
extension Complex: CustomStringConvertible {
public var description: String {
guard isFinite else {
return "inf"
}
return "(\(x), \(y))"
}
}
extension Complex: CustomDebugStringConvertible {
public var debugDescription: String {
"Complex<\(RealType.self)>(\(String(reflecting: x)), \(String(reflecting: y)))"
}
}
// MARK: - Operations for working with polar form
extension Complex {
/// The Euclidean norm (a.k.a. 2-norm, `sqrt(real*real + imaginary*imaginary)`).
///
/// This property takes care to avoid spurious over- or underflow in
/// this computation. For example:
///
/// let x: Float = 3.0e+20
/// let x: Float = 4.0e+20
/// let naive = sqrt(x*x + y*y) // +Inf
/// let careful = Complex(x, y).length // 5.0e+20
///
/// Note that it *is* still possible for this property to overflow,
/// because the length can be as much as sqrt(2) times larger than
/// either component, and thus may not be representable in the real type.
///
/// For most use cases, you can use the cheaper `.magnitude`
/// property (which computes the ∞-norm) instead, which always produces
/// a representable result.
///
/// Edge cases:
/// -
/// If a complex value is not finite, its `.length` is `infinity`.
///
/// See also:
/// -
/// - `.magnitude`
/// - `.lengthSquared`
/// - `.phase`
/// - `.polar`
/// - `init(r:θ:)`
@_transparent
public var length: RealType {
let naive = lengthSquared
guard naive.isNormal else { return carefulLength }
return .sqrt(naive)
}
// Internal implementation detail of `length`, moving slow path off
// of the inline function. Note that even `carefulLength` can overflow
// for finite inputs, but only when the result is outside the range
// of representable values.
@usableFromInline
internal var carefulLength: RealType {
guard isFinite else { return .infinity }
return .hypot(x, y)
}
/// The squared length `(real*real + imaginary*imaginary)`.
///
/// 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, `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.
///
/// For many cases, `.magnitude` can be used instead, which is similarly
/// cheap to compute and always returns a representable value.
///
/// See also:
/// -
/// - `.length`
/// - `.magnitude`
@_transparent
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
/// the complex value is zero or infinity, the phase is not defined,
/// and `nan` is returned.
///
/// Edge cases:
/// -
/// If the complex value is zero or non-finite, phase is `nan`.
///
/// See also:
/// -
/// - `.length`
/// - `.polar`
/// - `init(r:θ:)`
@inlinable
public var phase: RealType {
guard isFinite && !isZero else { return .nan }
return .atan2(y: y, x: x)
}
/// The length and phase (or polar coordinates) of this value.
///
/// Edge cases:
/// -
/// If the complex value is zero or non-finite, phase is `.nan`.
/// If the complex value is non-finite, length is `.infinity`.
///
/// See also:
/// -
/// - `.length`
/// - `.phase`
/// - `init(r:θ:)`
public var polar: (length: RealType, phase: RealType) {
(length, phase)
}
/// Creates a complex value specified with polar coordinates.
///
/// Edge cases:
/// -
/// - 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`
@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)
}
}
}
@@ -0,0 +1,99 @@
//===--- 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 swift(>=5.3) && canImport(_Differentiation)
import _Differentiation
extension Complex: Differentiable
where RealType: Differentiable, RealType.TangentVector == RealType {
public typealias TangentVector = Self
@inlinable
public var zeroTangentVectorInitializer: () -> Self {
{ Complex.zero }
}
}
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
@@ -1,67 +0,0 @@
# ``Complex``
A complex number type represented by its real and imaginary parts, and equipped
with the usual arithmetic operators and math functions.
## Overview
You can access these Cartesian components using the real and imaginary
properties.
```swift
let z = Complex(1,-1) // 1 - i
let re = z.real // 1
let im = z.imaginary // -1
```
All `Complex` numbers with a non-finite component are treated as a single
"point at infinity," with infinite magnitude and indeterminant phase. Thus,
the real and imaginary parts of an infinity are nan.
```swift
let w = Complex<Double>.infinity
w == -w // true
let re = w.real // .nan
let im = w.imag // .nan
```
See <doc:Infinity> for more details.
The ``magnitude`` property of a complex number is the infinity norm of the
value (a.k.a. “maximum norm” or “Чебышёв [Chebyshev] norm”). To get the two
norm (a.k.a. "Euclidean norm"), use the ``length`` property. See
<doc:Magnitude> for more details.
## Topics
### Real and imaginary parts
- ``real``
- ``imaginary``
- ``rawStorage``
- ``init(_:_:)``
- ``init(_:)-5aesj``
- ``init(imaginary:)``
### Phase, length and magnitude
- ``magnitude``
- ``length``
- ``lengthSquared``
- ``normalized``
- ``phase``
- ``polar``
- ``init(length:phase:)``
### Scaling by real numbers
- ``multiplied(by:)``
- ``divided(by:)``
### Complex-specific operations
- ``conjugate``
### Classification
- ``isZero``
- ``isSubnormal``
- ``isNormal``
- ``isFinite``
@@ -1,88 +0,0 @@
# ``ComplexModule``
Types and operations for working with complex numbers.
## Overview
### Representation
The `Complex` type is generic over an associated `RealType`; complex numbers
are represented as two `RealType` values, the real and imaginary parts of the
number.
```
let z = Complex<Double>(1, 2)
let re = z.real
let im = z.imaginary
```
### Memory layout
A `Complex` value is stored as two `RealType` values arranged consecutively
in memory. Thus it has the same memory layout as:
- A Fortran complex value built on the corresponding real type (as used
by BLAS and LAPACK).
- A C struct with real and imaginary parts and nothing else (as used by
computational libraries predating C99).
- A C99 `_Complex` value built on the corresponding real type.
- A C++ `std::complex` value built on the corresponding real type.
Functions taking complex arguments in these other languages are not
automatically converted on import, but you can safely write shims that
map them into Swift types by converting pointers.
### Real-Complex arithmetic
Because the real numbers are a subset of the complex numbers, many
languages support arithmetic with mixed real and complex operands.
For example, C allows the following:
```c
#include <complex.h>
double r = 1;
double complex z = CMPLX(0, 2); // 2i
double complex w = r + z; // 1 + 2i
```
The `Complex` type does not provide such mixed operators:
```swift
let r = 1.0
let z = Complex(imaginary: 2.0)
let w = r + z // error: binary operator '+' cannot be applied to operands of type 'Double' and 'Complex<Double>'
```
In order to write the example from C above in Swift, you have to perform an
explicit conversion:
```swift
let r = 1.0
let z = Complex(imaginary: 2.0)
let w = Complex(r) + z // OK
```
There are two reasons for this choice. Most importantly, Swift generally avoids
mixed-type arithmetic. Second, if we _did_ provide such heterogeneous operators,
it would lead to undesirable behavior in common expressions when combined with
literal type inference. Consider the following example:
```swift
let a: Double = 1
let b = 2*a
```
`b` ought to have type `Double`, but if we did have a Complex-by-Real `*`
operation, `2*a` would either be ambiguous (if there were no type context),
or be inferred to have type `Complex<Double>` (if the expression appeared
in the context of an extension defined on `Complex`).
Note that we _do_ provide heterogeneous multiplication and division by a real
value, spelled as ``Complex/divided(by:)`` and ``Complex/multiplied(by:)``
to avoid ambiguity.
```swift
let z = Complex<Double>(1,3)
let w = z.multiplied(by: 2)
```
These operations are generally more efficient than converting the scale to
a complex number and then using `*` or `/`.
@@ -1,140 +0,0 @@
# Notes on Complex Division
A discussion of the algorithms used to implement complex division
## Overview
How does compute the quotient of two complex numbers z/w? The naïve schoolbook
answer is to turn it into complex multiplication by scaling both numerator and
denominator by the conjugate of w: z/w = (zw̅)/(ww̅) = (zw̅)/|w|². Translated
directly into swift, this expression would become:
```swift
extension Complex {
func naïveDivision(_ z: Complex, _ w: Complex) -> Complex {
(z * w.conjugate).divded(by: w.lengthSquared)
}
}
```
If both z and w are both "well-scaled" (i.e. their exponents are neither very
large nor very small), then this expression works reasonably well when
evaluated in floating-point. Cancellation may occur in the computation of
either the real or the imaginary part of the zw̅ term, but not in both
simultaneously, so the relative error in any vector norm is bounded by a
small multiple of machine epsilon.
However, if z or w is not well-scaled, then either zw̅ or |w|² or both may
underflow or overflow, even when the actual quotient may be perfectly
representable. For example, if we have
```swift
let a: Float = 1.84467441E+19 // large, but not outrageously large
let z = Complex(a, a)
let w = z
```
then both `(z * w.conjugate)` and `w.lengthSquared` overflow, and the result
of `naïveDivision` is `(NaN, NaN)` even though the actual mathematical quotient
is 1.
At least `(NaN, NaN)` is obviously wrong; when intermediate results underflow
instead of overflow, we can instead get bogus results that are not obvious at
all. For example:
```swift
let z = Complex<Float>(imaginary: 6.6174449e-24)
let w = Complex<Float>(5.29395592e-23, 3.97046694e-23)
let q = naïveDivision(z, w)
```
`q` is computed as `(0.666666686, 0.666666686)`, which looks like a reasonable
result, but the exact `z/w` would be `(0.6, 0.8)`; both the phase and magnitude
of the computed result have large errors, and there is no indication that
anything went wrong.
## Complex division in Swift Numerics
### Goals
Programming languages and libraries have developed a variety of approaches to
handle this problem. Swift Numerics' approach is somewhat novel, so I will
first lay out the considerations that lead us to it.
1. Division should be reasonably fast, and permit compiler optimizations that
make it faster. So long as all inputs are well-scaled, it should not be
much slower than multiplication.
2. Division should have the same error characteristics as multiplication;
componentwise error bounds and correct rounding are non-goals. Good error
bounds in a complex norm are what matters.
3. Division should not be any more sensitive to undue overflow or underflow
than multiplication is (i.e. it is OK for results very near the boundaries
to overflow or underflow even though the exact result would be
representable, but results that are far from those boundaries should always
be computed with good accuracy).
### Fast path
These considerations lead us to a first draft of our implementation; since we
want division to be roughly like multiplication, we will "simply" turn it into
a multiplication via the naïve formula:
```swift
public static func /(z: Complex, w: Complex) -> Complex {
let lenSq = w.lengthSquared
guard lenSq.isNormal else { /* naive formula will not work */ }
return z * w.conjugate.divided(by: lenSq)
}
```
if `lenSq` can be computed without overflow or underflow, then
`w.conjugate.divided(by: lenSq)` is a (rounded) reciprocal `1/w`, and so
multiplying that by `z` satisfies the goals that we laid out above. Note
in particular that if we are dividing multiple values by a single divisor,
the reciprocal is a constant, and this check only has to happen once.
That leaves us just needing to figure out what to do when the reciprocal
is not well-scaled.
### Slow path
When an approximate reciprocal for the divisor is not representable, we use
a scaling algorithm adapted from Doug Priest's "Efficient Scaling for
Complex Division". In hand-wavy form, Priest's idea is:
1. choose a scale factor s ~ |w|^(-¾)
2. let wʹ ← sw
2. let zʹ ← sz
Note that we _can_ compute a reciprocal for wʹ without overflow or underflow,
because |wʹ| ~ |w|^(¼), so |wʹ²| ~ |w|^(½) and so |w̅ʹ/wʹ²| ~ |w|^(-¼).¹
To compute z/w, we compute zʹ/wʹ. sz might overflow or underflow, but only
if the final computation would overflow or underflow anyway. This is because
division by w is a dilation combined with a rotation; because |w| is bounded
away from 1, the multiplication by s is a dilation if and only if division
by w is also dilation (this is where we diverge from Priest; because he
doesn't have a fast-path for well-scaled w, he has to handle this case
carefully).
Like Priest, we arrange for s to be a power of the radix with the desired
scale, which makes the computation of wʹ and zʹ exact (unless zʹ over- or
underflows). This achieves one more desirable property: barring underflow,
rescaling both w and z by the radix does not change results when we move
between the fast and slow algorithms.
Instead of `zʹ/wʹ = zʹ(w̅ʹ/|wʹ|²)`, Priest uses `(zw″)/|wʹ|²`. There isn't
a strong reason to favor one or the other numerically, but our formulation
lets us preserve `z/w = z * w.reciprocal` under scaling by powers of the
radix (up to the underflow boundary), which is somewhat nice to have, and
allows us to extract a little bit more ILP in some cases.
----
### Notes
¹ This analysis fails for types like Float16 where the number of
significand bits is on the order of the greatest exponent because the desired
s may not be representable if w is subnormal. Note that the problem is _only_
in the representation of s, so we can handle this case by rescaling in two
steps.
@@ -1,55 +0,0 @@
# Zero and infinity
Semantics of `Complex` zero and infinity values, and important considerations
when porting code from other languages.
## Overview
Unlike C and C++'s complex types, `Complex` does not attempt to make a
semantic distinction between different infinity and NaN values. Any `Complex`
datum with a non-finite component is treated as the "point at infinity" on
the Riemann sphere--a value with infinite magnitude and unspecified phase.
As a consequence, all values with either component infinite or NaN compare
equal, and hash the same. Similarly, all zero values compare equal and hash
the same.
### Rationale
This choice has some drawbacks,¹ but also some significant advantages.
In particular, complex multiplication is the most common operation performed
with a complex type, and one would like to be able to use the usual naive
arithmetic implementation, consisting of four real multiplications and two
real additions:
```
(a + bi) * (c + di) = (ac - bd) + (ad + bc)i
```
`Complex` can use this implementation, because we do not differentiate between
infinities and NaN values. C and C++, by contrast, cannot use this
implementation by default, because, for example:
```
(1 + ∞i) * (0 - 2i) = (1*0 - ∞*(-2)) + (1*(-2) + ∞*0)i
= (0 - ∞) + (-2 + nan)i
= -∞ + nan i
```
`Complex` treats this as "infinity", which is the correct result. C and C++
treat it as a nan value, however, which is incorrect; infinity multiplied
by a non-zero number should be infinity. Thus, C and C++ (by default) must
detect these special cases and fix them up, which makes multiplication a
more computationally expensive operation.²
### Footnotes:
¹ W. Kahan, Branch Cuts for Complex Elementary Functions, or Much Ado
About Nothing's Sign Bit. In A. Iserles and M.J.D. Powell, editors,
_Proceedings The State of Art in Numerical Analysis_, pages 165–211, 1987.
² This can be addressed in C programs by use of the `STDC CX_LIMITED_RANGE`
pragma, which instructs the compiler to simply not care about these cases.
Unfortunately, this pragma is not often used in real C or C++ programs
(though it does see some use in _libraries_). Programmers tend to specify
`-ffast-math` or maybe `-ffinite-math-only` instead, which has other
undesirable consequences.
@@ -1,144 +0,0 @@
# Magnitude and norms
Introduction to the concept of norm and discussion of the `Complex` type's
`.magnitude` property.
## Overview
In mathematics, a *norm* is a function that gives each element of a vector
space a non-negative length.¹
Many different norms can be defined on the complex numbers, viewed as a
vector space over the reals. All of these norms have some basic
properties. If we use *‖z‖* to represent any norm of *z*, it must:
- be *subadditive* (a.k.a. satisfy the triangle inequalty):
‖z + w‖ ≤ ‖z‖ + ‖w‖ for any two complex numbers z and w.
- be *homogeneous*
‖az‖ = |a|‖z‖ for any real number a and complex number z.
- and be *positive definite*
‖z‖ is zero if and only if z is zero.
The three most commonly-used norms are:
- 1-norm ("taxicab norm"):
‖x + iy‖₁ = |x| + |y|
- 2-norm ("Euclidean norm"):
‖x + iy‖₂ = √(x² + y²)
- ∞-norm ("maximum norm" or "Чебышёв [Chebyshev] norm")²:
‖x + iy‖ = max(|x|,|y|)
> Exercise:
> 1. Check that these properties hold for one of the three norms
that we just defined. (Hint: write z = a+bi and w = c+di,
and use the fact that the absolute value is a norm on the
real numbers, and therefore has the same property).
The `Complex` type gives special names to two of these norms; `length`
for the 2-norm, and `magnitude` for the ∞-norm.
### Magnitude:
The `Numeric` protocol requires us to choose a norm to call `magnitude`,
but does not give guidance as to which one we should pick. The easiest choice
might have been the Euclidean norm; it's the one with which people are most
likely to be familiar.
However, there are good reasons to make a different choice:
- Computing the Euclidean norm requires special care to avoid spurious
overflow/underflow (see implementation notes for `length` below). The
naive expressions for the taxicab and maximum norm always give the best
answer possible.
- Even when special care is used, the Euclidean and taxicab norms are
not necessarily representable. Both can be infinite even for finite
numbers.
```swift
let big = Double.greatestFiniteMagnitude
let z = Complex(big, big)
```
The taxicab norm of `z` would be `big + big`, which overflows; the
Euclidean norm would be `sqrt(2) * big`, which also overflows.
But the maximum norm is always equal to the magnitude of either `real`
or `imaginary`, so it is necessarily representable.
- The ∞-norm is the choice of established computational libraries, like
BLAS and LAPACK.
For these reasons, the `magnitude` property of `Complex` binds the
maximum norm:
```swift
Complex(2, 3).magnitude // 3
Complex(-1, 0.5).magnitude // 1
```
### Length:
The `length` property of a `Complex` value is its Euclidean norm.
```swift
Complex(2, 3).length // 3.605551275463989
Complex(-1, 0.5).length // 1.118033988749895
```
Aside from familiarity, the Euclidean norm has one important property
that the maximum norm lacks:
- it is *multiplicative*:
‖zw‖₂ = ‖z‖₂‖w‖₂ for any two complex numbers z and w.
> Exercises:
> 1. Find z and w that show that the maximum norm is not multiplicative.
(i.e. exhibit z and w such that ‖zw‖ ≠ ‖z‖‖w‖.)
> 2. Is the 1-norm multiplicative?
### Implementation notes:
The `length` property takes special care to produce an accurate answer,
even when the value is poorly-scaled. The naive expression for `length`
would be `sqrt(x*x + y*y)`, but this can overflow or underflow even when
the final result should be a finite number.
```swift
// Suppose that length were implemented like this:
extension Complex {
var naiveLength: RealType {
.sqrt(real*real + imaginary*imaginary)
}
}
// Then taking the length of even a modestly large number:
let z = Complex<Float>(1e20, 1e20)
// or small number:
let w = Complex<Float>(1e-24, 1e-24)
// would overflow:
z.naiveLength // Inf
// or underflow:
w.naiveLength // 0
```
Instead, `length` is implemented using a two-step algorithm. First we
compute `lengthSquared`, which is `x*x + y*y`. If this is a normal
number (meaning that no overflow or underflow has occured), we can safely
return its square root. Otherwise, we redo the computation with a more
careful computation, which avoids spurious under- or overflow:
```swift
let z = Complex<Float>(1e20, 1e20)
let w = Complex<Float>(1e-24, 1e-24)
z.length // 1.41421358E+20
w.length // 1.41421362E-24
```
### Footnotes:
¹ Throughout this documentation, "norm" refers to a
[vector norm](https://en.wikipedia.org/wiki/Norm_(mathematics)).
To confuse the matter, there are several similar things also called
"norm" in mathematics. The other one you are most likely to run into
is the [field norm](https://en.wikipedia.org/wiki/Field_norm).
Field norms are much less common than vector norms, but the C++
`std::norm` operation implements a field norm. To get the (Euclidean)
vector norm in C++, use `std::abs`.
² There's no subscript-∞ in unicode, so I write the infinity norm
without the usual subscript.
@@ -1,8 +1,8 @@
//===--- Complex+ElementaryFunctions.swift --------------------*- swift -*-===//
//===--- ElementaryFunctions.swift ----------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
// Copyright (c) 2019-2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
@@ -119,7 +119,7 @@ extension Complex: ElementaryFunctions {
}
// Special cases out of the way, evaluate as discussed above.
return Complex(
Relaxed.multiplyAdd(.cos(z.y), .expMinusOne(z.x), .cosMinusOne(z.y)),
RealType._mulAdd(.cos(z.y), .expMinusOne(z.x), .cosMinusOne(z.y)),
.exp(z.x) * .sin(z.y)
)
}
@@ -141,10 +141,7 @@ extension Complex: ElementaryFunctions {
public static func cosh(_ z: Complex) -> Complex {
guard z.isFinite else { return z }
guard z.x.magnitude < -RealType.log(.ulpOfOne) else {
let phase = Complex(
RealType.cos(z.y),
RealType(signOf: z.x, magnitudeOf: 1) * RealType.sin(z.y)
)
let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))
let firstScale = RealType.exp(z.x.magnitude/2)
let secondScale = firstScale/2
return phase.multiplied(by: firstScale).multiplied(by: secondScale)
@@ -167,19 +164,16 @@ extension Complex: ElementaryFunctions {
)
}
// sinh(x + iy) = sinh(x) cos(y) + i cosh(x) sin(y)
// sinh(x + iy) = sinh(x) cos(y) + i cosh(x) sinh(y)
//
// See cosh above for algorithm details.
@inlinable
public static func sinh(_ z: Complex) -> Complex {
guard z.isFinite else { return z }
guard z.x.magnitude < -RealType.log(.ulpOfOne) else {
let phase = Complex(
RealType(signOf: z.x, magnitudeOf: RealType.cos(z.y)),
RealType.sin(z.y)
)
let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))
let firstScale = RealType.exp(z.x.magnitude/2)
let secondScale = firstScale/2
let secondScale = RealType(signOf: z.x, magnitudeOf: firstScale/2)
return phase.multiplied(by: firstScale).multiplied(by: secondScale)
}
return Complex(
@@ -306,7 +300,7 @@ extension Complex: ElementaryFunctions {
// We are not trying for sub-ulp accuracy, just a good relative error
// bound, so for our purposes it suffices to have log u dominate the
// result:
if u >= 1 || u >= Relaxed.multiplyAdd(u, u, v*v) {
if u >= 1 || u >= RealType._mulAdd(u,u,v*v) {
let r = v / u
return Complex(.log(u) + .log(onePlus: r*r)/2, θ)
}
-130
View File
@@ -1,130 +0,0 @@
//===--- Polar.swift ------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 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 RealModule
extension Complex {
/// The Euclidean norm (a.k.a. 2-norm).
///
/// This property takes care to avoid spurious over- or underflow in
/// this computation. For example:
///
/// let x: Float = 3.0e+20
/// let x: Float = 4.0e+20
/// let naive = sqrt(x*x + y*y) // +Inf
/// let careful = Complex(x, y).length // 5.0e+20
///
/// Note that it *is* still possible for this property to overflow,
/// because the length can be as much as sqrt(2) times larger than
/// either component, and thus may not be representable in the real type.
///
/// For most use cases, you can use the cheaper ``magnitude``
/// property (which computes the ∞-norm) instead, which always produces
/// a representable result. See <doc:Magnitude> for more details.
///
/// Edge cases:
/// - If a complex value is not finite, its `length` is `infinity`.
///
/// See also ``lengthSquared``, ``phase``, ``polar``
/// and ``init(length:phase:)``.
@_transparent
public var length: RealType {
let naive = lengthSquared
guard naive.isNormal else { return carefulLength }
return .sqrt(naive)
}
// Internal implementation detail of ``length``, moving slow path off
// of the inline function. Note that even `carefulLength` can overflow
// for finite inputs, but only when the result is outside the range
// of representable values.
@usableFromInline
internal var carefulLength: RealType {
guard isFinite else { return .infinity }
return .hypot(x, y)
}
/// The squared length `(real*real + imaginary*imaginary)`.
///
/// 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, `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.
///
/// For many cases, ``magnitude`` can be used instead, which is similarly
/// cheap to compute and always returns a representable value.
///
/// Note that because of how `lengthSquared` is used, it is a primary
/// design goal that it be as fast as possible. Therefore, it does not
/// normalize infinities, and may return either `.infinity` or `.nan`
/// for non-finite values.
@_transparent
public var lengthSquared: RealType {
x*x + y*y
}
/// The phase (angle, or "argument").
///
/// - Returns: The angle (measured above the real axis) in radians. If
/// the complex value is zero or infinity, the phase is not defined,
/// and `nan` is returned.
///
/// See also ``length``, ``polar`` and ``init(length:phase:)``.
@inlinable
public var phase: RealType {
guard isFinite && !isZero else { return .nan }
return .atan2(y: y, x: x)
}
/// The length and phase (or polar coordinates) of this value.
///
/// Edge cases:
/// - If the complex value is zero or non-finite, phase is `.nan`.
/// - If the complex value is non-finite, length is `.infinity`.
///
/// See also: ``length``, ``phase`` and ``init(length:phase:)``.
public var polar: (length: RealType, phase: RealType) {
(length, phase)
}
/// Creates a complex value specified with polar coordinates.
///
/// Edge cases:
/// - 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`` and ``polar``.
@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)
}
}
}
+7 -10
View File
@@ -2,14 +2,12 @@
This module provides a `Complex` number type generic over an underlying `RealType`:
```swift
import Numerics
let z = Complex(1,1) // z = 1 + i
1> import ComplexModule
2> let z = Complex(1,1) // z = 1 + i
```
This module provides approximate feature parity and memory layout compatibility with C, Fortran, and C++ complex types (although the importer does not map the types for you, buffers may be reinterpreted to shim API defined in other languages).
This module provides approximate feature parity and memory layout compatibility with C, Fortran, and C++ complex types (although the importer cannot map the types for you, buffers may be reinterpreted to shim API defined in other languages).
The usual arithmetic operators are provided for complex numbers, as well as conversion to and from polar coordinates and many useful properties, plus conformances to the obvious usual protocols: `Equatable`, `Hashable`, `Codable` (if the underlying `RealType` is), and `AlgebraicField` (hence also `AdditiveArithmetic` and `SignedNumeric`).
The `Complex` type conforms to `ElementaryFunctions`, which makes common transcendental functions like `log`, `pow`, and `sin` available (consult the documentation for `ElementaryFunctions` in the `RealModule` for a full list and more information.
The usual arithmetic operators are provided for Complex numbers, as well as conversion to and from polar coordinates and many useful properties, plus conformances to the obvious usual protocols: `Equatable`, `Hashable`, `Codable` (if the underlying `RealType` is), and `AlgebraicField` (hence also `AdditiveArithmetic` and `SignedNumeric`).
### Dependencies:
- `RealModule`.
@@ -38,10 +36,10 @@ They are not provided by the Complex module for two reasons:
}
}
```
This makes heterogeneous arithmetic operators a non-option in the short term.
This is a show-stopper for heterogeneous arithmetic operators in the short term.
### Infinity and nan
C and C++ attempt to define semantics that interpret the signs of infinity and zero.
C and C++ attempt to define precise semantics that interpret the sign of infinity and zero.
This is occasionally useful, but it also results in a lot of extra work.
The Swift Numerics `Complex` type does not assign any semantic meaning to the sign of zero and infinity; `(±0,±0)`, are all considered to be encodings of the value zero.
Similarly, `(±inf, y)`, `(x, ±inf)`, `(nan, y)` and `(x, nan)` are all considered to be encodings of a single exceptional value with infinite magnitude and undefined phase.
@@ -56,8 +54,7 @@ However, in practice there are good reasons to use something else instead:
- The 2-norm requires special care to avoid spurious overflow/underflow, but the naive expressions for the 1-norm ("taxicab norm") or ∞-norm ("sup norm") are always correct.
- Even when care is used, near the overflow boundary the 2-norm and the 1-norm are not representable.
As an example, consider `z = Complex(big, big)`, where `big` is `Double.greatestFiniteMagnitude`.
The 1-norm and 2-norm of `z` both overflow (the 1-norm would be `2*big`, and the 2-norm would be `sqrt(2)*big`, neither of which are representable as `Double`), but the ∞-norm is always equal to either `real` or `imaginary`, so it is guaranteed to be representable.
As an example, consider `z = Complex(big, big)`, where `big` is `Double.greatestFiniteMagnitude`. The 1-norm and 2-norm of `z` both overflow (the 1-norm would be `2*big`, and the 2-norm would be `sqrt(2)*big`, neither of which are representable as `Double`), but the ∞-norm is always equal to either `real` or `imaginary`, so it is guaranteed to be representable.
Because of this, the ∞-norm is the obvious alternative; it gives the nicest API surface.
- If we consider the magnitude of more exotic types, like operators, the 1-norm and ∞-norm are significantly easier to compute than the 2-norm (O(n) vs. "no closed form expression, but O(n^3) iterative methods"), so it is nice to establish a precedent of `.magnitude` binding one of these cheaper-to-compute norms.
- The ∞-norm is heavily used in other computational libraries; for example, it is used by the `izamax` and `icamax` functions in BLAS.
-41
View File
@@ -1,41 +0,0 @@
//===--- Scale.swift ------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 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
//
//===----------------------------------------------------------------------===//
// Policy: deliberately not using the * and / operators for these at the
// moment, because then there's an ambiguity in expressions like 2*z; is
// that Complex(2) * z or is it RealType(2) * z? This is especially
// problematic in type inference: suppose we have:
//
// let a: RealType = 1
// let b = 2*a
//
// what is the type of b? If we don't have a type context, it's ambiguous.
// If we have a Complex type context, then b will be inferred to have type
// Complex! Obviously, that doesn't help anyone.
extension Complex {
/// The result of multiplying this value by the real number `a`.
///
/// Equivalent to `self * Complex(a)`, but may be computed more efficiently.
@inlinable @inline(__always)
public func multiplied(by a: RealType) -> Complex {
Complex(x*a, y*a)
}
/// The result of dividing this value by the real number `a`.
///
/// More efficient than `self / Complex(a)`. May not produce exactly the
/// same result, but will always be more accurate if they differ.
@inlinable @inline(__always)
public func divided(by a: RealType) -> Complex {
Complex(x/a, y/a)
}
}
+1 -1
View File
@@ -10,5 +10,5 @@
//===----------------------------------------------------------------------===//
// A module that re-exports the complete Swift Numerics public API.
@_exported import ComplexModule
@_exported import RealModule
@_exported import ComplexModule
+21 -43
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
// 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
@@ -16,7 +16,7 @@
/// division are defined, and behave basically like those operations on
/// the real numbers. More precisely, a field is a commutative group under
/// its addition, the non-zero elements of the field form a commutative
/// group under its multiplication, and the distributive law holds.
/// group under its multiplication, and the distributitve law holds.
///
/// Some common examples of fields include:
///
@@ -32,16 +32,20 @@
/// Because integer multiplication does not form a group; it's commutative and
/// associative, but integers do not have multiplicative inverses.
/// I.e. if a is any integer other than 1 or -1, there is no integer b such
/// that `a*b = 1`. The existence of inverses is requried to form a field.
/// that a*b = 1. The existence of inverses is requried to form a field.
///
/// If a type `T` conforms to the ``Real`` protocol, then `T` and `Complex<T>`
/// If a type `T` conforms to the `Real` protocol, then `T` and `Complex<T>`
/// both conform to `AlgebraicField`.
///
/// See also Swift's `SignedNumeric`, `Numeric` and `AdditiveArithmetic`
/// protocols.
/// See Also:
/// -
/// - Real
/// - SignedNumeric
/// - Numeric
/// - AdditiveArithmetic
///
/// [field]: https://en.wikipedia.org/wiki/Field_(mathematics)
public protocol AlgebraicField: SignedNumeric where Magnitude: AlgebraicField {
public protocol AlgebraicField: SignedNumeric {
/// Replaces a with the (approximate) quotient `a/b`.
static func /=(a: inout Self, b: Self)
@@ -52,11 +56,6 @@ public protocol AlgebraicField: SignedNumeric where Magnitude: AlgebraicField {
/// The (approximate) reciprocal (multiplicative inverse) of this number,
/// if it is representable.
///
/// If reciprocal is non-nil, you can replace division by self with
/// multiplication by reciprocal and either get exact the same result
/// (for finite fields) or approximately the same result up to a typical
/// rounding error (for floating-point formats).
///
/// If self is zero and the type has no representation for infinity (as
/// in a typical finite field implementation), or if a reciprocal would
/// overflow or underflow such that it cannot be accurately represented,
@@ -66,17 +65,17 @@ public protocol AlgebraicField: SignedNumeric where Magnitude: AlgebraicField {
/// for `Real` or `Complex` types, because these types have an
/// `.infinity` value that acts as the reciprocal of `.zero`.
///
/// If `b.reciprocal` is non-nil, you may be able to replace division by `b`
/// If `x.reciprocal` is non-nil, you may be able to replace division by `x`
/// with multiplication by this value. It is not advantageous to do this
/// for an isolated division unless it is a compile-time constant visible
/// to the compiler, but if you are dividing many values by a single
/// denominator, this will often be a significant performance win.
///
/// Note that this will slightly perturb results for fields with approximate
/// arithmetic, such as real or complex types--using a normal division
/// Note that this will slightly perturb results for some fields with
/// approximate arithmetic, such as real types--using a normal division
/// is generally more accurate--but no catastrophic loss of accuracy will
/// result. For fields with exact arithmetic, the results are necessarily
/// identical.
/// result. For fields with exact arithmetic, or for the Complex types,
/// the results are identical.
///
/// A typical use case looks something like this:
/// ```
@@ -90,12 +89,6 @@ public protocol AlgebraicField: SignedNumeric where Magnitude: AlgebraicField {
/// }
/// ```
var reciprocal: Self? { get }
/// `a + b`, with the optimizer licensed to reassociate and form FMAs.
static func _relaxedAdd(_ a: Self, _ b: Self) -> Self
/// `a * b`, with the optimizer licensed to reassociate and form FMAs.
static func _relaxedMul(_ a: Self, _ b: Self) -> Self
}
extension AlgebraicField {
@@ -106,27 +99,12 @@ extension AlgebraicField {
return result
}
// Implementations should be *conservative* with the reciprocal property;
// it is OK to return `nil` even in cases where a reciprocal could be
// represented. For this reason, a default implementation that simply
// always returns `nil` is correct, but conforming types should provide
// a better implementation if possible.
@_transparent
/// Implementations should be *conservative* with the reciprocal property;
/// it is OK to return `nil` even in cases where a reciprocal could be
/// represented. For this reason, a default implementation that simply
/// always returns `nil` is correct, but conforming types should provide
/// a better implementation if possible.
public var reciprocal: Self? {
return nil
}
// It's always OK to simply fall back on normal arithmetic, and for any
// field with exact arithmetic, this is the correct definition.
@_transparent
public static func _relaxedAdd(_ a: Self, _ b: Self) -> Self {
a + b
}
// It's always OK to simply fall back on normal arithmetic, and for any
// field with exact arithmetic, this is the correct definition.
@_transparent
public static func _relaxedMul(_ a: Self, _ b: Self) -> Self {
a * b
}
}
+23 -8
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2020-2025 Apple Inc. and the Swift Numerics project authors
// Copyright (c) 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
@@ -28,7 +28,8 @@ extension Numeric where Magnitude: FloatingPoint {
/// is not suitable for all use cases.
///
/// Mathematical Properties:
///
/// ------------------------
///
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _reflexive_ for
/// non-exceptional values (such as NaN).
///
@@ -47,10 +48,12 @@ extension Numeric where Magnitude: FloatingPoint {
/// property implements a valid norm.)
///
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _scale invariant_,
/// so long as no underflow or overflow has occurred, and no exceptional
/// so long as no underflow or overflow has occured, and no exceptional
/// value is produced by the scaling.
///
/// See also `isApproximatelyEqual(to:absoluteTolerance:[relativeTolerance:norm:])`.
/// See Also:
/// -------
/// - `isApproximatelyEqual(to:absoluteTolerance:[relativeTolerance:norm:])`
///
/// - Parameters:
///
@@ -95,6 +98,7 @@ extension Numeric where Magnitude: FloatingPoint {
/// where `scale` is `max(self.magnitude, other.magnitude)`.
///
/// Mathematical Properties:
/// ------------------------
///
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:)`
/// is _reflexive_ for non-exceptional values (such as NaN).
@@ -114,7 +118,9 @@ extension Numeric where Magnitude: FloatingPoint {
/// to `a` is _convex_. (Under the assumption that `norm` implements a
/// valid norm, which cannot be checked by this function.)
///
/// See also `isApproximatelyEqual(to:[relativeTolerance:])`.
/// See Also:
/// -------
/// - `isApproximatelyEqual(to:[relativeTolerance:])`
///
/// - Parameters:
///
@@ -164,6 +170,7 @@ extension AdditiveArithmetic {
/// where `scale` is `max(norm(self), norm(other))`.
///
/// Mathematical Properties:
/// ------------------------
///
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:norm:)`
/// is _reflexive_ for non-exceptional values (such as NaN).
@@ -184,8 +191,10 @@ extension AdditiveArithmetic {
/// to `a` is _convex_ (under the assumption that `norm` implements a
/// valid norm, which cannot be checked by this function or a protocol).
///
/// See also `isApproximatelyEqual(to:[relativeTolerance:norm:])` and
/// `isApproximatelyEqual(to:absoluteTolerance:[relativeTolerance:])`.
/// See Also:
/// -------
/// - `isApproximatelyEqual(to:[relativeTolerance:norm:])`
/// - `isApproximatelyEqual(to:absoluteTolerance:[relativeTolerance:])`
///
/// - Parameters:
///
@@ -218,7 +227,7 @@ extension AdditiveArithmetic {
/// norm: \.length
/// )
/// ```
/// (if we used the default norm, `\.magnitude`, we would be testing if
/// (if we used the default norm, `.magnitude`, we would be testing if
/// `z` were inside a square region instead.)
@inlinable
public func isApproximatelyEqual<Magnitude>(
@@ -227,6 +236,12 @@ extension AdditiveArithmetic {
relativeTolerance: Magnitude = 0,
norm: (Self) -> Magnitude
) -> Bool
// TODO: constraint should really be weaker than FloatingPoint,
// but we need to have `isFinite` for it to work correctly with
// floating-point magnitudes in generic contexts, which is the
// most common case. The fix for this is to lift the isFinite
// requirement to Numeric in the standard library, but that's
// source-breaking, so requires an ABI rumspringa.
where Magnitude: FloatingPoint {
assert(
absoluteTolerance >= 0 && absoluteTolerance.isFinite,
+34 -75
View File
@@ -2,13 +2,19 @@
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2020-2025 Apple Inc. and the Swift Numerics project authors
// Copyright (c) 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
//
//===----------------------------------------------------------------------===//
/// A namespace for "augmented arithmetic" operations for types conforming to
/// `Real`.
///
/// Augmented arithmetic refers to a family of algorithms that represent
/// the results of floating-point computations using multiple values such that
/// either the error is minimized or the result is exact.
public enum Augmented { }
extension Augmented {
@@ -22,7 +28,7 @@ extension Augmented {
/// This operation is sometimes called "twoProd" or "twoProduct".
///
/// Edge Cases:
///
/// -
/// - `head` is always the IEEE 754 product `a * b`.
/// - If `head` is not finite, `tail` is unspecified and should not be
/// interpreted as having any meaning (it may be `NaN` or `infinity`).
@@ -33,15 +39,13 @@ extension Augmented {
/// - If `head` is zero, `tail` is also a zero with unspecified sign.
///
/// Postconditions:
///
/// -
/// - If `head` is normal, then `abs(tail) < head.ulp`.
/// Assuming IEEE 754 default rounding, `abs(tail) <= head.ulp/2`.
/// - If both `head` and `tail` are normal, then `a * b` is exactly
/// equal to `head + tail` when computed as real numbers.
@_transparent
public static func product<T:FloatingPoint>(
_ a: T, _ b: T
) -> (head: T, tail: T) {
public static func product<T:Real>(_ a: T, _ b: T) -> (head: T, tail: T) {
let head = a*b
// TODO: consider providing an FMA-less implementation for use when
// targeting platforms without hardware FMA support. This works everywhere,
@@ -52,96 +56,51 @@ extension Augmented {
/// The sum `a + b` represented as an implicit sum `head + tail`.
///
/// - Parameters:
/// - a: The summand with larger magnitude.
/// - b: The summand with smaller magnitude.
///
/// `head` is the correctly rounded value of `a + b`. `tail` is the
/// error from that computation rounded to the closest representable
/// value.
///
/// > Note:
/// > `tail` is guaranteed to be the best approximation to the error of
/// the sum only if `large.magnitude` >= `small.magnitude`. If this is
/// not the case, then `head` is the correctly rounded sum, but `tail`
/// is not guaranteed to be the exact error. If you do not know a priori
/// how the magnitudes of `a` and `b` compare, you likely want to use
/// ``sum(_:_:)`` instead.
/// Unlike `Augmented.product(a, b)`, the rounding error of a sum can
/// never underflow. However, it may not be exactly representable when
/// `a` and `b` differ widely in magnitude.
///
/// Unlike ``product(_:_:)``, the rounding error of `sum` never underflows.
/// This operation is sometimes called "fastTwoSum".
///
/// This operation is sometimes called ["fastTwoSum"].
/// - Parameters:
/// - a: The summand with larger magnitude.
/// - b: The summand with smaller magnitude.
///
/// > Note:
/// > Classical fastTwoSum does not work when `radix` is 10. This function
/// will fall back on another algorithm for decimal floating-point types
/// to ensure correct results.
/// Preconditions:
/// -
/// - `large.magnitude` must not be smaller than `small.magnitude`.
/// They may be equal, or one or both may be `NaN`.
/// This precondition is only enforced in debug builds.
///
/// Edge Cases:
///
/// -
/// - `head` is always the IEEE 754 sum `a + b`.
/// - If `head` is not finite, `tail` is unspecified and should not be
/// interpreted as having any meaning (it may be `NaN` or `infinity`).
///
/// Postconditions:
///
/// -
/// - If `head` is normal, then `abs(tail) < head.ulp`.
/// Assuming IEEE 754 default rounding, `abs(tail) <= head.ulp/2`.
///
/// ["fastTwoSum"]: https://en.wikipedia.org/wiki/2Sum
@_transparent
public static func sum<T: FloatingPoint>(
large a: T, small b: T
) -> (head: T, tail: T) {
// Fall back on 2Sum if radix != 2. Future implementations might use an
// cheaper algorithm specialized for decimal FP, but must deliver a
// correct result if the preconditions are satisfied.
guard T.radix == 2 else { return sum(a, b) }
// Fast2Sum:
public static func sum<T:Real>(large a: T, small b: T) -> (head: T, tail: T) {
assert(!(b.magnitude > a.magnitude))
let head = a + b
let tail = a - head + b
return (head, tail)
}
/// The sum `a + b` represented as an implicit sum `head + tail`.
///
/// `head` is the correctly rounded value of `a + b`. `tail` is the
/// error from that computation rounded to the closest representable
/// value.
///
/// Unlike ``sum(large:small:)``, the magnitude of the summands does not
/// matter. If you know statically that `a.magnitude >= b.magnitude`, you
/// should use ``sum(large:small:)``. If you do not have such a static
/// bound, you should use this function instead.
///
/// Unlike ``product(_:_:)``, the rounding error of `sum` never underflows.
///
/// This operation is sometimes called ["twoSum"].
///
/// - Parameters:
/// - a: One of the summands
/// - b: The other summand
///
/// Edge Cases:
///
/// - `head` is always the IEEE 754 sum `a + b`.
/// - If `head` is not finite, `tail` is unspecified and should not be
/// interpreted as having any meaning (it may be `NaN` or `infinity`).
///
/// Postconditions:
///
/// - If `head` is normal, then `abs(tail) < head.ulp`.
/// Assuming IEEE 754 default rounding, `abs(tail) <= head.ulp/2`.
///
/// ["twoSum"]: https://en.wikipedia.org/wiki/2Sum
@_transparent
public static func sum<T: FloatingPoint>(
_ a: T, _ b: T
) -> (head: T, tail: T) {
let head = a + b
let x = head - b
let y = head - x
let tail = (a - x) + (b - y)
return (head, tail)
@available(*, deprecated, renamed: "product")
public static func twoProdFMA<T:Real>(_ a: T, _ b: T) -> (head: T, tail: T) {
product(a, b)
}
@available(*, deprecated, renamed: "sum(large:small:)")
public static func fastTwoSum<T:Real>(_ a: T, _ b: T) -> (head: T, tail: T) {
sum(large: a, small: b)
}
}
+1 -2
View File
@@ -17,8 +17,7 @@ add_library(RealModule
Float16+Real.swift
Float80+Real.swift
Real.swift
RealFunctions.swift
RelaxedArithmetic.swift)
RealFunctions.swift)
set_target_properties(RealModule PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
target_link_libraries(RealModule PUBLIC
@@ -1,228 +0,0 @@
# Approximate Equality
Test whether two values agree within a specified tolerance.
## Overview
In numerical computing, mathematical equality often diverges from computed
equality. Rounding in floating-point arithmetic is one common cause, but many
nontrivial numerical algorithms also have inherent truncation or discretization
errors, and empirical measurements carry uncertainty to begin with. In these
scenarios, exact equality (`==`) may be too strict or inappropriate, and an
approximate equality comparison is needed instead. Conversely, exact equality
remains entirely appropriate when checking for identical values, sentinel states,
or integers.
`RealModule` provides a family of `isApproximatelyEqual` methods that test
whether two values are within a tolerance of one another. They are available
on any `Numeric` type whose `Magnitude` is a `FloatingPoint` type (including
`Float`, `Double`, and `Complex`), and a more general form is available on any
`AdditiveArithmetic` type for which you can supply a norm.
```swift
import Numerics
let x = 0.1 + 0.2
x == 0.3 // false
x.isApproximatelyEqual(to: 0.3) // true
```
### Comparing non-Numeric types with a custom norm
The approximate equality API is not limited to scalar numbers or `Numeric`
types. Any type conforming to `AdditiveArithmetic` can be compared once you
supply a suitable norm function mapping differences to a `FloatingPoint`
magnitude.
For example, consider a 2D geometric vector or point type representing spatial
displacements:
```swift
struct Vector2D: AdditiveArithmetic, Equatable {
var x: Double
var y: Double
static var zero: Vector2D {
Vector2D(x: 0, y: 0)
}
static func + (lhs: Vector2D, rhs: Vector2D) -> Vector2D {
Vector2D(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
static func - (lhs: Vector2D, rhs: Vector2D) -> Vector2D {
Vector2D(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
}
// Compare vectors using the Euclidean distance (L2 norm):
let v1 = Vector2D(x: 1.0, y: 2.0)
let v2 = Vector2D(x: 1.000000001, y: 1.999999999)
let areClose = v1.isApproximatelyEqual(
to: v2,
absoluteTolerance: 1e-6,
norm: { v in (v.x * v.x + v.y * v.y).squareRoot() }
)
// areClose == true
```
Because `Vector2D` is not `Numeric` (it does not define multiplication of
vectors to produce a vector), it cannot use the standard `Numeric.isApproximatelyEqual`
overload. However, because vector subtraction forms a difference vector in an
additive space, the general `AdditiveArithmetic` overload evaluates the custom
norm directly.
### Choosing a tolerance
The simplest method uses a _relative_ tolerance:
```swift
public func isApproximatelyEqual(
to other: Self,
relativeTolerance: Magnitude = Magnitude.ulpOfOne.squareRoot(),
norm: (Self) -> Magnitude = \.magnitude
) -> Bool
```
Two finite values compare equal when
```
norm(self - other) <= relativeTolerance * scale
```
where `scale` is `max(norm(self), norm(other), .leastNormalMagnitude)`.
Because the bound grows with the size of the operands, a single relative
tolerance works across a wide range of magnitudes.
The default tolerance is `.ulpOfOne.squareRoot()`, which corresponds to
expecting about half of the available digits in the result to be correct. This
is the usual rule of thumb in numerical analysis when you have no other
information about the computation, but it is not appropriate for every use
case, so you should pass an explicit value when you can estimate how much error
your computation introduces.
#### Absolute versus relative tolerance
A relative tolerance scales with the magnitude of the operands, making it
effective across numbers of very small or very large scale. However, a pure
relative tolerance fails when comparing against zero or numbers much smaller
than the surrounding computation, because `scale` approaches zero and shrinks
the allowable difference to near zero.
To handle values near zero, use the overload that also accepts an _absolute_
tolerance:
```swift
public func isApproximatelyEqual(
to other: Self,
absoluteTolerance: Magnitude,
relativeTolerance: Magnitude = 0
) -> Bool
```
Two finite values compare equal when _either_ the absolute or the relative
bound is satisfied:
```
(self - other).magnitude <= absoluteTolerance
```
or
```
(self - other).magnitude <= relativeTolerance * scale
```
where `scale` is `max(self.magnitude, other.magnitude)`.
When choosing values:
- Use **relative tolerance** when the allowed error is proportional to the
magnitude of the values being computed (e.g. general floating-point arithmetic).
- Use **absolute tolerance** when values can be near zero, or when the error
is independent of the scale of the inputs (e.g. fixed measurement resolution).
- Supplying both allows the absolute tolerance to govern comparisons near
zero, while the relative tolerance takes over once values grow beyond
`absoluteTolerance / relativeTolerance`.
Setting `absoluteTolerance == relativeTolerance` is typically appropriate only
when values are expected to lie on an integral or unit-spaced grid due to
algorithmic considerations (where `1.0` represents the base unit scale). For
general computations, the two tolerances should be chosen independently based on
the scale of the problem and the expected precision.
### Special values
The comparison follows the same conventions as `FloatingPoint`:
```swift
Double.nan.isApproximatelyEqual(to: .nan) // false
Double.infinity.isApproximatelyEqual(to: .infinity) // true
(0.0).isApproximatelyEqual(to: -0.0) // true
```
A NaN is never approximately equal to anything, including itself, and a finite
value is never approximately equal to an infinity. Equal values always compare
approximately equal regardless of the tolerance, so infinities compare equal to
themselves and `+0` compares equal to `-0`.
### Comparing other types with a custom norm
The methods above measure the difference between two values using the
`.magnitude` property. Sometimes you want to use a different
[norm](https://en.wikipedia.org/wiki/Norm_(mathematics)). The most general
overload, defined on `AdditiveArithmetic`, lets you supply one:
```swift
public func isApproximatelyEqual<Magnitude>(
to other: Self,
absoluteTolerance: Magnitude,
relativeTolerance: Magnitude = 0,
norm: (Self) -> Magnitude
) -> Bool
where Magnitude: FloatingPoint
```
#### Complex magnitude vs other norms
For complex numbers, the default norm is `\.magnitude`, which computes the
infinity-norm (`max(abs(real), abs(imaginary))`).
A major numerical advantage of `\.magnitude` for complex values is that it is
finite and non-zero for any finite non-zero value:
- Unlike Euclidean length (`\.length`, $\sqrt{x^2 + y^2}$), which can overflow
to infinity if $x^2 + y^2$ exceeds the maximum representable finite value or
underflow if both components are tiny, `\.magnitude` never overflows or underflows
for finite numbers.
- It avoids intermediate squaring, square roots, or the complex scaling logic of
`hypot`, making it robust even when handling very poorly scaled values.
If you specifically need to test whether a complex number lies inside a circular
disk of radius `0.001` centered at `1 + 0i` rather than a square box, you can
pass the Euclidean length as the norm:
```swift
import ComplexModule
z.isApproximatelyEqual(
to: 1,
absoluteTolerance: 0.001,
norm: \.length
)
```
## Mathematical properties
For any fixed tolerance, approximate equality is _reflexive_ on
non-exceptional values and _symmetric_: if `a` is approximately equal to `b`,
then `b` is approximately equal to `a`.
It is **not transitive**. `a` can be approximately equal to `b`, and `b` to
`c`, while `a` and `c` differ by more than the tolerance. Approximate equality
is therefore **not** an equivalence relation, even when restricted to
non-exceptional values. For this reason you must not use it to implement a
conformance to `Equatable`: doing so would violate the invariants that generic
code written against `Equatable` relies on.
For any point `a`, the set of values that compare approximately equal to `a`
is _convex_ (under the assumption that `norm` implements a valid norm).
@@ -1,37 +0,0 @@
# ``Augmented``
A namespace for a family of algorithms that compute the results of floating-
point arithmetic using multiple values such that either the error is minimized
or the result is exact.
## Overview
Consider multiplying two Doubles. A Double has 53 significand bits, so their
product could be up to 106 bits wide before it is rounded to a Double result.
So up to 53 of those 106 bits will be "lost" in that process:
```swift
let a = 1.0 + .ulpOfOne // 1 + 2⁻⁵²
let b = 1.0 - .ulpOfOne // 1 - 2⁻⁵²
let c = a * b // 1 - 2⁻¹⁰⁴ before rounding, rounds to 1.0
```
Sometimes it is necessary to preserve some or all of those low-order bits;
maybe a subsequent subtraction cancels most of the high-order bits, and so
the low-order part of the product suddenly becomes significant:
```swift
let result = 1 - c // exactly zero, but "should be" 2⁻¹⁰⁴
```
Augmented arithmetic is a building-block that library writers can use to
handle cases like this more carefully. For the example above, one might
compute:
```swift
let (head, tail) = Augmented.product(a,b)
```
`head` is then 1.0 and `tail` is -2⁻¹⁰⁴, so no information has been lost.
Of course, the result is now split across two Doubles instead of one, but the
information in `tail` can be carried forward into future computations.
@@ -1,68 +0,0 @@
# ``ElementaryFunctions``
A type that has elementary functions (`sin`, `cos`, etc.) available.
## Overview
An ["elementary function"][elfn] is a function built up from powers, roots,
exponentials, logarithms, trigonometric functions (sin, cos, tan) and
their inverses, and the hyperbolic functions (sinh, cosh, tanh) and their
inverses.
Conformance to this protocol means that all of these building blocks are
available as static functions on the type.
```swift
let x: Float = 1
let y = Float.sin(x) // 0.84147096
```
`ElementaryFunctions` conformance implies `AdditiveArithmetic`, so addition
and subtraction and the `zero` property are also available.
``RealFunctions`` refines this protocol and adds additional functions that
are primarily used with real numbers, such as ``RealFunctions/atan2(y:x:)``
and ``RealFunctions/exp10(_:)``.
``Real`` conforms to `RealFunctions` and `FloatingPoint`, and is the
protocol that you will use most often for generic code.
## Topics
There are a few families of functions defined by `ElementaryFunctions`:
### Exponential functions
- ``exp(_:)``
- ``expMinusOne(_:)``
### Logarithmetic functions
- ``log(_:)``
- ``log(onePlus:)``
### Power and root functions:
- ``pow(_:_:)-9imp6``
- ``pow(_:_:)-2qmul``
- ``sqrt(_:)``
- ``root(_:_:)``
### Trigonometric functions
- ``cos(_:)``
- ``sin(_:)``
- ``tan(_:)``
### Inverse trigonometric functions
- ``acos(_:)``
- ``asin(_:)``
- ``atan(_:)``
### Hyperbolic functions
- ``cosh(_:)``
- ``sinh(_:)``
- ``tanh(_:)``
### Inverse hyperbolic functions
- ``acosh(_:)``
- ``asinh(_:)``
- ``atanh(_:)``
[elfn]: http://en.wikipedia.org/wiki/Elementary_function
@@ -1,27 +0,0 @@
# ``RealFunctions``
A type that extends ``ElementaryFunctions`` with additional operations that
are primarily used with real numbers.
## Topics
### Exponential functions
- ``exp2(_:)``
- ``exp10(_:)``
### Logarithmetic functions
- ``log2(_:)``
- ``log10(_:)``
### Plane geometry
- ``atan2(y:x:)``
- ``hypot(_:_:)``
### Gamma function
- ``gamma(_:)``
- ``logGamma(_:)``
- ``signGamma(_:)``
### Error function
- ``erf(_:)``
- ``erfc(_:)``
@@ -1,32 +0,0 @@
# ``RealModule``
Extensions on the Swift standard library that provide functionality for
floating-point types.
## Overview
``RealModule`` provides four protocols that extend the standard library's
numeric protocol hierarchy: AlgebraicField, ElementaryFunctions,
RealFunctions, and Real.
Types conforming to AlgebraicField represent
[fields](https://en.wikipedia.org/wiki/Field_(mathematics)). These are the
mathematical structures that typically form the elements of vectors and
matrices, so this protocol is appropriate for writing generic code to do
linear-algebra-type operations.
ElementaryFunctions provides bindings for the "math functions": the logarithm
and exponential functions, sine, cosine and tangent as well as their inverses,
and other functions that you may be familiar with from trigonometry and
calculus. RealFunctions refines ElementaryFunctions and provides functions that
are primarily used with the real numbers, such as atan2, erf and gamma, and
the base-2 and -10 logarithm and exponential funtions.
The Real protocol is a convenient name for the intersection of `FloatingPoint`,
`RealFunctions`, and `AlgebraicField`; this is the protocol that you are most
likely to want to constrain to when writing generic "math" code that works
with floating-point types.
``RealModule`` also provides `isApproximatelyEqual` methods for comparing
floating-point values up to a tolerance, which is almost always what you want
instead of an exact `==` comparison. See <doc:ApproximateEquality> for details.
@@ -1,53 +0,0 @@
# ``Relaxed``
A namespace for a family of operations that "relax" the usual rules for
floating-point to allow reassociation of arithmetic and FMA formation.
## Overview
Because of rounding, and the arithmetic rules for infinity and NaN values,
floating-point addition and multiplication are not associative:
```swift
let ε = Double.leastNormalMagnitude
let sumLeft = (-1 + 1) + ε // 0 + ε = ε
let sumRight = -1 + (1 + ε) // -1 + 1 = 0
let ∞ = Double.infinity
let productLeft = (ε * ε) * ∞ // 0 * ∞ = .nan
let productRight = ε * (ε * ∞) // ε * ∞ = ∞
```
For some algorithms, the distinction between these results is incidental; for
some others it is critical to their correct function. Because of this,
compilers cannot freely change the order of reductions, which prevents some
important optimizations: extraction of instruction-level parallelism and
vectorization.
If you know that you are in a case where the order of elements being summed
or multiplied is incidental, the Relaxed operations give you a mechanism
to communicate that to the compiler and unlock these optimizations. For
example, consider the following two functions:
```swift
func sum(array: [Float]) -> Float {
array.reduce(0, +)
}
func relaxedSum(array: [Float]) -> Float {
array.reduce(0, Relaxed.sum)
}
```
when called on an array with 1000 elements in a Release build, `relaxedSum`
is about 8x faster than `sum` on Apple M2, with a similar speedup on Intel
processors, without the need for any unsafe code or flags.
### multiplyAdd
In addition to `sum` and `product`, `Relaxed` provides the
``multiplyAdd(_:_:_:)`` operation, which communciates to the compiler that
it is allowed to replace separate multiply and add operations with a single
_fused multiply-add_ instruction if its cost model indicates that it would
be advantageous to do so. When targeting processors that support this
instruction, this may be a significant performance advantage.
+10 -15
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
// 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
@@ -107,14 +107,14 @@ extension Double: Real {
libm_exp2(x)
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
@_transparent
public static func exp10(_ x: Double) -> Double {
libm_exp10(x)
}
#endif
#endif
#if os(macOS) && arch(x86_64)
#if os(macOS) && arch(x86_64)
// Workaround for macOS bug (<rdar://problem/56844150>) where hypot can
// overflow for values very close to the overflow boundary of the naive
// algorithm. Since this is only for macOS, we can just unconditionally
@@ -125,12 +125,12 @@ extension Double: Real {
let y80 = Float80(y)
return Double(Float80.sqrt(x80*x80 + y80*y80))
}
#else
#else
@_transparent
public static func hypot(_ x: Double, _ y: Double) -> Double {
libm_hypot(x, y)
}
#endif
#endif
@_transparent
public static func gamma(_ x: Double) -> Double {
@@ -212,21 +212,16 @@ extension Double: Real {
libm_atan2(y, x)
}
#if !os(Windows)
#if !os(Windows)
@_transparent
public static func logGamma(_ x: Double) -> Double {
var dontCare: Int32 = 0
return libm_lgamma(x, &dontCare)
}
#endif
#endif
@_transparent
public static func _relaxedAdd(_ a: Double, _ b: Double) -> Double {
_numerics_relaxed_add(a, b)
}
@_transparent
public static func _relaxedMul(_ a: Double, _ b: Double) -> Double {
_numerics_relaxed_mul(a, b)
public static func _mulAdd(_ a: Double, _ b: Double, _ c: Double) -> Double {
_numerics_muladd(a, b, c)
}
}
+149 -40
View File
@@ -2,19 +2,65 @@
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
// 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
//
//===----------------------------------------------------------------------===//
/// A type that has elementary functions available.
///
/// An ["elementary function"][elfn] is a function built up from powers, roots,
/// exponentials, logarithms, trigonometric functions (sin, cos, tan) and
/// their inverses, and the hyperbolic functions (sinh, cosh, tanh) and their
/// inverses.
///
/// Conformance to this protocol means that all of these building blocks are
/// available as static functions on the type.
///
/// ```swift
/// let x: Float = 1
/// let y = Float.sin(x) // 0.84147096
/// ```
///
/// There are three broad families of functions defined by
/// `ElementaryFunctions`:
/// - Exponential, trigonometric, and hyperbolic functions:
/// `exp`, `expMinusOne`, `cos`, `sin`, `tan`, `cosh`, `sinh`, and `tanh`.
/// - Logarithmic, inverse trigonometric, and inverse hyperbolic functions:
/// `log`, `log(onePlus:)`, `acos`, `asin`, `atan`, `acosh`, `asinh`, and
/// `atanh`.
/// - Power and root functions:
/// `pow`, `sqrt`, and `root`.
///
/// `ElementaryFunctions` conformance implies `AdditiveArithmetic`, so addition
/// and subtraction and the `.zero` property are also available.
///
/// There are two other protocols that you are more likely to want to use
/// directly:
///
/// `RealFunctions` refines `ElementaryFunctions` and includes
/// additional functions specific to real number types.
///
/// `Real` conforms to `RealFunctions` and `FloatingPoint`, and is the
/// protocol that you will want to use most often for generic code.
///
/// See Also:
/// -
/// - `RealFunctions`
/// - `Real`
///
/// [elfn]: http://en.wikipedia.org/wiki/Elementary_function
public protocol ElementaryFunctions: AdditiveArithmetic {
/// The [exponential function][wiki] e^x whose base `e` is the base of the
/// natural logarithm.
///
/// For types that conform to ``RealFunctions`` see
/// ``RealFunctions/exp2(_:)`` and ``RealFunctions/exp10(_:)``.
/// See also:
/// -
/// - `expMinusOne()`
/// - `exp2()` (for types conforming to `RealFunctions`)
/// - `exp10()` (for types conforming to `RealFunctions`)
///
/// [wiki]: https://en.wikipedia.org/wiki/Exponential_function
static func exp(_ x: Self) -> Self
@@ -25,7 +71,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// catastrophic cancellation and the result will not have full accuracy.
/// The `.expMinusOne(x)` function gives you a means to address this problem.
///
/// As an example, consider the expression `(x + 1) * .exp(x) - 1`. When `x`
/// As an example, consider the expression `(x + 1)*exp(x) - 1`. When `x`
/// is smaller than `.ulpOfOne`, this expression evaluates to `0.0`, when it
/// should actually round to `2*x`. We can get a full-accuracy result by
/// using the following instead:
@@ -36,8 +82,11 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// This re-written expression delivers an accurate result for all values
/// of `x`, not just for small values.
///
/// For types that conform to ``RealFunctions`` see
/// ``RealFunctions/exp2(_:)`` and ``RealFunctions/exp10(_:)``.
/// See also:
/// -
/// - `exp()`
/// - `exp2()` (for types conforming to `RealFunctions`)
/// - `exp10()` (for types conforming to `RealFunctions`)
static func expMinusOne(_ x: Self) -> Self
/// The [hyperbolic cosine][wiki] of `x`.
@@ -47,7 +96,11 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// 2
/// ```
///
/// See also ``acosh(_:)``.
/// See also:
/// -
/// - `sinh()`
/// - `tanh()`
/// - `acosh()`
///
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
static func cosh(_ x: Self) -> Self
@@ -59,7 +112,11 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// 2
/// ```
///
/// See also ``asinh(_:)``.
/// See also:
/// -
/// - `cosh()`
/// - `tanh()`
/// - `asinh()`
///
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
static func sinh(_ x: Self) -> Self
@@ -71,7 +128,11 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// cosh(x)
/// ```
///
/// See also ``atanh(_:)``.
/// See also:
/// -
/// - `cosh()`
/// - `sinhh()`
/// - `atanh()`
///
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
static func tanh(_ x: Self) -> Self
@@ -80,7 +141,11 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
///
/// For real types, `x` may be interpreted as an angle measured in radians.
///
/// See also ``acos(_:)``.
/// See also:
/// -
/// - `sin()`
/// - `tan()`
/// - `acos()`
///
/// [wiki]: https://en.wikipedia.org/wiki/Cosine
static func cos(_ x: Self) -> Self
@@ -90,7 +155,11 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
///
/// For real types, `x` may be interpreted as an angle measured in radians.
///
/// See also ``asin(_:)``.
/// See also:
/// -
/// - `cos()`
/// - `tan()`
/// - `asin()`
///
/// [wiki]: https://en.wikipedia.org/wiki/Sine
static func sin(_ x: Self) -> Self
@@ -99,54 +168,75 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
///
/// For real types, `x` may be interpreted as an angle measured in radians.
///
/// See also ``atan(_:)``.
///
/// See also:
/// -
/// - `cos()`
/// - `sin()`
/// - `atan()`
/// - `atan2(y:x:)` (for types conforming to `RealFunctions`)
/// ```
/// sin(x)
/// tan(x) = --------
/// cos(x)
/// ```
/// [wiki]: https://en.wikipedia.org/wiki/Tangent
static func tan(_ x: Self) -> Self
/// The [natural logarithm][wiki] of `x`.
///
/// For types that conform to ``RealFunctions`` see also
/// ``RealFunctions/log2(_:)`` and ``RealFunctions/log10(_:)``.
/// See also:
/// -
/// - `log(onePlus:)`
/// - `log2()` (for types conforming to `RealFunctions`)
/// - `log10()` (for types conforming to `RealFunctions`)
///
/// [wiki]: https://en.wikipedia.org/wiki/Logarithm
static func log(_ x: Self) -> Self
/// log(1 + x), computed in such a way as to maintain accuracy for small x.
///
/// For types that conform to ``RealFunctions`` see also
/// ``RealFunctions/log2(_:)`` and ``RealFunctions/log10(_:)``.
/// See also:
/// -
/// - `log()`
/// - `log2()` (for types conforming to `RealFunctions`)
/// - `log10()` (for types conforming to `RealFunctions`)
static func log(onePlus x: Self) -> Self
/// The [inverse hyperbolic cosine][wiki] of `x`.
///
/// ```
/// cosh(acosh(x)) ≅ x
/// ```
///
/// See also ``cosh(_:)``.
/// See also:
/// -
/// - `asinh()`
/// - `atanh()`
/// - `cosh()`
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
static func acosh(_ x: Self) -> Self
/// The [inverse hyperbolic sine][wiki] of `x`.
///
/// ```
/// sinh(asinh(x)) ≅ x
/// ```
///
/// See also ``sinh(_:)``.
/// See also:
/// -
/// - `acosh()`
/// - `atanh()`
/// - `sinh()`
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
static func asinh(_ x: Self) -> Self
/// The [inverse hyperbolic tangent][wiki] of `x`.
///
/// ```
/// tanh(atanh(x)) ≅ x
/// ```
///
/// See also ``tanh(_:)``.
/// See also:
/// -
/// - `acosh()`
/// - `asinh()`
/// - `tanh()`
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
static func atanh(_ x: Self) -> Self
@@ -155,12 +245,14 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
///
/// For real types, the result may be interpreted as an angle measured in
/// radians.
///
/// ```
/// cos(acos(x)) ≅ x
/// ```
///
/// See also ``cos(_:)``.
/// See also:
/// -
/// - `asin()`
/// - `atan()`
/// - `cos()`
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
static func acos(_ x: Self) -> Self
@@ -169,12 +261,14 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
///
/// For real types, the result may be interpreted as an angle measured in
/// radians.
///
/// ```
/// sin(asin(x)) ≅ x
/// ```
///
/// See also ``sin(_:)``.
/// See also:
/// -
/// - `acos()`
/// - `atan()`
/// - `sin()`
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
static func asin(_ x: Self) -> Self
@@ -183,14 +277,15 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
///
/// For real types, the result may be interpreted as an angle measured in
/// radians.
///
/// ```
/// tan(atan(x)) ≅ x
/// ```
///
/// See also ``tan(_:)``.
/// For types that conform to ``RealFunctions``, you will sometimes want
/// to use ``RealFunctions/atan2(y:x:)`` instead.
/// See also:
/// -
/// - `acos()`
/// - `asin()`
/// - `atan2()` (for types conforming to `RealFunctions`)
/// - `tan()`
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
static func atan(_ x: Self) -> Self
@@ -202,9 +297,10 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// In particular, this means that if `x` and `y` are both zero, `pow(x,y)`
/// is `nan` for real types and `infinity` for complex types, rather than 1.
///
/// There is also
/// <doc:/documentation/RealModule/ElementaryFunctions/pow(_:_:)-9imp6>,
/// whose behavior is defined in terms of repeated multiplication.
/// There is also a `pow(_:Self,_:Int)` overload, whose behavior is defined
/// in terms of repeated multiplication, and hence returns 1 for this case.
///
/// See also `sqrt()` and `root()`.
static func pow(_ x: Self, _ y: Self) -> Self
/// `x` raised to the nth power.
@@ -212,13 +308,26 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// The edge-cases of this function are defined in terms of repeated
/// multiplication or division, rather than exp(n log x). In particular,
/// `Float.pow(0, 0)` is 1.
///
/// See also `sqrt()` and `root()`.
static func pow(_ x: Self, _ n: Int) -> Self
/// The [square root][wiki] of `x`.
///
/// See also:
/// -
/// - `pow()`
/// - `root()`
///
/// [wiki]: https://en.wikipedia.org/wiki/Square_root
static func sqrt(_ x: Self) -> Self
/// The nth root of `x`.
///
/// See also:
/// -
/// - `pow()`
/// - `sqrt()`
///
static func root(_ x: Self, _ n: Int) -> Self
}
+2 -7
View File
@@ -194,12 +194,7 @@ extension Float: Real {
#endif
@_transparent
public static func _relaxedAdd(_ a: Float, _ b: Float) -> Float {
_numerics_relaxed_addf(a, b)
}
@_transparent
public static func _relaxedMul(_ a: Float, _ b: Float) -> Float {
_numerics_relaxed_mulf(a, b)
public static func _mulAdd(_ a: Float, _ b: Float, _ c: Float) -> Float {
_numerics_muladdf(a, b, c)
}
}
+162 -11
View File
@@ -11,8 +11,9 @@
import _NumericsShims
// Float16 is only available on macOS when targeting arm64.
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
// When building with a Swift 5.4 or later toolchain, Float16 is available on
// non-x86 macOS from 11.0 onward.
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
extension Float16: Real {
@@ -172,19 +173,169 @@ extension Float16: Real {
Float16(.logGamma(Float(x)))
}
#endif
#if !arch(wasm32)
// WASM doesn't have _Float16 on the C side, so we can't define the C hooks
// that these use. TODO: implement these as Swift builtins instead.
}
// When building with older Swift toolchains for macOS, Float16 is not
// available. We will drop support for these older toolchains at some
// future point and remove this duplication.
#elseif swift(>=5.3) && !(os(macOS) || targetEnvironment(macCatalyst))
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, *)
extension Float16: Real {
@_transparent
public static func _relaxedAdd(_ a: Float16, _ b: Float16) -> Float16 {
_numerics_relaxed_addf16(a, b)
public static func cos(_ x: Float16) -> Float16 {
Float16(.cos(Float(x)))
}
@_transparent
public static func _relaxedMul(_ a: Float16, _ b: Float16) -> Float16 {
_numerics_relaxed_mulf16(a, b)
public static func sin(_ x: Float16) -> Float16 {
Float16(.sin(Float(x)))
}
@_transparent
public static func tan(_ x: Float16) -> Float16 {
Float16(.tan(Float(x)))
}
@_transparent
public static func acos(_ x: Float16) -> Float16 {
Float16(.acos(Float(x)))
}
@_transparent
public static func asin(_ x: Float16) -> Float16 {
Float16(.asin(Float(x)))
}
@_transparent
public static func atan(_ x: Float16) -> Float16 {
Float16(.atan(Float(x)))
}
@_transparent
public static func cosh(_ x: Float16) -> Float16 {
Float16(.cosh(Float(x)))
}
@_transparent
public static func sinh(_ x: Float16) -> Float16 {
Float16(.sinh(Float(x)))
}
@_transparent
public static func tanh(_ x: Float16) -> Float16 {
Float16(.tanh(Float(x)))
}
@_transparent
public static func acosh(_ x: Float16) -> Float16 {
Float16(.acosh(Float(x)))
}
@_transparent
public static func asinh(_ x: Float16) -> Float16 {
Float16(.asinh(Float(x)))
}
@_transparent
public static func atanh(_ x: Float16) -> Float16 {
Float16(.atanh(Float(x)))
}
@_transparent
public static func exp(_ x: Float16) -> Float16 {
Float16(.exp(Float(x)))
}
@_transparent
public static func expMinusOne(_ x: Float16) -> Float16 {
Float16(.expMinusOne(Float(x)))
}
@_transparent
public static func log(_ x: Float16) -> Float16 {
Float16(.log(Float(x)))
}
@_transparent
public static func log(onePlus x: Float16) -> Float16 {
Float16(.log(onePlus: Float(x)))
}
@_transparent
public static func erf(_ x: Float16) -> Float16 {
Float16(.erf(Float(x)))
}
@_transparent
public static func erfc(_ x: Float16) -> Float16 {
Float16(.erfc(Float(x)))
}
@_transparent
public static func exp2(_ x: Float16) -> Float16 {
Float16(.exp2(Float(x)))
}
@_transparent
public static func exp10(_ x: Float16) -> Float16 {
Float16(.exp10(Float(x)))
}
@_transparent
public static func hypot(_ x: Float16, _ y: Float16) -> Float16 {
if x.isInfinite || y.isInfinite { return .infinity }
let xf = Float(x)
let yf = Float(y)
return Float16(.sqrt(xf*xf + yf*yf))
}
@_transparent
public static func gamma(_ x: Float16) -> Float16 {
Float16(.gamma(Float(x)))
}
@_transparent
public static func log2(_ x: Float16) -> Float16 {
Float16(.log2(Float(x)))
}
@_transparent
public static func log10(_ x: Float16) -> Float16 {
Float16(.log10(Float(x)))
}
@_transparent
public static func pow(_ x: Float16, _ y: Float16) -> Float16 {
Float16(.pow(Float(x), Float(y)))
}
@_transparent
public static func pow(_ x: Float16, _ n: Int) -> Float16 {
// Float16 is simpler than Float or Double, because the range of
// "interesting" exponents is pretty small; anything outside of
// -22707 ... 34061 simply overflows or underflows for every
// x that isn't zero or one. This whole range is representable
// as Float, so we can just use powf as long as we're a little
// bit (get it?) careful to preserve parity.
let clamped = min(max(n, -0x10000), 0x10000) | (n & 1)
return Float16(libm_powf(Float(x), Float(clamped)))
}
@_transparent
public static func root(_ x: Float16, _ n: Int) -> Float16 {
Float16(.root(Float(x), n))
}
@_transparent
public static func atan2(y: Float16, x: Float16) -> Float16 {
Float16(.atan2(y: Float(y), x: Float(x)))
}
#if !os(Windows)
@_transparent
public static func logGamma(_ x: Float16) -> Float16 {
Float16(.logGamma(Float(x)))
}
#endif
}
-10
View File
@@ -165,15 +165,5 @@ extension Float80: Real {
var dontCare: Int32 = 0
return libm_lgammal(x, &dontCare)
}
@_transparent
public static func _relaxedAdd(_ a: Float80, _ b: Float80) -> Float80 {
_numerics_relaxed_addl(a, b)
}
@_transparent
public static func _relaxedMul(_ a: Float80, _ b: Float80) -> Float80 {
_numerics_relaxed_mull(a, b)
}
}
#endif
-21
View File
@@ -68,30 +68,9 @@ This gives us an implementation that works for `Float`, `Double`, and `Float80`
When new basic floating-point types are added to Swift, like `Float16` or `Float128`, it will work for them as well.
Not having this protocol is a significant missing feature for numerical computing in Swift, and I'm really looking forward to seeing what people do with it.
## Approximate equality
`RealModule` provides a family of `isApproximatelyEqual` methods that test
whether two values agree up to a relative or absolute tolerance:
```swift
import Numerics
let x = 0.1 + 0.2
x == 0.3 // false
x.isApproximatelyEqual(to: 0.3) // true
```
These methods are available on any `Numeric` type whose `Magnitude` is a
`FloatingPoint` type, with a more general form on `AdditiveArithmetic` that
takes a custom norm.
See the [Approximate Equality][ApproximateEquality] article for a discussion of
how to choose a tolerance, how special values are handled, and why approximate
equality must not be used to implement `Equatable`.
### Dependencies:
- The C standard math library (`libm`) via the `_NumericsShims` target.
[ApproximateEquality]: Documentation.docc/ApproximateEquality.md
[ErrorFunction]: https://en.wikipedia.org/wiki/Error_function
[GammaFunction]: https://en.wikipedia.org/wiki/Gamma_function
[SE-0246]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0246-mathable.md
+23 -16
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
// 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
@@ -23,25 +23,30 @@
/// return 1/(1 + .exp(-x))
/// }
/// ```
/// See also `ElementaryFunctions`, `RealFunctions` and `AlgebraicField`.
public protocol Real: FloatingPoint, RealFunctions, AlgebraicField { }
/// See Also:
/// -
/// - `ElementaryFunctions`
/// - `RealFunctions`
/// - `AlgebraicField`
public protocol Real: FloatingPoint, RealFunctions, AlgebraicField {
}
// While `Real` does not provide any additional customization points,
// it does allow us to default the implementation of a few operations,
// and also provides `signGamma`.
extension Real {
// Most math libraries do not provide exp10, so we need a default
// implementation. This is not a great one (if the underlying math
// library does not have a sub-ulp accurate pow, this will not get
// exact powers of ten right), but suffices in the short term.
// implementation.
@_transparent
public static func exp10(_ x: Self) -> Self {
pow(10, x)
return pow(10, x)
}
/// cos(x) - 1, computed in such a way as to maintain accuracy for small x.
///
/// See also ``ElementaryFunctions/expMinusOne(_:)``.
/// See also:
/// -
/// - `ElementaryFunctions.expMinusOne()`
@_transparent
public static func cosMinusOne(_ x: Self) -> Self {
let sinxOver2 = sin(x/2)
@@ -91,16 +96,16 @@ extension Real {
@_transparent
public static func sqrt(_ x: Self) -> Self {
x.squareRoot()
return x.squareRoot()
}
/// The (approximate) reciprocal (multiplicative inverse) of this number,
/// if it is representable.
///
/// If `a` if finite and nonzero, and `1/a` overflows or underflows,
/// then `a.reciprocal` is `nil`. Otherwise, `a.reciprocal` is `1/a`.
/// If `x` if finite and nonzero, and `1/x` overflows or underflows,
/// then `x.reciprocal` is `nil`. Otherwise, `a.reciprocal` is `1/x`.
///
/// If `b.reciprocal` is non-nil, you may be able to replace division by `b`
/// If `x.reciprocal` is non-nil, you may be able to replace division by `x`
/// with multiplication by this value. It is not advantageous to do this
/// for an isolated division unless it is a compile-time constant visible
/// to the compiler, but if you are dividing many values by a single
@@ -129,12 +134,14 @@ extension Real {
/// the real reciprocal (when it exists) as follows (I will use circle
/// operators to denote real-number arithmetic, and normal operators
/// for floating-point arithmetic):
///
/// ```
/// a * b.reciprocal! = a * (1/b)
/// = a * (1 ⊘ b)(1 + δ₁)
/// = (a ⊘ b)(1 + δ₁)(1 + δ₂)
/// = (a ⊘ b)(1 + δ₁ + δ₂ + δ₁δ₂)
/// a * b.reciprocal! = a * (1/b)
/// = a * (1 ⊘ b)(1 + δ₁)
/// = (a ⊘ b)(1 + δ₁)(1 + δ₂)
/// = (a ⊘ b)(1 + δ₁ + δ₂ + δ₁δ₂)
/// ```
///
/// where `0 < δᵢ <= ulpOfOne/2`. This gives a roughly 1-ulp error,
/// about twice the error bound we get using division. For most
/// purposes this is an acceptable error, but if you need to match
+69 -46
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
// 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
@@ -10,89 +10,112 @@
//===----------------------------------------------------------------------===//
public protocol RealFunctions: ElementaryFunctions {
/// The signed angle formed in the plane between the vector `(x,y)` and the
/// positive real axis, measured in radians.
/// `atan(y/x)`, with sign selected according to the quadrant of `(x, y)`.
///
/// The result is in the interval `[-π, π]`.
///
/// The argument order to `atan2` may be surprising to new programmers.
/// The convention of `y` being the first argument goes back at least to
/// Fortran IV in 1961 and is generally followed in computing with a few
/// notable exceptions (e.g. Mathematica and Excel). This convention was
/// originally chosen because of the mathematical definition of the
/// function:
///
/// ```
/// atan2(y,x) = atan(y/x) if x > 0
/// ```
///
/// See also ``ElementaryFunctions/atan(_:)``, as well as the `phase` and
/// `polar` properties defined on the `Complex` type.
/// See also:
/// -
/// - `atan()`
static func atan2(y: Self, x: Self) -> Self
/// The [error function](https://en.wikipedia.org/wiki/Error_function)
/// evaluated at `x`.
/// The error function evaluated at `x`.
///
/// See also:
/// -
/// - `erfc()`
static func erf(_ x: Self) -> Self
/// The complimentary [error function](https://en.wikipedia.org/wiki/Error_function)
/// evaluated at `x`.
/// The complimentary error function evaluated at `x`.
///
/// See also:
/// -
/// - `erf()`
static func erfc(_ x: Self) -> Self
/// 2 raised to the power x.
/// 2^x
///
/// See also ``log2(_:)``, ``ElementaryFunctions/exp(_:)``,
/// ``ElementaryFunctions/expMinusOne(_:)``
/// and ``ElementaryFunctions/pow(_:_:)-2qmul``.
/// See also:
/// -
/// - `exp()`
/// - `expMinusOne()`
/// - `exp10()`
/// - `log2()`
/// - `pow()`
static func exp2(_ x: Self) -> Self
/// 10 raised to the power x.
/// 10^x
///
/// See also ``log10(_:)``, ``ElementaryFunctions/exp(_:)``,
/// ``ElementaryFunctions/expMinusOne(_:)``
/// and ``ElementaryFunctions/pow(_:_:)-2qmul``.
/// See also:
/// -
/// - `exp()`
/// - `expMinusOne()`
/// - `exp2()`
/// - `log10()`
/// - `pow()`
static func exp10(_ x: Self) -> Self
/// The length of the vector `(x,y)`, computed in a manner that avoids
/// spurious overflow or underflow.
///
/// See also the `length` and `polar` properties defined on the `Complex`
/// type.
/// `sqrt(x*x + y*y)`, computed in a manner that avoids spurious overflow or
/// underflow.
static func hypot(_ x: Self, _ y: Self) -> Self
/// The [gamma function](https://en.wikipedia.org/wiki/Gamma_function) Γ(x).
/// The gamma function Γ(x).
///
/// See also:
/// -
/// - `logGamma()`
/// - `signGamma()`
static func gamma(_ x: Self) -> Self
/// The base-2 logarithm of `x`.
///
/// See also ``exp2(_:)``, ``ElementaryFunctions/log(_:)``,
/// and ``ElementaryFunctions/log(onePlus:)``.
/// See also:
/// -
/// - `exp2()`
/// - `log()`
/// - `log(onePlus:)`
/// - `log10()`
static func log2(_ x: Self) -> Self
/// The base-10 logarithm of `x`.
///
/// See also ``exp10(_:)``, ``ElementaryFunctions/log(_:)``,
/// and ``ElementaryFunctions/log(onePlus:)``.
/// See also:
/// -
/// - `exp10()`
/// - `log()`
/// - `log(onePlus:)`
/// - `log2()`
static func log10(_ x: Self) -> Self
#if !os(Windows)
/// The logarithm of the absolute value of the
/// [gamma function](https://en.wikipedia.org/wiki/Gamma_function),
/// log(|Γ(x)|).
/// The logarithm of the absolute value of the gamma function, log(|Γ(x)|).
///
/// Not available on Windows targets.
///
/// See also:
/// -
/// - `gamma()`
/// - `signGamma()`
static func logGamma(_ x: Self) -> Self
/// The sign of the
/// [gamma function](https://en.wikipedia.org/wiki/Gamma_function), Γ(x).
/// The sign of the gamma function, Γ(x).
///
/// For `x >= 0`, `signGamma(x)` is `.plus`. For negative `x`, `signGamma(x)`
/// is `.plus` when `x` is an integer, and otherwise it is `.minus` whenever
/// `trunc(x)` is even, and `.plus` when `trunc(x)` is odd.
///
/// This function is used together with ``logGamma(_:)``, which computes the
/// This function is used together with `logGamma`, which computes the
/// logarithm of the absolute value of Γ(x), to recover the sign information.
///
/// Not available on Windows targets.
///
/// See also:
/// -
/// - `gamma()`
/// - `logGamma()`
static func signGamma(_ x: Self) -> FloatingPointSign
#endif
/// a*b + c, computed _either_ with an FMA or with separate multiply and add.
///
/// Whichever is faster should be chosen by the compiler statically.
static func _mulAdd(_ a: Self, _ b: Self, _ c: Self) -> Self
}
@@ -1,82 +0,0 @@
//===--- RelaxedArithmetic.swift ------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021-2025 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 _NumericsShims
public enum Relaxed { }
extension Relaxed {
/// a+b, but grants the optimizer permission to reassociate expressions
/// and form FMAs.
///
/// Floating-point addition is not an associative operation, so the Swift
/// compiler does not have any flexibility in how it evaluates an expression
/// like:
/// ```
/// func sum(array: [Float]) -> Float {
/// array.reduce(0, +)
/// }
/// ```
/// Using `Relaxed.sum` instead of `+` permits the compiler to reorder the
/// terms in the summation, which unlocks loop unrolling and vectorization.
/// In a benchmark, simply using `Relaxed.sum` provides about an 8x speedup
/// for release builds, without any unsafe flags or other optimizations.
/// Further improvement should be possible by improving LLVM optimizations
/// or adding attributes to license more aggressive unrolling and taking
/// advantage of vector ISA extensions for swift.
///
/// If you want to compute `a-b` with relaxed semantics, use
/// `Relaxed.sum(a, -b)`.
///
/// If a type or toolchain does not support reassociation for optimization
/// purposes, this operation decays to a normal addition; it is a license
/// for the compiler to optimize, not a guarantee that any change occurs.
@_transparent
public static func sum<T: AlgebraicField>(_ a: T, _ b: T) -> T {
T._relaxedAdd(a, b)
}
/// a*b, but grants the optimizer permission to reassociate expressions
/// and form FMAs.
///
/// Floating-point addition and multiplication are not associative operations,
/// so the Swift compiler does not have any flexibility in how it evaluates
/// an expression like:
/// ```
/// func sumOfSquares(array: [Float]) -> Float {
/// array.reduce(0) { $0 + $1*$1 }
/// }
/// ```
/// Using `Relaxed.sum` and `Relaxed.product` instead of `+` and `*` permits
/// the compiler to reorder the terms in the summation, which unlocks loop
/// unrolling and vectorization, and form fused multiply-adds, which allows
/// us to achieve twice the throughput on some hardware.
///
/// If a type or toolchain does not support reassociation for optimization
/// purposes, this operation decays to a normal multiplication; it is a
/// license for the compiler to optimize, not a guarantee that any change
/// occurs.
@_transparent
public static func product<T: AlgebraicField>(_ a: T, _ b: T) -> T {
T._relaxedMul(a, b)
}
}
extension Relaxed {
/// a*b + c, computed _either_ with an FMA or with separate multiply and add,
/// whichever is fastest according to the optimizer's heuristics.
@_transparent
public static func multiplyAdd<T: AlgebraicField>(
_ a: T, _ b: T, _ c: T
) -> T {
T._relaxedAdd(c, T._relaxedMul(a, b))
}
}
+11 -64
View File
@@ -386,74 +386,21 @@ HEADER_SHIM long double libm_lgammal(long double x, int *signp) {
}
#endif
// MARK: - math inlines with relaxed semantics to support optimization.
#define CLANG_RELAX_FP _Pragma("clang fp reassociate(on) contract(fast)")
#if !defined __wasm__ // No _Float16 on wasm
/// a + b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM _Float16 _numerics_relaxed_addf16(_Float16 a, _Float16 b) {
CLANG_RELAX_FP
return a + b;
// MARK: - fast mul-add inlines
/// a*b + c evaluated _either_ as two operations or fma, whichever is faster.
HEADER_SHIM float _numerics_muladdf(float a, float b, float c) {
#pragma STDC FP_CONTRACT ON
return a*b + c;
}
/// a * b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM _Float16 _numerics_relaxed_mulf16(_Float16 a, _Float16 b) {
CLANG_RELAX_FP
return a * b;
}
#endif
/// a + b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM float _numerics_relaxed_addf(float a, float b) {
CLANG_RELAX_FP
return a + b;
/// a*b + c evaluated _either_ as two operations or fma, whichever is faster.
HEADER_SHIM double _numerics_muladd(double a, double b, double c) {
#pragma STDC FP_CONTRACT ON
return a*b + c;
}
/// a * b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM float _numerics_relaxed_mulf(float a, float b) {
CLANG_RELAX_FP
return a * b;
}
/// a + b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM double _numerics_relaxed_add(double a, double b) {
CLANG_RELAX_FP
return a + b;
}
/// a * b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM double _numerics_relaxed_mul(double a, double b) {
CLANG_RELAX_FP
return a * b;
}
#if !defined _WIN32 && (defined __i386__ || defined __x86_64__)
/// a + b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM long double _numerics_relaxed_addl(long double a, long double b) {
CLANG_RELAX_FP
return a + b;
}
/// a * b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM long double _numerics_relaxed_mull(long double a, long double b) {
CLANG_RELAX_FP
return a * b;
}
#endif
HEADER_SHIM void _numerics_optimization_barrier(const void *pointer) {
__asm("": :"r" (pointer));
}
#undef CLANG_RELAX_FP
// No long-double muladd operation, because no one has built an FMA for it
// (except for Itanium, which Swift doesn't support).
#ifdef __cplusplus
}
-19
View File
@@ -1,19 +0,0 @@
//===--- BlackHole.swift --------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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 _NumericsShims
@_transparent
public func blackHole<T>(_ thing: T) {
withUnsafePointer(to: thing) {
_numerics_optimization_barrier($0)
}
}
+1 -3
View File
@@ -1,15 +1,13 @@
#[[
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-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
#]]
add_library(_TestSupport
BlackHole.swift
DoubleWidth.swift
Error.swift
Interval.swift
RealTestSupport.swift)
-782
View File
@@ -1,782 +0,0 @@
//===--- DoubleWidth.swift ------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2017-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
//
//===----------------------------------------------------------------------===//
/// A fixed-width integer that has twice the bit width of its base type.
///
/// You can use the `DoubleWidth` type to continue calculations with the result
/// of a full width arithmetic operation. Normally, when you perform a full
/// width operation, the result is a tuple of the high and low parts of the
/// result.
///
/// let a = 2241543570477705381
/// let b = 186319822866995413
/// let c = a.multipliedFullWidth(by: b)
/// // c == (high: 22640526660490081, low: 7959093232766896457)
///
/// The tuple `c` can't be used in any further comparisons or calculations. To
/// use this value, create a `DoubleWidth` instance from the result. You can
/// use the `DoubleWidth` instance in the same way that you would use any other
/// integer type.
///
/// let d = DoubleWidth(a.multipliedFullWidth(by: b))
/// // d == 417644001000058515200174966092417353
///
/// // Check the calculation:
/// print(d / DoubleWidth(a) == b)
/// // Prints "true"
///
/// if d > Int.max {
/// print("Too big to be an 'Int'!")
/// } else {
/// print("Small enough to fit in an 'Int'")
/// }
/// // Prints "Too big to be an 'Int'!"
///
/// The `DoubleWidth` type is not intended as a replacement for a variable-width
/// integer type. Nesting `DoubleWidth` instances, in particular, may result in
/// undesirable performance.
public struct DoubleWidth<Base : FixedWidthInteger> {
public typealias High = Base
public typealias Low = Base.Magnitude
internal var _storage: (low: Low, high: High)
}
extension DoubleWidth {
/// The "high word" of this value.
///
/// Equivalent to `Base(self >> Base.bitWidth)`.
public var high: High {
return _storage.high
}
/// The "low word" of the value.
///
/// Equivalent to`Base.Magnitude(truncatingIfNecessary: self)`.
public var low: Low {
return _storage.low
}
/// Creates a new instance from the given tuple of high and low parts.
///
/// Equivalent to
/// ```
/// DoubleWidth<Base>(high) << Base.bitWidth + DoubleWidth<Base>(low)
/// ```
///
/// - Parameter value: The tuple to use as the source of the new instance's
/// high and low parts.
public init(_ value: (high: High, low: Low)) {
self._storage = (low: value.low, high: value.high)
}
// We expect users to invoke the public initializer above as demonstrated in
// the documentation (that is, by passing in the result of a full width
// operation).
//
// Internally, we'll need to create new instances by supplying high and low
// parts directly; ((double parentheses)) greatly impair readability,
// especially when nested:
//
// DoubleWidth<DoubleWidth>((DoubleWidth((0, 0)), DoubleWidth((0, 0))))
//
// For that reason, we'll include an internal initializer that takes two
// separate arguments.
/// Creates a new instance from the given tuple of high and low parts.
///
/// Equivalent to
/// ```
/// DoubleWidth<Base>(high) << Base.bitWidth + DoubleWidth<Base>(low)
/// ```
internal init(_ _high: High, _ low: Low) {
self.init((_high, low))
}
/// Zero.
public init() {
self.init(0, 0)
}
}
extension DoubleWidth : CustomStringConvertible {
public var description: String {
return String(self, radix: 10)
}
}
extension DoubleWidth : CustomDebugStringConvertible {
public var debugDescription: String {
return "(\(_storage.high), \(_storage.low))"
}
}
extension DoubleWidth : Equatable {
public static func ==(lhs: DoubleWidth, rhs: DoubleWidth) -> Bool {
return lhs._storage.low == rhs._storage.low
&& lhs._storage.high == rhs._storage.high
}
}
extension DoubleWidth : Comparable {
public static func <(lhs: DoubleWidth, rhs: DoubleWidth) -> Bool {
if lhs._storage.high < rhs._storage.high { return true }
else if lhs._storage.high > rhs._storage.high { return false }
else { return lhs._storage.low < rhs._storage.low }
}
}
extension DoubleWidth : Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(low)
hasher.combine(high)
}
}
extension DoubleWidth : Numeric {
public typealias Magnitude = DoubleWidth<Low>
public var magnitude: Magnitude {
let result = Magnitude(Low(truncatingIfNeeded: _storage.high), _storage.low)
if Base.isSigned && _storage.high < (0 as High) {
return ~result &+ 1
} else {
return result
}
}
internal init(_ _magnitude: Magnitude) {
self.init(High(_magnitude._storage.high), _magnitude._storage.low)
}
public init<T : BinaryInteger>(_ source: T) {
guard let result = DoubleWidth<Base>(exactly: source) else {
preconditionFailure("Value is outside the representable range")
}
self = result
}
public init?<T : BinaryInteger>(exactly source: T) {
// Can't represent a negative 'source' if Base is unsigned.
guard DoubleWidth.isSigned || source >= 0 else { return nil }
// Is 'source' entirely representable in Low?
if let low = Low(exactly: source.magnitude) {
self.init(source < (0 as T) ? (~0, ~low &+ 1) : (0, low))
} else {
// At this point we know source.bitWidth > Base.bitWidth, or else we
// would've taken the first branch.
let lowInT = source & T(~0 as Low)
let highInT = source >> Low.bitWidth
let low = Low(lowInT)
guard let high = High(exactly: highInT) else { return nil }
self.init(high, low)
}
}
}
extension DoubleWidth {
public struct Words {
public var _high: High.Words
public var _low: Low.Words
public init(_ value: DoubleWidth<Base>) {
// Multiples of word size only.
guard Base.bitWidth == Base.Magnitude.bitWidth &&
(UInt.bitWidth % Base.bitWidth == 0 ||
Base.bitWidth % UInt.bitWidth == 0) else {
fatalError("Access to words is not supported on this type")
}
self._high = value._storage.high.words
self._low = value._storage.low.words
assert(!_low.isEmpty)
}
}
}
extension DoubleWidth.Words: RandomAccessCollection {
public typealias Index = Int
public var startIndex: Index {
return 0
}
public var endIndex: Index {
return count
}
public var count: Int {
if Base.bitWidth < UInt.bitWidth { return 1 }
return _low.count + _high.count
}
public subscript(_ i: Index) -> UInt {
if Base.bitWidth < UInt.bitWidth {
precondition(i == 0, "Invalid index")
assert(2 * Base.bitWidth <= UInt.bitWidth)
return _low.first! | (_high.first! &<< Base.bitWidth._lowWord)
}
if i < _low.count {
return _low[i + _low.startIndex]
}
return _high[i - _low.count + _high.startIndex]
}
}
extension DoubleWidth : FixedWidthInteger {
public var words: Words {
return Words(self)
}
public static var isSigned: Bool {
return Base.isSigned
}
public static var max: DoubleWidth {
return self.init(High.max, Low.max)
}
public static var min: DoubleWidth {
return self.init(High.min, Low.min)
}
public static var bitWidth: Int {
return High.bitWidth + Low.bitWidth
}
public func addingReportingOverflow(_ rhs: DoubleWidth)
-> (partialValue: DoubleWidth, overflow: Bool) {
let (low, lowOverflow) =
_storage.low.addingReportingOverflow(rhs._storage.low)
let (high, highOverflow) =
_storage.high.addingReportingOverflow(rhs._storage.high)
let result = (high &+ (lowOverflow ? 1 : 0), low)
let overflow = highOverflow ||
high == Base.max && lowOverflow
return (partialValue: DoubleWidth(result), overflow: overflow)
}
public func subtractingReportingOverflow(_ rhs: DoubleWidth)
-> (partialValue: DoubleWidth, overflow: Bool) {
let (low, lowOverflow) =
_storage.low.subtractingReportingOverflow(rhs._storage.low)
let (high, highOverflow) =
_storage.high.subtractingReportingOverflow(rhs._storage.high)
let result = (high &- (lowOverflow ? 1 : 0), low)
let overflow = highOverflow ||
high == Base.min && lowOverflow
return (partialValue: DoubleWidth(result), overflow: overflow)
}
public func multipliedReportingOverflow(
by rhs: DoubleWidth
) -> (partialValue: DoubleWidth, overflow: Bool) {
let (carry, product) = multipliedFullWidth(by: rhs)
let partialValue = DoubleWidth(truncatingIfNeeded: product)
// Overflow has occured if carry is not just the sign-extension of
// partialValue (which is zero when Base is unsigned).
let overflow = carry != (partialValue >> DoubleWidth.bitWidth)
return (partialValue, overflow)
}
public func quotientAndRemainder(
dividingBy other: DoubleWidth
) -> (quotient: DoubleWidth, remainder: DoubleWidth) {
let (quotient, remainder) =
Magnitude._divide(self.magnitude, by: other.magnitude)
guard DoubleWidth.isSigned else {
return (DoubleWidth(quotient), DoubleWidth(remainder))
}
let isNegative = (self.high < (0 as High)) != (other.high < (0 as High))
let quotient_ = isNegative
? quotient == DoubleWidth.min.magnitude
? DoubleWidth.min
: 0 - DoubleWidth(quotient)
: DoubleWidth(quotient)
let remainder_ = self.high < (0 as High)
? 0 - DoubleWidth(remainder)
: DoubleWidth(remainder)
return (quotient_, remainder_)
}
public func dividedReportingOverflow(
by other: DoubleWidth
) -> (partialValue: DoubleWidth, overflow: Bool) {
if other == (0 as DoubleWidth) { return (self, true) }
if DoubleWidth.isSigned && other == -1 && self == .min {
return (self, true)
}
return (quotientAndRemainder(dividingBy: other).quotient, false)
}
public func remainderReportingOverflow(
dividingBy other: DoubleWidth
) -> (partialValue: DoubleWidth, overflow: Bool) {
if other == (0 as DoubleWidth) { return (self, true) }
if DoubleWidth.isSigned && other == -1 && self == .min { return (0, true) }
return (quotientAndRemainder(dividingBy: other).remainder, false)
}
// When using a pre-Swift 6.0 runtime, `&*` is not a protocol requirement of
// FixedWidthInteger, which results in the default implementation of this
// operation ending up recursively calling itself forever. In order to avoid
// this, we keep the concrete implementation around.
public func multipliedFullWidth(
by other: DoubleWidth
) -> (high: DoubleWidth, low: DoubleWidth.Magnitude) {
let isNegative = DoubleWidth.isSigned &&
(self < (0 as DoubleWidth)) != (other < (0 as DoubleWidth))
func mul(_ x: Low, _ y: Low) -> (partial: Low, carry: Low) {
let (high, low) = x.multipliedFullWidth(by: y)
return (low, high)
}
func sum(_ x: Low, _ y: Low, _ z: Low) -> (partial: Low, carry: Low) {
let (sum1, overflow1) = x.addingReportingOverflow(y)
let (sum2, overflow2) = sum1.addingReportingOverflow(z)
let carry: Low = (overflow1 ? 1 : 0) + (overflow2 ? 1 : 0)
return (sum2, carry)
}
let lhs = self.magnitude
let rhs = other.magnitude
let a = mul(rhs._storage.low, lhs._storage.low)
let b = mul(rhs._storage.low, lhs._storage.high)
let c = mul(rhs._storage.high, lhs._storage.low)
let d = mul(rhs._storage.high, lhs._storage.high)
let mid1 = sum(a.carry, b.partial, c.partial)
let mid2 = sum(b.carry, c.carry, d.partial)
let low =
DoubleWidth<Low>(mid1.partial, a.partial)
let (sum_, overflow_) =
mid1.carry.addingReportingOverflow(mid2.partial)
let high =
DoubleWidth(High(mid2.carry + d.carry + (overflow_ ? 1 : 0)), sum_)
if isNegative {
let (lowComplement, overflow) = (~low).addingReportingOverflow(1)
return (~high + (overflow ? 1 : 0 as DoubleWidth), lowComplement)
} else {
return (high, low)
}
}
public func dividingFullWidth(
_ dividend: (high: DoubleWidth, low: DoubleWidth.Magnitude)
) -> (quotient: DoubleWidth, remainder: DoubleWidth) {
let other = DoubleWidth<DoubleWidth>(dividend)
let (quotient, remainder) =
Magnitude._divide(other.magnitude, by: self.magnitude)
guard DoubleWidth.isSigned else {
return (DoubleWidth(quotient), DoubleWidth(remainder))
}
let isNegative =
(self.high < (0 as High)) != (other.high.high < (0 as High))
let quotient_ = isNegative
? quotient == DoubleWidth.min.magnitude
? DoubleWidth.min
: 0 - DoubleWidth(quotient)
: DoubleWidth(quotient)
let remainder_ = other.high.high < (0 as High)
? 0 - DoubleWidth(remainder)
: DoubleWidth(remainder)
return (quotient_, remainder_)
}
public static func &=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
lhs._storage.low &= rhs._storage.low
lhs._storage.high &= rhs._storage.high
}
public static func |=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
lhs._storage.low |= rhs._storage.low
lhs._storage.high |= rhs._storage.high
}
public static func ^=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
lhs._storage.low ^= rhs._storage.low
lhs._storage.high ^= rhs._storage.high
}
public static func <<=(lhs: inout DoubleWidth, rhs: DoubleWidth) {
if DoubleWidth.isSigned && rhs < (0 as DoubleWidth) {
lhs >>= 0 - rhs
return
}
// Shift is larger than this type's bit width.
if rhs._storage.high != (0 as High) ||
rhs._storage.low >= DoubleWidth.bitWidth
{
lhs = 0
return
}
lhs &<<= rhs
}
public static func >>=(lhs: inout DoubleWidth, rhs: DoubleWidth) {
if DoubleWidth.isSigned && rhs < (0 as DoubleWidth) {
lhs <<= 0 - rhs
return
}
// Shift is larger than this type's bit width.
if rhs._storage.high != (0 as High) ||
rhs._storage.low >= DoubleWidth.bitWidth
{
lhs = lhs < (0 as DoubleWidth) ? ~0 : 0
return
}
lhs &>>= rhs
}
/// Returns this value "masked" by its bit width.
///
/// "Masking" notionally involves repeatedly incrementing or decrementing
/// this value by `self.bitWidth` until the result is contained in the
/// range `0..<self.bitWidth`.
internal func _masked() -> DoubleWidth {
let bits = DoubleWidth(DoubleWidth.bitWidth)
if DoubleWidth.bitWidth.nonzeroBitCount == 1 {
return self & (bits &- 1)
}
let reduced = self % bits
// bitWidth is always positive, but the value being reduced might have
// been negative, in which case reduced will also be negative. We need
// the representative in [0, bitWidth), so conditionally add the count
// to get the positive residue.
if Base.isSigned && reduced < 0 { return reduced &+ bits }
return reduced
}
public static func &<<=(lhs: inout DoubleWidth, rhs: DoubleWidth) {
let rhs = rhs._masked()
guard rhs._storage.low < Base.bitWidth else {
lhs._storage.high = High(
truncatingIfNeeded: lhs._storage.low &<<
(rhs._storage.low &- Low(Base.bitWidth)))
lhs._storage.low = 0
return
}
guard rhs._storage.low != (0 as Low) else { return }
lhs._storage.high &<<= High(rhs._storage.low)
lhs._storage.high |= High(
truncatingIfNeeded: lhs._storage.low &>>
(Low(Base.bitWidth) &- rhs._storage.low))
lhs._storage.low &<<= rhs._storage.low
}
public static func &>>=(lhs: inout DoubleWidth, rhs: DoubleWidth) {
let rhs = rhs._masked()
guard rhs._storage.low < Base.bitWidth else {
lhs._storage.low = Low(
truncatingIfNeeded: lhs._storage.high &>>
High(rhs._storage.low &- Low(Base.bitWidth)))
lhs._storage.high = lhs._storage.high < (0 as High) ? ~0 : 0
return
}
guard rhs._storage.low != (0 as Low) else { return }
lhs._storage.low &>>= rhs._storage.low
lhs._storage.low |= Low(
truncatingIfNeeded: lhs._storage.high &<<
High(Low(Base.bitWidth) &- rhs._storage.low))
lhs._storage.high &>>= High(rhs._storage.low)
}
// FIXME(integers): remove this once the operators are back to Numeric
public static func + (
lhs: DoubleWidth, rhs: DoubleWidth
) -> DoubleWidth {
var lhs = lhs
lhs += rhs
return lhs
}
public static func +=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
let (result, overflow) = lhs.addingReportingOverflow(rhs)
precondition(!overflow, "Overflow in +=")
lhs = result
}
// FIXME(integers): remove this once the operators are back to Numeric
public static func - (
lhs: DoubleWidth, rhs: DoubleWidth
) -> DoubleWidth {
var lhs = lhs
lhs -= rhs
return lhs
}
public static func -=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
let (result, overflow) = lhs.subtractingReportingOverflow(rhs)
precondition(!overflow, "Overflow in -=")
lhs = result
}
// FIXME(integers): remove this once the operators are back to Numeric
public static func * (
lhs: DoubleWidth, rhs: DoubleWidth
) -> DoubleWidth {
var lhs = lhs
lhs *= rhs
return lhs
}
public static func *=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
let (result, overflow) = lhs.multipliedReportingOverflow(by:rhs)
precondition(!overflow, "Overflow in *=")
lhs = result
}
// FIXME(integers): remove this once the operators are back to Numeric
public static func / (
lhs: DoubleWidth, rhs: DoubleWidth
) -> DoubleWidth {
var lhs = lhs
lhs /= rhs
return lhs
}
public static func /=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
let (result, overflow) = lhs.dividedReportingOverflow(by:rhs)
precondition(!overflow, "Overflow in /=")
lhs = result
}
// FIXME(integers): remove this once the operators are back to Numeric
public static func % (
lhs: DoubleWidth, rhs: DoubleWidth
) -> DoubleWidth {
var lhs = lhs
lhs %= rhs
return lhs
}
public static func %=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
let (result, overflow) = lhs.remainderReportingOverflow(dividingBy:rhs)
precondition(!overflow, "Overflow in %=")
lhs = result
}
public static func &+(
lhs: DoubleWidth, rhs: DoubleWidth
) -> DoubleWidth {
let (low, carry) = lhs.low.addingReportingOverflow(rhs.low)
let high = lhs.high &+ rhs.high &+ (carry ? 1 : 0)
return DoubleWidth(high, low)
}
public static func &-(
lhs: DoubleWidth, rhs: DoubleWidth
) -> DoubleWidth {
let (low, borrow) = lhs.low.subtractingReportingOverflow(rhs.low)
let high = lhs.high &- rhs.high &- (borrow ? 1 : 0)
return DoubleWidth(high, low)
}
public static func &*(
lhs: DoubleWidth, rhs: DoubleWidth
) -> DoubleWidth {
let p00 = lhs.low.multipliedFullWidth(by: rhs.low)
let p10 = lhs.high &* Base(truncatingIfNeeded: rhs.low)
let p01 = Base(truncatingIfNeeded: lhs.low) &* rhs.high
return DoubleWidth(p10 &+ p01 &+ Base(truncatingIfNeeded: p00.high), p00.low)
}
public init(_truncatingBits bits: UInt) {
_storage.low = Low(_truncatingBits: bits)
_storage.high = High(_truncatingBits: bits >> UInt(Low.bitWidth))
}
public init(integerLiteral x: Int) {
self.init(x)
}
public var leadingZeroBitCount: Int {
return high == (0 as High)
? High.bitWidth + low.leadingZeroBitCount
: high.leadingZeroBitCount
}
public var trailingZeroBitCount: Int {
return low == (0 as Low)
? Low.bitWidth + high.trailingZeroBitCount
: low.trailingZeroBitCount
}
public var nonzeroBitCount: Int {
return high.nonzeroBitCount + low.nonzeroBitCount
}
public var byteSwapped: DoubleWidth {
return DoubleWidth(
High(truncatingIfNeeded: low.byteSwapped),
Low(truncatingIfNeeded: high.byteSwapped))
}
}
extension DoubleWidth : UnsignedInteger where Base : UnsignedInteger {
/// Returns the quotient and remainder after dividing a triple-width magnitude
/// `lhs` by a double-width magnitude `rhs`.
///
/// This operation is conceptually that described by Burnikel and Ziegler
/// (1998).
internal static func _divide(
_ lhs: (high: Low, mid: Low, low: Low), by rhs: Magnitude
) -> (quotient: Low, remainder: Magnitude) {
// The following invariants are guaranteed to hold by dividingFullWidth or
// quotientAndRemainder before this method is invoked:
assert(rhs.leadingZeroBitCount == 0)
assert(Magnitude(lhs.high, lhs.mid) < rhs)
guard lhs.high != (0 as Low) else {
let lhs_ = Magnitude(lhs.mid, lhs.low)
return lhs_ < rhs ? (0, lhs_) : (1, lhs_ &- rhs)
}
// Estimate the quotient.
var quotient = lhs.high == rhs.high
? Low.max
: rhs.high.dividingFullWidth((lhs.high, lhs.mid)).quotient
// Compute quotient * rhs.
// TODO: This could be performed more efficiently.
var product =
DoubleWidth<Magnitude>(
0, Magnitude(quotient.multipliedFullWidth(by: rhs.low)))
let (x, y) = quotient.multipliedFullWidth(by: rhs.high)
product += DoubleWidth<Magnitude>(Magnitude(0, x), Magnitude(y, 0))
// Compute the remainder after decrementing quotient as necessary.
var remainder =
DoubleWidth<Magnitude>(
Magnitude(0, lhs.high), Magnitude(lhs.mid, lhs.low))
while remainder < product {
quotient = quotient &- 1
remainder += DoubleWidth<Magnitude>(0, rhs)
}
remainder -= product
return (quotient, remainder.low)
}
/// Returns the quotient and remainder after dividing a quadruple-width
/// magnitude `lhs` by a double-width magnitude `rhs`.
internal static func _divide(
_ lhs: DoubleWidth<Magnitude>, by rhs: Magnitude
) -> (quotient: Magnitude, remainder: Magnitude) {
guard _fastPath(rhs > (0 as Magnitude)) else {
fatalError("Division by zero")
}
guard _fastPath(rhs >= lhs.high) else {
fatalError("Division results in an overflow")
}
if lhs.high == (0 as Magnitude) {
return lhs.low.quotientAndRemainder(dividingBy: rhs)
}
if rhs.high == (0 as Low) {
let a = lhs.high.high % rhs.low
let b = a == (0 as Low)
? lhs.high.low % rhs.low
: rhs.low.dividingFullWidth((a, lhs.high.low)).remainder
let (x, c) = b == (0 as Low)
? lhs.low.high.quotientAndRemainder(dividingBy: rhs.low)
: rhs.low.dividingFullWidth((b, lhs.low.high))
let (y, d) = c == (0 as Low)
? lhs.low.low.quotientAndRemainder(dividingBy: rhs.low)
: rhs.low.dividingFullWidth((c, lhs.low.low))
return (Magnitude(x, y), Magnitude(0, d))
}
// Left shift both rhs and lhs, then divide and right shift the remainder.
let shift = rhs.leadingZeroBitCount
let rhs = rhs &<< shift
let lhs = lhs &<< shift
if lhs.high.high == (0 as Low)
&& Magnitude(lhs.high.low, lhs.low.high) < rhs {
let (quotient, remainder) =
Magnitude._divide((lhs.high.low, lhs.low.high, lhs.low.low), by: rhs)
return (Magnitude(0, quotient), remainder &>> shift)
}
let (x, a) =
Magnitude._divide((lhs.high.high, lhs.high.low, lhs.low.high), by: rhs)
let (y, b) =
Magnitude._divide((a.high, a.low, lhs.low.low), by: rhs)
return (Magnitude(x, y), b &>> shift)
}
/// Returns the quotient and remainder after dividing a double-width
/// magnitude `lhs` by a double-width magnitude `rhs`.
internal static func _divide(
_ lhs: Magnitude, by rhs: Magnitude
) -> (quotient: Magnitude, remainder: Magnitude) {
guard _fastPath(rhs > (0 as Magnitude)) else {
fatalError("Division by zero")
}
guard rhs < lhs else {
if _fastPath(rhs > lhs) { return (0, lhs) }
return (1, 0)
}
if lhs.high == (0 as Low) {
let (quotient, remainder) =
lhs.low.quotientAndRemainder(dividingBy: rhs.low)
return (Magnitude(quotient), Magnitude(remainder))
}
if rhs.high == (0 as Low) {
let (x, a) = lhs.high.quotientAndRemainder(dividingBy: rhs.low)
let (y, b) = a == (0 as Low)
? lhs.low.quotientAndRemainder(dividingBy: rhs.low)
: rhs.low.dividingFullWidth((a, lhs.low))
return (Magnitude(x, y), Magnitude(0, b))
}
// Left shift both rhs and lhs, then divide and right shift the remainder.
let shift = rhs.leadingZeroBitCount
// Note the use of `>>` instead of `&>>` below,
// as `high` should be zero if `shift` is zero.
let high = (lhs >> (Magnitude.bitWidth &- shift)).low
let rhs = rhs &<< shift
let lhs = lhs &<< shift
let (quotient, remainder) =
Magnitude._divide((high, lhs.high, lhs.low), by: rhs)
return (Magnitude(0, quotient), remainder &>> shift)
}
}
extension DoubleWidth : SignedNumeric, SignedInteger
where Base : SignedInteger {}
+3 -3
View File
@@ -1,8 +1,8 @@
//===--- Error.swift ------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
@@ -10,8 +10,8 @@
//
//===----------------------------------------------------------------------===//
import ComplexModule
import RealModule
import ComplexModule
public func relativeError(_ tst: Float, _ ref: Double) -> Double {
let scale = max(ref.magnitude, Double(Float.leastNormalMagnitude))
+2 -2
View File
@@ -1,8 +1,8 @@
//===--- Interval.swift ---------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
+1 -1
View File
@@ -15,7 +15,7 @@ public protocol FixedWidthFloatingPoint: BinaryFloatingPoint
where Exponent: FixedWidthInteger,
RawSignificand: FixedWidthInteger { }
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
extension Float16: FixedWidthFloatingPoint { }
#endif
@@ -1,8 +1,8 @@
//===--- ApproximateEqualityTests.swift -----------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
+17 -66
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2024 Apple Inc. and the Swift Numerics project authors
// 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
@@ -13,23 +13,11 @@ import XCTest
import ComplexModule
import RealModule
func ulpsFromInfinity<T: Real>(_ a: T) -> T {
(.greatestFiniteMagnitude - a) / .greatestFiniteMagnitude.ulp + 1
}
// TODO: improve this to be a general-purpose complex comparison with tolerance
func relativeError<T>(_ a: Complex<T>, _ b: Complex<T>) -> T {
if a == b { return 0 }
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)
}
}
let scale = max(a.magnitude, b.magnitude, T.leastNormalMagnitude).ulp
return (a - b).magnitude / scale
}
func closeEnough<T: Real>(_ a: T, _ b: T, ulps allowed: T) -> Bool {
@@ -41,15 +29,11 @@ func checkMultiply<T>(
_ a: Complex<T>, _ b: Complex<T>, expected: Complex<T>, ulps allowed: T
) -> Bool {
let observed = a*b
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 {
if rel > allowed {
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
@@ -59,15 +43,11 @@ func checkDivide<T>(
_ a: Complex<T>, _ b: Complex<T>, expected: Complex<T>, ulps allowed: T
) -> Bool {
let observed = a/b
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 {
if rel > allowed {
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
@@ -83,6 +63,7 @@ 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.
@@ -95,9 +76,10 @@ final class ArithmeticTests: XCTestCase {
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.greatestFiniteMagnitude.exponent
(T.leastNormalMagnitude.exponent + T.Exponent(T.significandBitCount)) ...
T.greatestFiniteMagnitude.exponent
let inputs = (0..<100).map { _ in
Polar(length: T(
sign: .plus,
@@ -154,29 +136,20 @@ 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)
var product = Complex(length: p.length, phase: p.phase + q.phase)
product.real *= q.length
product.imaginary *= q.length
let product = Complex(length: p.length * q.length, phase: p.phase + q.phase)
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
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 !((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)
}
#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() {
@@ -218,38 +191,16 @@ 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: 1.0) { XCTFail() }
if checkDivide(test.a, test.b, expected: test.c, ulps: 0.5) { 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)) && LONG_TESTS
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
func testFloat16DivisionSemiExhaustive() {
func complex(bitPattern: UInt32) -> Complex<Float16> {
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<Float>(a)/Complex<Float>(b)
if checkDivide(a, b, expected: Complex<Float16>(q), ulps: 4) { XCTFail() }
q = Complex<Float>(b)/Complex<Float>(a)
if checkDivide(b, a, expected: Complex<Float16>(q), ulps: 4) { XCTFail() }
}
}
#endif
}
+1
View File
@@ -10,6 +10,7 @@ See https://swift.org/LICENSE.txt for license information
add_library(ComplexTests
ApproximateEqualityTests.swift
ArithmeticTests.swift
DifferentiableTests.swift
ElementaryFunctionTests.swift
PropertyTests.swift)
set_target_properties(ComplexTests PROPERTIES
@@ -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 swift(>=5.3) && canImport(_Differentiation)
import XCTest
import ComplexModule
import _Differentiation
final class DifferentiableTests: XCTestCase {
func testComponentGetter() {
XCTAssertEqual(
gradient(at: Complex<Float>(5, 5)) { $0.real * 2 },
Complex(2, 0))
XCTAssertEqual(
gradient(at: Complex<Float>(5, 5)) { $0.imaginary * 2 },
Complex(0, 2))
XCTAssertEqual(
gradient(at: Complex<Float>(5, 5)) { $0.real * 5 + $0.imaginary * 2 },
Complex(5, 2))
}
func testInitializer() {
let φ1 = pullback(at: 4, -3) { r, i in Complex<Float>(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<Float>(r * r, i + i) }
let tan2 = φ2(Complex(-1, 1))
XCTAssertEqual(tan2.0, -8)
XCTAssertEqual(tan2.1, 2)
}
func testConjugate() {
let φ = pullback(at: Complex<Float>(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<Float>(2, 3)) { x in
x + Complex(5, 6)
}
XCTAssertEqual(φAdd(Complex(1, 1)), Complex(1, 1))
let φSubtract = pullback(at: Complex<Float>(2, 3)) { x in
Complex(5, 6) - x
}
XCTAssertEqual(φSubtract(Complex(1, 1)), Complex(-1, -1))
let φMultiply = pullback(at: Complex<Float>(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<Float>(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
@@ -1,8 +1,8 @@
//===--- ElementaryFunctionTests.swift ------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
@@ -180,13 +180,7 @@ final class ElementaryFunctionTests: XCTestCase {
XCTAssert(huge.imaginary.isApproximatelyEqual(to: mag))
huge = Complex<T>.cosh(Complex(-x, .pi/4))
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
XCTAssert(huge.imaginary.isApproximatelyEqual(to: -mag))
huge = Complex<T>.cosh(Complex(-x, -.pi/4))
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
XCTAssert(huge.imaginary.isApproximatelyEqual(to: mag))
huge = Complex<T>.cosh(Complex(x, -.pi/4))
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
XCTAssert(huge.imaginary.isApproximatelyEqual(to: -mag))
}
func testSinh<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
@@ -218,12 +212,6 @@ final class ElementaryFunctionTests: XCTestCase {
XCTAssert(huge.imaginary.isApproximatelyEqual(to: mag))
huge = Complex<T>.sinh(Complex(-x, .pi/4))
XCTAssert(huge.real.isApproximatelyEqual(to: -mag))
XCTAssert(huge.imaginary.isApproximatelyEqual(to: mag))
huge = Complex<T>.sinh(Complex(-x, -.pi/4))
XCTAssert(huge.real.isApproximatelyEqual(to: -mag))
XCTAssert(huge.imaginary.isApproximatelyEqual(to: -mag))
huge = Complex<T>.sinh(Complex(x, -.pi/4))
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
XCTAssert(huge.imaginary.isApproximatelyEqual(to: -mag))
// For randomly-chosen well-scaled finite values, we expect to have
// cosh² - sinh² ≈ 1. Note that this test would break down due to
@@ -412,18 +400,6 @@ final class ElementaryFunctionTests: XCTestCase {
}
}
func testPowR<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
XCTAssertEqual(Complex<T>.pow(.zero, -.one), .infinity)
XCTAssertEqual(Complex<T>.pow(.zero, .zero), .infinity)
XCTAssertEqual(Complex<T>.pow(.zero, +.one), .zero)
}
func testPowN<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
XCTAssertEqual(Complex<T>.pow(.zero, -1), .infinity)
XCTAssertEqual(Complex<T>.pow(.zero, 0), .one)
XCTAssertEqual(Complex<T>.pow(.zero, +1), .zero)
}
func testFloat() {
testExp(Float.self)
testExpMinusOne(Float.self)
@@ -435,8 +411,6 @@ final class ElementaryFunctionTests: XCTestCase {
testAcosh(Float.self)
testAsinh(Float.self)
testAtanh(Float.self)
testPowR(Float.self)
testPowN(Float.self)
}
func testDouble() {
@@ -450,11 +424,9 @@ final class ElementaryFunctionTests: XCTestCase {
testAcosh(Double.self)
testAsinh(Double.self)
testAtanh(Double.self)
testPowR(Double.self)
testPowN(Double.self)
}
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
func testFloat80() {
testExp(Float80.self)
testExpMinusOne(Float80.self)
@@ -466,8 +438,6 @@ final class ElementaryFunctionTests: XCTestCase {
testAcosh(Float80.self)
testAsinh(Float80.self)
testAtanh(Float80.self)
testPowR(Float80.self)
testPowN(Float80.self)
}
#endif
#endif
}
+108
View File
@@ -0,0 +1,108 @@
//===--- main.swift -------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Numerics
import _TestSupport
#if DEBUG
fatalError("Run this test in Release configuration")
#else
var componentError = Double(Float.ulpOfOne/2)
var complexError = Double(Float.ulpOfOne/2)
var componentMaxInput = Complex<Float>.zero
var complexMaxInput = Complex<Float>.zero
func test(_ z: Complex<Float>) {
let tst = Complex.log(z)
// TODO: we _should_ be able to say Complex<Double>(z), but that goes through
// the slow, generic path for BinaryFloatingPoint conversion; once we get
// that resolved in the standard library, we can replace the conversion on
// this and the next line. Currently it dominate testing time if we do that.
let ref = Complex.log(Complex(Double(z.real), Double(z.imaginary)))
if tst == Complex(Float(ref.real), Float(ref.imaginary)) { return }
let thisError = relativeError(tst, ref)
if thisError > complexError {
complexMaxInput = z
complexError = thisError
}
let thisComponentError = componentwiseError(tst, ref)
if thisComponentError > componentError {
componentMaxInput = z
componentError = thisComponentError
}
}
func testWithSymmetries(_ x: Float, _ y: Float) {
test(Complex( x, y))
test(Complex( y, x))
test(Complex(-y, x))
test(Complex(-x, y))
test(Complex(-x,-y))
test(Complex(-y,-x))
test(Complex( y,-x))
test(Complex( x,-y))
}
// The hardest to evaluate cases for log are those close to the unit circle,
// where log(z) is nearly zero. We want to have plausibly dense test coverage
// close to the circle.
let radii: [Float] = [0.9,
0.95,
0.99,
0.999,
0.9999,
1 - 10 * .ulpOfOne,
1,
1 + 10 * .ulpOfOne,
1.0001,
1.001,
1.01,
1.05,
1.1]
for r in radii {
for x in Interval(from: 1/Float.sqrt(2), to: r) {
// Generate the two y values that put us closest to the circle of radius r
let base = Double.sqrt(Double(r).addingProduct(Double(-x), Double(x)))
let a, b: Float
if Double(Float(base)) < base { a = Float(base); b = a.nextUp }
else { b = Float(base); a = b.nextDown }
testWithSymmetries(x, a)
testWithSymmetries(x, b)
}
}
// Away from the unit circle is "easy" but we still want to get some coverage.
// Generate 1 million uniform random points inside the circle, and then test
// both z and 1/z.
var g = SystemRandomNumberGenerator()
var count = 0
while count < 1_000_000 {
let z = Complex<Float>(.random(in: -1 ... 1, using: &g), .random(in: -1 ... 1, using: &g))
if z.length > 1 { continue }
count += 1
test(z)
test(1/z)
}
print("Worst complex norm error seen for log was \(complexError)")
print("For input \(complexMaxInput).")
print("Reference result: \(Complex.log(Complex<Double>(complexMaxInput)))")
print(" Observed result: \(Complex.log(complexMaxInput))")
print("Worst componentwise error seen for log was \(componentError)")
print("For input \(componentMaxInput).")
print("Reference result: \(Complex.log(Complex<Double>(componentMaxInput)))")
print(" Observed result: \(Complex.log(componentMaxInput))")
#endif
+108
View File
@@ -0,0 +1,108 @@
//===--- main.swift -------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Numerics
import _TestSupport
#if DEBUG
fatalError("Run this test in Release configuration")
#else
var componentError = Double(Float.ulpOfOne/2)
var complexError = Double(Float.ulpOfOne/2)
var componentMaxInput = Complex<Float>.zero
var complexMaxInput = Complex<Float>.zero
func test(_ z: Complex<Float>) {
let tst = Complex.log(onePlus: z)
// TODO: we _should_ be able to say Complex<Double>(z), but that goes through
// the slow, generic path for BinaryFloatingPoint conversion; once we get
// that resolved in the standard library, we can replace the conversion on
// this and the next line. Currently it dominate testing time if we do that.
let ref = Complex.log(onePlus: Complex(Double(z.real), Double(z.imaginary)))
if tst == Complex(Float(ref.real), Float(ref.imaginary)) { return }
let thisError = relativeError(tst, ref)
if thisError > complexError {
complexMaxInput = z
complexError = thisError
}
let thisComponentError = componentwiseError(tst, ref)
if thisComponentError > componentError {
componentMaxInput = z
componentError = thisComponentError
}
}
func testWithSymmetry(_ x: Float, _ y: Float) {
test(Complex( x-1, y))
test(Complex( y-1, x))
test(Complex(-y-1, x))
test(Complex(-x-1, y))
test(Complex(-x-1,-y))
test(Complex(-y-1,-x))
test(Complex( y-1,-x))
test(Complex( x-1,-y))
}
// The hardest to evaluate cases for log are those close to the unit circle
// centered at -1, where log(1+z) is nearly zero. We want to have plausibly
// dense test coverage close to the circle.
let radii: [Float] = [0.9,
0.95,
0.99,
0.999,
0.9999,
1 - 10 * .ulpOfOne,
1,
1 + 10 * .ulpOfOne,
1.0001,
1.001,
1.01,
1.05,
1.1]
for r in radii {
for x in Interval(from: 1/Float.sqrt(2), to: r) {
// Generate the two y values that put us closest to the circle of radius r
let base = Double.sqrt(Double(r).addingProduct(Double(-x), Double(x)))
let a, b: Float
if Double(Float(base)) < base { a = Float(base); b = a.nextUp }
else { b = Float(base); a = b.nextDown }
testWithSymmetry(x, a)
testWithSymmetry(x, b)
}
}
// Away from the unit circle is "easy" but we still want to get some coverage.
// Generate 1 million uniform random points inside the circle, and then test
// both z and 1/z.
var g = SystemRandomNumberGenerator()
var count = 0
while count < 1_000_000 {
let z = Complex<Float>(.random(in: -1 ... 1, using: &g), .random(in: -1 ... 1, using: &g))
if z.length > 1 { continue }
count += 1
test(z - 1)
test(1/z - 1)
}
print("Worst complex norm error seen for log(onePlus:) was \(complexError)")
print("For input \(complexMaxInput).")
print("Reference result: \(Complex.log(onePlus: Complex<Double>(complexMaxInput)))")
print(" Observed result: \(Complex.log(onePlus: complexMaxInput))")
print("Worst componentwise error seen for log(onePlus:) was \(componentError)")
print("For input \(componentMaxInput).")
print("Reference result: \(Complex.log(onePlus: Complex<Double>(componentMaxInput)))")
print(" Observed result: \(Complex.log(onePlus: componentMaxInput))")
#endif
@@ -1,8 +1,8 @@
//===--- ApproximateEqualityTests.swift -----------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
@@ -1,160 +0,0 @@
//===--- AugmentedArithmeticTests.swift -----------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import RealModule
import XCTest
import _TestSupport
final class AugmentedArithmeticTests: XCTestCase {
func testTwoSumSpecials<T: Real & FixedWidthFloatingPoint>(_: T.Type) {
// Must be exact and not overflow on outer bounds
var x = T.greatestFiniteMagnitude
var y = -T.greatestFiniteMagnitude
XCTAssertEqual(Augmented.sum(x, y).head, .zero)
XCTAssertEqual(Augmented.sum(x, y).tail, .zero)
XCTAssert(Augmented.sum(x, y).head.isFinite)
XCTAssert(Augmented.sum(x, y).tail.isFinite)
// Must be exact on lower subnormal bounds
x = T.leastNonzeroMagnitude
y = -T.leastNonzeroMagnitude
XCTAssertEqual(Augmented.sum(x, y).head, .zero)
XCTAssertEqual(Augmented.sum(x, y).tail, .zero)
// Must preserve floating point signs for:
// (1) (+0) + (-0) == +0
// (2) (-0) + (+0) == +0
// (3) (-0) + (-0) == -0
x = T(sign: .plus, exponent: 1, significand: 0)
y = T(sign: .minus, exponent: 1, significand: 0)
XCTAssertEqual(Augmented.sum(x, y).head.sign, .plus) // (1)
XCTAssertEqual(Augmented.sum(x, y).tail.sign, .plus)
x = T(sign: .minus, exponent: 1, significand: 0)
y = T(sign: .plus, exponent: 1, significand: 0)
XCTAssertEqual(Augmented.sum(x, y).head.sign, .plus) // (2)
XCTAssertEqual(Augmented.sum(x, y).tail.sign, .plus)
x = T(sign: .minus, exponent: 1, significand: 0)
y = T(sign: .minus, exponent: 1, significand: 0)
XCTAssertEqual(Augmented.sum(x, y).head.sign, .minus) // (3)
XCTAssertEqual(Augmented.sum(x, y).tail.sign, .plus)
// Infinity and NaN are propagated correctly
XCTAssertEqual(Augmented.sum( 0, T.infinity).head, T.infinity)
XCTAssertEqual(Augmented.sum( T.infinity, 0 ).head, T.infinity)
XCTAssertEqual(Augmented.sum( T.infinity, T.infinity).head, T.infinity)
XCTAssertEqual(Augmented.sum( 0, -T.infinity).head, -T.infinity)
XCTAssertEqual(Augmented.sum(-T.infinity, 0 ).head, -T.infinity)
XCTAssertEqual(Augmented.sum(-T.infinity, -T.infinity).head, -T.infinity)
XCTAssert(Augmented.sum( T.infinity, -T.infinity).head.isNaN)
XCTAssert(Augmented.sum(-T.infinity, T.infinity).head.isNaN)
XCTAssert(Augmented.sum( T.infinity, T.nan).head.isNaN)
XCTAssert(Augmented.sum( T.nan, T.infinity).head.isNaN)
XCTAssert(Augmented.sum(-T.infinity, T.nan).head.isNaN)
XCTAssert(Augmented.sum( T.nan, -T.infinity).head.isNaN)
XCTAssert(Augmented.sum( 0, T.nan).head.isNaN)
XCTAssert(Augmented.sum(T.nan, 0).head.isNaN)
XCTAssert(Augmented.sum(T.nan, T.nan).head.isNaN)
}
func testTwoSumRandomValues<T: Real & FixedWidthFloatingPoint>(_: T.Type) {
// For randomly-chosen well-scaled finite values, we expect:
// (1) `head` to be exactly the IEEE 754 sum of `a + b`
// (2) `tail` to be less than or equal `head.ulp/2`
// (3) the result of `twoSum` for unordered input to be exactly equal to
// the result of `fastTwoSum` for ordered input.
var g = SystemRandomNumberGenerator()
let values: [T] = (0 ..< 100).map { _ in
T.random(
in: T.ulpOfOne ..< 1,
using: &g)
}
for a in values {
for b in values {
let twoSum = Augmented.sum(a, b)
XCTAssertEqual(twoSum.head, a + b) // (1)
XCTAssert(twoSum.tail.magnitude <= twoSum.head.ulp/2) // (2)
let x: T = a.magnitude < b.magnitude ? b : a
let y: T = a.magnitude < b.magnitude ? a : b
let fastTwoSum = Augmented.sum(large: x, small: y)
XCTAssertEqual(twoSum.head, fastTwoSum.head) // (3)
XCTAssertEqual(twoSum.tail, fastTwoSum.tail) // (3)
}
}
}
func testTwoSumCancellation<T: Real & FixedWidthFloatingPoint>(_: T.Type) {
// Must be exact for exactly representable values
XCTAssertEqual(Augmented.sum( 0.984375, 1.375).head, 2.359375)
XCTAssertEqual(Augmented.sum( 0.984375, 1.375).tail, 0.0)
XCTAssertEqual(Augmented.sum(-0.984375, 1.375).head, 0.390625)
XCTAssertEqual(Augmented.sum(-0.984375, 1.375).tail, 0.0)
XCTAssertEqual(Augmented.sum( 0.984375,-1.375).head,-0.390625)
XCTAssertEqual(Augmented.sum( 0.984375,-1.375).tail, 0.0)
XCTAssertEqual(Augmented.sum(-0.984375,-1.375).head,-2.359375)
XCTAssertEqual(Augmented.sum(-0.984375,-1.375).tail, 0.0)
XCTAssertEqual(Augmented.sum( 1.375, 0.984375).head, 2.359375)
XCTAssertEqual(Augmented.sum( 1.375, 0.984375).tail, 0.0)
XCTAssertEqual(Augmented.sum( 1.375,-0.984375).head, 0.390625)
XCTAssertEqual(Augmented.sum( 1.375,-0.984375).tail, 0.0)
XCTAssertEqual(Augmented.sum(-1.375, 0.984375).head,-0.390625)
XCTAssertEqual(Augmented.sum(-1.375, 0.984375).tail, 0.0)
XCTAssertEqual(Augmented.sum(-1.375,-0.984375).head,-2.359375)
XCTAssertEqual(Augmented.sum(-1.375,-0.984375).tail, 0.0)
// Must handle cancellation when `b` is not representable in `a` and
// we expect `b` to be lost entirely in the calculation of `a + b`.
var a: T = 1.0
var b: T = .ulpOfOne * .ulpOfOne
var twoSum = Augmented.sum(a, b)
XCTAssertEqual(twoSum.head, a) // a + b = a
XCTAssertEqual(twoSum.tail, b) // Error: b
twoSum = Augmented.sum( a, -b)
XCTAssertEqual(twoSum.head, a)
XCTAssertEqual(twoSum.tail,-b)
twoSum = Augmented.sum(-a, b)
XCTAssertEqual(twoSum.head,-a)
XCTAssertEqual(twoSum.tail, b)
twoSum = Augmented.sum(-a, -b)
XCTAssertEqual(twoSum.head,-a)
XCTAssertEqual(twoSum.tail,-b)
// Must handle cancellation when `b` is only partially representable in `a`.
// We expect the fractional digits of `b` to be cancelled in the following
// example but the fractional digits to be preserved in `tail`.
let exponent = T.Exponent(T.significandBitCount + 1)
a = T(sign: .plus, exponent: exponent, significand: 1.0)
b = 256 + 0.5
twoSum = Augmented.sum( a, b)
XCTAssertEqual(twoSum.head, a + 256)
XCTAssertEqual(twoSum.tail, 0.5)
twoSum = Augmented.sum( a, -b)
XCTAssertEqual(twoSum.head, a - 256)
XCTAssertEqual(twoSum.tail, -0.5)
twoSum = Augmented.sum(-a, b)
XCTAssertEqual(twoSum.head, -a + 256)
XCTAssertEqual(twoSum.tail, 0.5)
twoSum = Augmented.sum(-a, -b)
XCTAssertEqual(twoSum.head, -a - 256)
XCTAssertEqual(twoSum.tail, -0.5)
}
func testTwoSum() {
testTwoSumSpecials(Float32.self)
testTwoSumRandomValues(Float32.self)
testTwoSumCancellation(Float32.self)
testTwoSumSpecials(Float64.self)
testTwoSumRandomValues(Float64.self)
testTwoSumCancellation(Float64.self)
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
testTwoSumSpecials(Float80.self)
testTwoSumRandomValues(Float80.self)
testTwoSumCancellation(Float80.self)
#endif
}
}
+1 -3
View File
@@ -9,10 +9,8 @@ See https://swift.org/LICENSE.txt for license information
add_library(RealTests
ApproximateEqualityTests.swift
AugmentedArithmeticTests.swift
ElementaryFunctionChecks.swift
IntegerExponentTests.swift
RelaxedArithmeticTests.swift)
IntegerExponentTests.swift)
target_compile_options(RealTests PRIVATE
-enable-testing)
target_link_libraries(RealTests PUBLIC
@@ -120,11 +120,11 @@ internal extension Real where Self: BinaryFloatingPoint {
assertClose(0.4041169094348222983238250859191217675, Self.erf(0.375))
assertClose(0.5958830905651777016761749140808782324, Self.erfc(0.375))
assertClose(2.3704361844166009086464735041766525098, Self.gamma(0.375))
#if !os(Windows)
#if !os(Windows)
assertClose( -0.11775527074107877445136203331798850, Self.logGamma(1.375))
XCTAssertEqual(.plus, Self.signGamma(1.375))
XCTAssertEqual(.minus, Self.signGamma(-2.375))
#endif
#endif
}
}
@@ -146,7 +146,7 @@ extension Real {
final class ElementaryFunctionChecks: XCTestCase {
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
func testFloat16() {
if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
Float16.elementaryFunctionChecks()
@@ -154,7 +154,7 @@ final class ElementaryFunctionChecks: XCTestCase {
Float16.powZeroChecks()
}
}
#endif
#endif
func testFloat() {
Float.elementaryFunctionChecks()
@@ -168,11 +168,11 @@ final class ElementaryFunctionChecks: XCTestCase {
Double.powZeroChecks()
}
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
func testFloat80() {
Float80.elementaryFunctionChecks()
Float80.realFunctionChecks()
Float80.powZeroChecks()
}
#endif
#endif
}
+6 -6
View File
@@ -77,8 +77,8 @@ internal extension Real where Self: FixedWidthFloatingPoint {
}
}
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
@available(macOS 11.0, iOS 14.0, watchOS 14.0, tvOS 7.0, *)
extension Float16 {
static func testIntegerExponent() {
testIntegerExponentCommon()
@@ -157,10 +157,10 @@ extension Double {
#endif
assertClose( 1.7976931348623151738531864721534215e308, Double.pow(-u, 3196577161300664268), allowedError: tol)
assertClose(-1.7976931348623155730212483790972209e308, Double.pow(-u, 3196577161300664269), allowedError: tol)
assertClose( 1.7976931348623159721893102860411089e308, Double.pow(-u, 3196577161300664270), allowedError: tol) // warning expected on non-x86
assertClose( 1.7976931348623159721893102860411089e308, Double.pow(-u, 3196577161300664270), allowedError: tol)
assertClose( 1.7976931348623157075547244136070910e308, Double.pow(-d, -6393154322601327474), allowedError: tol)
assertClose(-1.7976931348623159071387553670790721e308, Double.pow(-d, -6393154322601327475), allowedError: tol) // warning expected on non-x86
assertClose( 1.7976931348623161067227863205510754e308, Double.pow(-d, -6393154322601327476), allowedError: tol) // warning expected on non-x86
assertClose(-1.7976931348623159071387553670790721e308, Double.pow(-d, -6393154322601327475), allowedError: tol)
assertClose( 1.7976931348623161067227863205510754e308, Double.pow(-d, -6393154322601327476), allowedError: tol)
// Exponents close to underflow boundary.
assertClose( 2.4703282292062334560337346683707907e-324, Double.pow(-u, -3355781687888880946))
assertClose(-2.4703282292062329075106789791206172e-324, Double.pow(-u, -3355781687888880947))
@@ -174,7 +174,7 @@ extension Double {
final class IntegerExponentTests: XCTestCase {
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
func testFloat16() {
if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
Float16.testIntegerExponent()
@@ -1,129 +0,0 @@
//===--- RelaxedArithmeticTests.swift -------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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 RealModule
import _TestSupport
#if canImport(Accelerate)
import Accelerate
#endif
#if !DEBUG
func strictSum<T: Real>(_ array: [T]) -> T {
array.reduce(0, +)
}
func relaxedSum<T: Real>(_ array: [T]) -> T {
array.reduce(0, Relaxed.sum)
}
func strictSumOfSquares<T: Real>(_ array: [T]) -> T {
array.reduce(0) { $0 + $1*$1 }
}
func relaxedSumOfSquares<T: Real>(_ array: [T]) -> T {
array.reduce(0) { Relaxed.multiplyAdd($1, $1, $0) }
}
// TODO: not a great harness, but making it better bumps up against the
// limitations of what XCT measure { } lets us do easily. Good enough for now.
func benchmarkReduction(_ data: [Float], _ reduction: ([Float]) -> Float) {
var accum: Float = 0
let iters = 100_000
for _ in 0 ..< iters {
accum += reduction(data)
}
blackHole(accum)
}
final class RelaxedArithmeticTests: XCTestCase {
var floatData: [Float] = []
override func setUp() {
super.setUp()
floatData = (0 ..< 1024).map { _ in .random(in: .sqrt(1/2) ..< .sqrt(2)) }
}
func testStrictSumPerformance() {
measure { benchmarkReduction(floatData, strictSum) }
}
func testRelaxedSumPerformance() {
// Performance of this should be closer to vDSP.sum than to
// strict sum
measure { benchmarkReduction(floatData, relaxedSum) }
}
#if canImport(Accelerate)
func testvDSPSumPerformance() {
measure { benchmarkReduction(floatData, vDSP.sum) }
}
#endif
func testStrictDotPerformance() {
measure { benchmarkReduction(floatData, strictSumOfSquares) }
}
func testRelaxedDotPerformance() {
// Performance of this should be closer to vDSP.sumOfSquares than to
// strict sumOfSquares
measure { benchmarkReduction(floatData, relaxedSumOfSquares) }
}
#if canImport(Accelerate)
func testvDSPDotPerformance() {
measure { benchmarkReduction(floatData, vDSP.sumOfSquares) }
}
#endif
func testRelaxedArithmetic<T: FixedWidthFloatingPoint & Real>(_ type: T.Type) {
// Relaxed add is still an add; it's just permitted to reorder relative
// to other adds or form FMAs. So if we do one in isolation, it has to
// produce the same result as a normal addition.
let a = T.random(in: -1 ... 1)
let b = T.random(in: -1 ... 1)
XCTAssertEqual(a + b, Relaxed.sum(a, b))
// Same is true for mul.
XCTAssertEqual(a * b, Relaxed.product(a, b))
// add + mul must be either two operations or an FMA:
let unfused = a + 1.5 * b
let fused = a.addingProduct(1.5, b)
let relaxed = Relaxed.multiplyAdd(1.5, b, a)
XCTAssert(relaxed == unfused || relaxed == fused)
// Summing all values in an array can be associated however we want, but
// has to satisfy the usual error bound of 0.5 * sum.ulp * numberOfElements.
// We don't have a golden reference, but we can compare two sums with twice
// the bound for a basic check.
let array = (0 ..< 128).map { _ in T.random(in: 1 ..< 2) }
var ref = strictSum(array)
var tst = relaxedSum(array)
var bound = max(ref, tst).ulp * T(array.count)
XCTAssertLessThanOrEqual(abs(ref - tst), bound)
// Similarly for sum of squares ...
ref = strictSumOfSquares(array)
tst = relaxedSumOfSquares(array)
bound = 2 * max(ref, tst).ulp * T(array.count)
XCTAssertLessThanOrEqual(abs(ref - tst), bound)
}
func testRelaxedArithmetic() {
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
testRelaxedArithmetic(Float16.self)
#endif
testRelaxedArithmetic(Float.self)
testRelaxedArithmetic(Double.self)
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
testRelaxedArithmetic(Float80.self)
#endif
}
}
#endif
+2 -4
View File
@@ -23,9 +23,9 @@ function(get_swift_host_arch result_var_name)
else()
set("${result_var_name}" "aarch64" PARENT_SCOPE)
endif()
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64" OR "${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "powerpc64")
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64")
set("${result_var_name}" "powerpc64" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64le" OR "${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "powerpc64le")
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64le")
set("${result_var_name}" "powerpc64le" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "s390x")
set("${result_var_name}" "s390x" PARENT_SCOPE)
@@ -43,8 +43,6 @@ function(get_swift_host_arch result_var_name)
set("${result_var_name}" "i686" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "i686")
set("${result_var_name}" "i686" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "riscv64")
set("${result_var_name}" "riscv64" PARENT_SCOPE)
else()
message(FATAL_ERROR "Unrecognized architecture on host system: ${CMAKE_SYSTEM_PROCESSOR}")
endif()