mirror of
https://github.com/apple/swift-numerics
synced 2026-11-22 04:30:45 +00:00
Compare commits
35
Commits
Quaternions
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb58826429 | ||
|
|
02deda5402 | ||
|
|
669f618518 | ||
|
|
673c0f6c3d | ||
|
|
20fe3d7d8e | ||
|
|
69890e3639 | ||
|
|
8a65bea94b | ||
|
|
9f745b7c9b | ||
|
|
8630961065 | ||
|
|
0d1ccaf0d3 | ||
|
|
a7d826ead0 | ||
|
|
20a774f1a6 | ||
|
|
c2d05532d3 | ||
|
|
3b272b08af | ||
|
|
bb7b69501f | ||
|
|
738b0cdb23 | ||
|
|
ee167adfea | ||
|
|
a6c13f7de8 | ||
|
|
ea5d4cf4a5 | ||
|
|
15eab09844 | ||
|
|
2d92c04e96 | ||
|
|
aa5684820a | ||
|
|
63dc00f053 | ||
|
|
1f6c508c58 | ||
|
|
899af71c02 | ||
|
|
178f513ce6 | ||
|
|
3403d50630 | ||
|
|
167fe9b22a | ||
|
|
50552bf86b | ||
|
|
18274b1caa | ||
|
|
894008997c | ||
|
|
d46e20b4c5 | ||
|
|
6a7cf593bf | ||
|
|
cbdb286797 | ||
|
|
30074a3846 |
No files matched your search
@@ -1,5 +1,8 @@
|
||||
name: Pull request
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
@@ -9,9 +12,11 @@ jobs:
|
||||
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
|
||||
enable_freebsd_checks: true
|
||||
soundness:
|
||||
name: Soundness
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
cmake_minimum_required(VERSION 3.29)
|
||||
project(swift-numerics
|
||||
LANGUAGES Swift)
|
||||
|
||||
|
||||
@@ -47,6 +47,9 @@ let package = Package(
|
||||
name: "RealModule",
|
||||
dependencies: ["_NumericsShims"],
|
||||
exclude: excludedFilenames,
|
||||
swiftSettings: [
|
||||
.enableExperimentalFeature("BuiltinModule")
|
||||
],
|
||||
linkerSettings: [
|
||||
.linkedLibrary("m", .when(platforms: [.linux, .android]))
|
||||
]
|
||||
|
||||
@@ -155,9 +155,17 @@ extension Complex: AlgebraicField {
|
||||
///
|
||||
/// 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.
|
||||
/// 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
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
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()
|
||||
@@ -21,6 +24,9 @@ extension Complex: Decodable where RealType: Decodable {
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=6.0)
|
||||
@_unavailableInEmbedded
|
||||
#endif
|
||||
extension Complex: Encodable where RealType: Encodable {
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var unkeyedContainer = encoder.unkeyedContainer()
|
||||
|
||||
@@ -141,7 +141,10 @@ 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.sin(z.y))
|
||||
let phase = Complex(
|
||||
RealType.cos(z.y),
|
||||
RealType(signOf: z.x, magnitudeOf: 1) * RealType.sin(z.y)
|
||||
)
|
||||
let firstScale = RealType.exp(z.x.magnitude/2)
|
||||
let secondScale = firstScale/2
|
||||
return phase.multiplied(by: firstScale).multiplied(by: secondScale)
|
||||
@@ -171,9 +174,12 @@ extension Complex: ElementaryFunctions {
|
||||
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.cos(z.y), RealType.sin(z.y))
|
||||
let phase = Complex(
|
||||
RealType(signOf: z.x, magnitudeOf: RealType.cos(z.y)),
|
||||
RealType.sin(z.y)
|
||||
)
|
||||
let firstScale = RealType.exp(z.x.magnitude/2)
|
||||
let secondScale = RealType(signOf: z.x, magnitudeOf: firstScale/2)
|
||||
let secondScale = firstScale/2
|
||||
return phase.multiplied(by: firstScale).multiplied(by: secondScale)
|
||||
}
|
||||
return Complex(
|
||||
|
||||
@@ -16,6 +16,9 @@ extension Complex: CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=6.0)
|
||||
@_unavailableInEmbedded
|
||||
#endif
|
||||
extension Complex: CustomDebugStringConvertible {
|
||||
public var debugDescription: String {
|
||||
"Complex<\(RealType.self)>(\(String(reflecting: x)), \(String(reflecting: y)))"
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
# 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.
|
||||
@@ -163,7 +163,7 @@ public enum RoundingRule {
|
||||
/// - `(-4).divided(by: 3, rounding: .toNearestOrZero)`
|
||||
/// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2.
|
||||
///
|
||||
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrZero)` is `3`,
|
||||
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrZero)` is `2`,
|
||||
/// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is closer to zero.
|
||||
case toNearestOrZero
|
||||
|
||||
|
||||
@@ -27,9 +27,8 @@ extension BinaryInteger {
|
||||
/// // is odd.
|
||||
/// 3.shifted(rightBy: 1, rounding: .toOdd)
|
||||
///
|
||||
/// // 7/4 = 1.75, so the result is 1 with probability 1/4, or 2
|
||||
/// // with probability 3/4.
|
||||
/// 7.shifted(rightBy: 2, rounding: .stochastically)
|
||||
/// // 6/4 = 1.5, so the tie is broken in favor of the even value 2.
|
||||
/// 6.shifted(rightBy: 2, rounding: .toNearestOrEven)
|
||||
///
|
||||
/// // 4/4 is exactly 1, so this does not trap.
|
||||
/// 4.shifted(rightBy: 2, rounding: .requireExact)
|
||||
@@ -153,9 +152,8 @@ extension BinaryInteger {
|
||||
/// // is odd.
|
||||
/// 3.shifted(rightBy: 1, rounding: .toOdd)
|
||||
///
|
||||
/// // 7/4 = 1.75, so the result is 1 with probability 1/4, or 2
|
||||
/// // with probability 3/4.
|
||||
/// 7.shifted(rightBy: 2, rounding: .stochastically)
|
||||
/// // 6/4 = 1.5, so the tie is broken in favor of the even value 2.
|
||||
/// 6.shifted(rightBy: 2, rounding: .toNearestOrEven)
|
||||
///
|
||||
/// // 4/4 is exactly 1, so this does not trap.
|
||||
/// 4.shifted(rightBy: 2, rounding: .requireExact)
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
# 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).
|
||||
@@ -26,3 +26,7 @@ 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.
|
||||
@@ -10,6 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import _NumericsShims
|
||||
import Builtin
|
||||
|
||||
extension Double: Real {
|
||||
@_transparent
|
||||
@@ -222,11 +223,19 @@ extension Double: Real {
|
||||
|
||||
@_transparent
|
||||
public static func _relaxedAdd(_ a: Double, _ b: Double) -> Double {
|
||||
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
|
||||
Double(Builtin.fadd_relaxed_FPIEEE64(a._value, b._value))
|
||||
#else
|
||||
_numerics_relaxed_add(a, b)
|
||||
#endif
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func _relaxedMul(_ a: Double, _ b: Double) -> Double {
|
||||
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
|
||||
Double(Builtin.fmul_relaxed_FPIEEE64(a._value, b._value))
|
||||
#else
|
||||
_numerics_relaxed_mul(a, b)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import _NumericsShims
|
||||
import Builtin
|
||||
|
||||
extension Float: Real {
|
||||
@_transparent
|
||||
@@ -195,11 +196,19 @@ extension Float: Real {
|
||||
|
||||
@_transparent
|
||||
public static func _relaxedAdd(_ a: Float, _ b: Float) -> Float {
|
||||
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
|
||||
Float(Builtin.fadd_relaxed_FPIEEE32(a._value, b._value))
|
||||
#else
|
||||
_numerics_relaxed_addf(a, b)
|
||||
#endif
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func _relaxedMul(_ a: Float, _ b: Float) -> Float {
|
||||
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
|
||||
Float(Builtin.fmul_relaxed_FPIEEE32(a._value, b._value))
|
||||
#else
|
||||
_numerics_relaxed_mulf(a, b)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import _NumericsShims
|
||||
import Builtin
|
||||
|
||||
// Float16 is only available on macOS when targeting arm64.
|
||||
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
|
||||
@@ -173,18 +174,27 @@ extension Float16: Real {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !arch(wasm32)
|
||||
#if !arch(wasm32) || hasFeature(BuiltinRelaxedFP)
|
||||
// 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.
|
||||
// that these use. However, if we have BuiltinRelaxedFP we can use builtins
|
||||
// to do this directly without needing the C hooks.
|
||||
|
||||
@_transparent
|
||||
public static func _relaxedAdd(_ a: Float16, _ b: Float16) -> Float16 {
|
||||
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
|
||||
Float16(Builtin.fadd_relaxed_FPIEEE16(a._value, b._value))
|
||||
#else
|
||||
_numerics_relaxed_addf16(a, b)
|
||||
#endif
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func _relaxedMul(_ a: Float16, _ b: Float16) -> Float16 {
|
||||
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
|
||||
Float16(Builtin.fmul_relaxed_FPIEEE16(a._value, b._value))
|
||||
#else
|
||||
_numerics_relaxed_mulf16(a, b)
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import _NumericsShims
|
||||
import Builtin
|
||||
|
||||
// Restrict extension to platforms for which Float80 exists.
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
@@ -168,12 +169,20 @@ extension Float80: Real {
|
||||
|
||||
@_transparent
|
||||
public static func _relaxedAdd(_ a: Float80, _ b: Float80) -> Float80 {
|
||||
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
|
||||
Float80(Builtin.fadd_relaxed_FPIEEE80(a._value, b._value))
|
||||
#else
|
||||
_numerics_relaxed_addl(a, b)
|
||||
#endif
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func _relaxedMul(_ a: Float80, _ b: Float80) -> Float80 {
|
||||
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
|
||||
Float80(Builtin.fmul_relaxed_FPIEEE80(a._value, b._value))
|
||||
#else
|
||||
_numerics_relaxed_mull(a, b)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -68,9 +68,30 @@ 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
|
||||
|
||||
@@ -180,7 +180,13 @@ 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) {
|
||||
@@ -212,6 +218,12 @@ 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
|
||||
|
||||
@@ -31,6 +31,11 @@ internal extension Real where Self: FixedWidthFloatingPoint {
|
||||
XCTAssertEqual(Self.pow(-1, Int.max), -1)
|
||||
XCTAssertEqual(Self.pow(-1, -Int.max), -1)
|
||||
XCTAssertEqual(Self.pow(-1, Int.min), 1)
|
||||
}
|
||||
|
||||
static func testIntegerExponentOverflowAndUnderflow() {
|
||||
// TODO: replace with seedable generator, print seed.
|
||||
var g = SystemRandomNumberGenerator()
|
||||
// Generate some random test values that definitely overflow or
|
||||
// underflow; we want to be sure that we get the right ±0 or ±∞
|
||||
// result.
|
||||
@@ -82,6 +87,7 @@ internal extension Real where Self: FixedWidthFloatingPoint {
|
||||
extension Float16 {
|
||||
static func testIntegerExponent() {
|
||||
testIntegerExponentCommon()
|
||||
testIntegerExponentOverflowAndUnderflow()
|
||||
testIntegerExponentDoubleAndSmaller()
|
||||
let u = Float16(1).nextUp
|
||||
let d = Float16(1).nextDown
|
||||
@@ -109,6 +115,7 @@ extension Float16 {
|
||||
extension Float {
|
||||
static func testIntegerExponent() {
|
||||
testIntegerExponentCommon()
|
||||
testIntegerExponentOverflowAndUnderflow()
|
||||
testIntegerExponentDoubleAndSmaller()
|
||||
let u = Float(1).nextUp
|
||||
let d = Float(1).nextDown
|
||||
@@ -135,6 +142,7 @@ extension Float {
|
||||
extension Double {
|
||||
static func testIntegerExponent() {
|
||||
testIntegerExponentCommon()
|
||||
testIntegerExponentOverflowAndUnderflow()
|
||||
// Following tests only make sense (and are only necessary) on 64b platforms.
|
||||
#if arch(arm64) || arch(x86_64)
|
||||
testIntegerExponentDoubleAndSmaller()
|
||||
@@ -193,6 +201,10 @@ final class IntegerExponentTests: XCTestCase {
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
func testFloat80() {
|
||||
Float80.testIntegerExponentCommon()
|
||||
// FreeBSD's powl(3) has a bug where a minus sign is not perserved on overflow/underflow.
|
||||
#if !os(FreeBSD)
|
||||
Float80.testIntegerExponentOverflowAndUnderflow()
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -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")
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64" OR "${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "powerpc64")
|
||||
set("${result_var_name}" "powerpc64" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64le")
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64le" OR "${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "powerpc64le")
|
||||
set("${result_var_name}" "powerpc64le" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "s390x")
|
||||
set("${result_var_name}" "s390x" PARENT_SCOPE)
|
||||
|
||||
Reference in new issue
Block a user