21 Commits
Author SHA1 Message Date
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
Stephen Canon f50a1acf2d Merge pull request #178 from kylemacomber/remove-xcodesamplecode-plist
Remove .xcodesamplecode.plist, which prevents editing markdown from Xcode
2021-03-23 09:03:31 -04:00
Stephen Canon 2aa93ccf24 Merge pull request #179 from stephentyrone/remove-workflows
remove workflows, no longer needed.
2021-03-21 16:01:56 -04:00
Steve (Numerics) Canon 50161d39df remove workflows, no longer needed. 2021-03-21 16:01:23 -04:00
Kyle Macomber d34cff5a13 Remove .xcodesamplecode.plist, which prevents editing markdown from Xcode 2021-03-19 12:40:59 -07:00
Stephen Canon 9f55a78685 Merge pull request #175 from stephentyrone/eighty-columns-wide-my-father-lies
80-column formatting for source doc comments
2021-03-03 20:01:35 -05:00
Steve (Numerics) Canon 5827f9a943 80-column formatting for source doc comments
Tidying, plus a few small edits. This commit should not include any code changes.
2021-03-03 14:01:09 -05:00
Stephen Canon 3cad9b69a0 Update README.md
Update version number in sample code.
2021-02-21 21:22:01 -05:00
12 changed files with 334 additions and 126 deletions

No files matched your search

-15
View File
@@ -1,15 +0,0 @@
name: Swift
on: [push]
jobs:
build:
runs-on: macOS-latest
steps:
- uses: actions/checkout@v1
- name: Build
run: swift build -v
- name: Run tests
run: swift test -v -c release
-5
View File
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array/>
</plist>
+17 -1
View File
@@ -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: "0.0.7"),
.package(url: "https://github.com/apple/swift-numerics", from: "1.0.0"),
```
2. Add `Numerics` as a dependency for your target:
@@ -56,6 +56,22 @@ To use Swift Numerics in a SwiftPM project:
3. Add `import Numerics` in your source code.
## 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, *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.
The definitions therein may therefore change at whim, and the entire module may be removed in any new release.
If you have a use case that requires underscored operations, please raise an issue to request that they be made public API.
Future minor versions of the package may introduce changes to these rules as needed.
We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate.
Accordingly, from time to time, we expect that new versions of this package will require clients to upgrade to a more recent Swift toolchain release.
Requiring a new Swift release will only require a minor version bump.
## Contributing to Swift Numerics
Swift Numerics is a standalone library that is separate from the core Swift project, but it will sometimes act as a staging ground for APIs that will later be incorporated into the Swift Standard Library.
+34 -8
View File
@@ -52,13 +52,31 @@ extension Complex: AdditiveArithmetic {
// 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)
}
}
@@ -126,8 +144,8 @@ extension Complex: AlgebraicField {
/// 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.
/// 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 {
@@ -139,16 +157,18 @@ extension Complex: AlgebraicField {
return self.divided(by: magnitude).normalized
}
/// The reciprocal of this value, if it can be computed without undue overflow or underflow.
/// 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.
/// 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.
///
/// Typical use looks like this:
/// 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, use multiply by reciprocal.
/// // If divisor is well-scaled, multiply by reciprocal.
/// if let recip = divisor.reciprocal {
/// return data.map { $0 * recip }
/// }
@@ -156,6 +176,12 @@ extension Complex: AlgebraicField {
/// 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
+16 -12
View File
@@ -163,9 +163,10 @@ extension Complex {
/// True if this value is normal.
///
/// A complex number is normal if it is finite and *either* the real or imaginary component is normal.
/// A floating-point number representing one of the components is normal if its exponent allows a full-
/// precision representation.
/// A complex number is normal if it is finite and *either* the real or
/// imaginary component is normal. A floating-point number representing
/// one of the components is normal if its exponent allows a full-precision
/// representation.
///
/// See also:
/// -
@@ -179,9 +180,10 @@ extension Complex {
/// True if this value is subnormal.
///
/// A complex number is subnormal if it is finite, not normal, and not zero. When the result of a
/// computation is subnormal, underflow has occurred and the result generally does not have full
/// precision.
/// A complex number is subnormal if it is finite, not normal, and not zero.
/// When the result of a computation is subnormal, underflow has occurred and
/// the result generally does not have full precision.
///
/// See also:
/// -
/// - `.isFinite`
@@ -194,7 +196,8 @@ extension Complex {
/// True if this value is zero.
///
/// A complex number is zero if *both* the real and imaginary components are zero.
/// A complex number is zero if *both* the real and imaginary components
/// are zero.
///
/// See also:
/// -
@@ -208,8 +211,8 @@ extension Complex {
/// The ∞-norm of the value (`max(abs(real), abs(imaginary))`).
///
/// If you need the Euclidean norm (a.k.a. 2-norm) use the `length` or `lengthSquared`
/// properties instead.
/// If you need the Euclidean norm (a.k.a. 2-norm) use the `length` or
/// `lengthSquared` properties instead.
///
/// Edge cases:
/// -
@@ -240,8 +243,8 @@ extension Complex {
/// This is mainly useful for interoperation with other languages, where
/// you may want to reduce each equivalence class to a single representative
/// before passing across language boundaries, but it may also be useful
/// for some serialization tasks. It's also a useful implementation detail for
/// some primitive operations.
/// for some serialization tasks. It's also a useful implementation detail
/// for some primitive operations.
@_transparent
public var canonicalized: Self {
if isZero { return .zero }
@@ -491,7 +494,8 @@ extension Complex {
///
/// Edge cases:
/// -
/// - Negative lengths are interpreted as reflecting the point through the origin, i.e.:
/// - Negative lengths are interpreted as reflecting the point through the
/// origin, i.e.:
/// ```
/// Complex(length: -r, phase: θ) == -Complex(length: r, phase: θ)
/// ```
+14 -12
View File
@@ -39,17 +39,19 @@ extension Complex: ElementaryFunctions {
// MARK: - exp-like functions
/// The complex exponential function e^z whose base `e` is the base of the natural logarithm.
/// The complex exponential function e^z whose base `e` is the base of the
/// natural logarithm.
///
/// Mathematically, this operation can be expanded in terms of the `Real` operations `exp`,
/// `cos` and `sin` as follows:
/// Mathematically, this operation can be expanded in terms of the `Real`
/// operations `exp`, `cos` and `sin` as follows:
/// ```
/// exp(x + iy) = exp(x) exp(iy)
/// = exp(x) cos(y) + i exp(x) sin(y)
/// ```
/// Note that naive evaluation of this expression in floating-point would be prone to premature
/// overflow, since `cos` and `sin` both have magnitude less than 1 for most inputs (i.e.
/// `exp(x)` may be infinity when `exp(x) cos(y)` would not be.
/// Note that naive evaluation of this expression in floating-point would be
/// prone to premature overflow, since `cos` and `sin` both have magnitude
/// less than 1 for most inputs (i.e. `exp(x)` may be infinity when
/// `exp(x) cos(y)` would not be).
@inlinable
public static func exp(_ z: Complex) -> Complex {
guard z.isFinite else { return z }
@@ -309,13 +311,13 @@ extension Complex: ElementaryFunctions {
// as exact head-tail products (u is guaranteed to be well scaled,
// v may underflow, but if it does it doesn't matter, the u term is
// all we need).
let (a,b) = Augmented.twoProdFMA(u, u)
let (c,d) = Augmented.twoProdFMA(v, v)
let (a,b) = Augmented.product(u, u)
let (c,d) = Augmented.product(v, v)
// It would be nice if we could simply use a - 1, but unfortunately
// we don't have a tight enough bound to guarantee that that expression
// is exact; a may be as small as 1/4, so we could lose a single bit
// to rounding if we did that.
var (s,e) = Augmented.fastTwoSum(-1, a)
var (s,e) = Augmented.sum(large: -1, small: a)
// Now we are ready to assemble the result. If cancellation happens,
// then |c| > |e| > |b|, |d|, so this assembly order is safe. It's
// also possible that |c| and |d| are small, but if that happens then
@@ -351,9 +353,9 @@ extension Complex: ElementaryFunctions {
// So now we need to evaluate (2+x)x + y² accurately. To do this,
// we employ augmented arithmetic; the key observation here is that
// cancellation is only a problem when y² ≈ -(2+x)x
let xp2 = Augmented.fastTwoSum(2, z.x) // Known that 2 > |x|.
let a = Augmented.twoProdFMA(z.x, xp2.head)
let y² = Augmented.twoProdFMA(z.y, z.y)
let xp2 = Augmented.sum(large: 2, small: z.x) // Known that 2 > |x|.
let a = Augmented.product(z.x, xp2.head)
let y² = Augmented.product(z.y, z.y)
let s = (a.head + y².head + a.tail + y².tail).addingProduct(z.x, xp2.tail)
return Complex(.log(onePlus: s)/2, θ)
}
+33 -9
View File
@@ -47,23 +47,47 @@
/// [field]: https://en.wikipedia.org/wiki/Field_(mathematics)
public protocol AlgebraicField: SignedNumeric {
/// Replaces a with the (approximate) quotient `a/b`.
static func /=(a: inout Self, b: Self)
/// The (approximate) quotient `a/b`.
static func /(a: Self, b: Self) -> Self
/// 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,
/// the result is nil.
///
/// If self is zero, or if a reciprocal would overflow or underflow such
/// that it cannot be accurately represented, the result is nil. Note that
/// `.zero.reciprocal`, somewhat surprisingly, is *not* nil for `Real` or
/// `Complex` types, because these types have an `.infinity` value that
/// acts as the reciprocal of `.zero`.
/// Note that `.zero.reciprocal`, somewhat surprisingly, is *not* nil
/// for `Real` or `Complex` types, because these types have an
/// `.infinity` value that acts as the reciprocal of `.zero`.
///
/// 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 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, or for the Complex types,
/// the results are identical.
///
/// A typical use case looks something like this:
/// ```
/// func divide<T: AlgebraicField>(data: [T], by divisor: T) -> [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 }
/// }
/// ```
var reciprocal: Self? { get }
}
+56 -35
View File
@@ -22,9 +22,10 @@ extension Numeric where Magnitude: FloatingPoint {
/// ```
///
/// The default value of `relativeTolerance` is `.ulpOfOne.squareRoot()`,
/// which corresponds to expecting "about half the digits" in the computed results to be good.
/// This is the usual guidance in numerical analysis, if you don't know anything about the
/// computation being performed, but is not suitable for all use cases.
/// which corresponds to expecting "about half the digits" in the computed
/// results to be good. This is the usual guidance in numerical analysis,
/// if you don't know anything about the computation being performed, but
/// is not suitable for all use cases.
///
/// Mathematical Properties:
/// ------------------------
@@ -34,16 +35,21 @@ extension Numeric where Magnitude: FloatingPoint {
///
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _symmetric_.
///
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is __not__ _transitive_.
/// Because of this, approximately equality is __not an equivalence relation__,
/// even when restricted to non-exceptional values.
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is __not__
/// _transitive_. Because of this, approximately equality is __not an
/// equivalence relation__, even when restricted to non-exceptional values.
///
/// - For any point `a`, the set of values that compare approximately equal to `a` is _convex_.
/// (Under the assumption that the `.magnitude` property implements a valid norm.)
/// This means that you must not use approximate equality to implement
/// a conformance to Equatable, as it will violate the invariants of
/// code written against that protocol.
///
/// - For any point `a`, the set of values that compare approximately equal
/// to `a` is _convex_. (Under the assumption that the `.magnitude`
/// property implements a valid norm.)
///
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _scale invariant_,
/// so long as no underflow or overflow has occured, and no exceptional value is produced
/// by the scaling.
/// so long as no underflow or overflow has occured, and no exceptional
/// value is produced by the scaling.
///
/// See Also:
/// -------
@@ -57,8 +63,9 @@ extension Numeric where Magnitude: FloatingPoint {
/// Defaults to `.ulpOfOne.squareRoot()`.
///
/// This value should be non-negative and less than or equal to 1.
/// This constraint on is only checked in debug builds, because a mathematically
/// well-defined result exists for any tolerance, even one out of range.
/// This constraint on is only checked in debug builds, because a
/// mathematically well-defined result exists for any tolerance,
/// even one out of range.
///
/// - norm: The [norm] to use for the comparison.
/// Defaults to `\.magnitude`.
@@ -99,13 +106,17 @@ extension Numeric where Magnitude: FloatingPoint {
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:)`
/// is _symmetric_.
///
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:)`
/// is __not__ _transitive_. Because of this, approximately equality is
/// __not an equivalence relation__, even when restricted to non-exceptional values.
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is __not__
/// _transitive_. Because of this, approximately equality is __not an
/// equivalence relation__, even when restricted to non-exceptional values.
///
/// - 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, which cannot be checked
/// by this function.)
/// This means that you must not use approximate equality to implement
/// a conformance to Equatable, as it will violate the invariants of
/// code written against that protocol.
///
/// - 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, which cannot be checked by this function.)
///
/// See Also:
/// -------
@@ -118,15 +129,17 @@ extension Numeric where Magnitude: FloatingPoint {
/// - absoluteTolerance: The absolute tolerance to use in the comparison.
///
/// This value should be non-negative and finite.
/// This constraint on is only checked in debug builds, because a mathematically
/// well-defined result exists for any tolerance, even one out of range.
/// This constraint on is only checked in debug builds, because a
/// mathematically well-defined result exists for any tolerance,
/// even one out of range.
///
/// - relativeTolerance: The relative tolerance to use in the comparison.
/// Defaults to zero.
///
/// This value should be non-negative and less than or equal to 1.
/// This constraint on is only checked in debug builds, because a mathematically
/// well-defined result exists for any tolerance, even one out of range.
/// This constraint on is only checked in debug builds, because a
/// mathematically well-defined result exists for any tolerance,
/// even one out of range.
@inlinable @inline(__always)
public func isApproximatelyEqual(
to other: Self,
@@ -143,7 +156,8 @@ extension Numeric where Magnitude: FloatingPoint {
}
extension AdditiveArithmetic {
/// Test if `self` and `other` are approximately equal with specified tolerances and norm.
/// Test if `self` and `other` are approximately equal with specified
/// tolerances and norm.
///
/// `true` if `self` and `other` are equal, or if they are finite and either
/// ```
@@ -166,11 +180,16 @@ extension AdditiveArithmetic {
///
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:norm:)`
/// is __not__ _transitive_. Because of this, approximately equality is
/// __not an equivalence relation__, even when restricted to non-exceptional values.
/// __not an equivalence relation__, even when restricted to
/// non-exceptional values.
///
/// - 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, which cannot be checked
/// by this function.)
/// This means that you must not use approximate equality to implement
/// a conformance to Equatable, as it will violate the invariants of
/// code written against that protocol.
///
/// - 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, which cannot be checked by this function or a protocol).
///
/// See Also:
/// -------
@@ -184,21 +203,23 @@ extension AdditiveArithmetic {
/// - absoluteTolerance: The absolute tolerance to use in the comparison.
///
/// This value should be non-negative and finite.
/// This constraint on is only checked in debug builds, because a mathematically
/// well-defined result exists for any tolerance, even one out of range.
/// This constraint on is only checked in debug builds, because a
/// mathematically well-defined result exists for any tolerance, even
/// one out of range.
///
/// - relativeTolerance: The relative tolerance to use in the comparison.
/// Defaults to zero.
///
/// This value should be non-negative and less than or equal to 1.
/// This constraint on is only checked in debug builds, because a mathematically
/// well-defined result exists for any tolerance, even one out of range.
/// This constraint on is only checked in debug builds, because a
/// mathematically well-defined result exists for any tolerance,
/// even one out of range.
///
/// - norm: The norm to use for the comparison.
/// Defaults to `\.magnitude`.
///
/// For example, if we wanted to test if a complex value was inside a circle of
/// radius 0.001 centered at (1 + 0i), we could use:
/// For example, if we wanted to test if a complex value was inside a
/// circle of radius 0.001 centered at (1 + 0i), we could use:
/// ```
/// z.isApproximatelyEqual(
/// to: 1,
@@ -206,8 +227,8 @@ extension AdditiveArithmetic {
/// norm: \.length
/// )
/// ```
/// (if we used the default, we would be testing if `z` were inside a square region
/// instead.)
/// (if we used the default norm, `.magnitude`, we would be testing if
/// `z` were inside a square region instead.)
@inlinable
public func isApproximatelyEqual<Magnitude>(
to other: Self,
+79 -2
View File
@@ -9,21 +9,98 @@
//
//===----------------------------------------------------------------------===//
/// 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 {
/// The product `a * b` represented as an implicit sum `head + tail`.
///
/// `head` is the correctly rounded value of `a*b`. If no overflow or
/// underflow occurs, `tail` represents the rounding error incurred in
/// computing `head`, such that the exact product is the sum of `head`
/// and `tail` computed without rounding.
///
/// 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`).
/// - When `head` is close to the underflow boundary, the rounding error
/// may not be representable due to underflow, and `tail` will be rounded.
/// If `head` is very small, `tail` may even be zero, even though the
/// product is not exact.
/// - 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 twoProdFMA<T:Real>(_ 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,
// falling back on the C math.h fma funcions, but may be slow on older x86.
let tail = (-head).addingProduct(a, 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 `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.
///
/// This operation is sometimes called "fastTwoSum".
///
/// - Parameters:
/// - a: The summand with larger magnitude.
/// - b: The summand with smaller magnitude.
///
/// 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`.
@_transparent
public static func fastTwoSum<T:Real>(_ a: T, _ b: T) -> (head: T, tail: T) {
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)
}
@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)
}
}
+23 -15
View File
@@ -24,18 +24,21 @@
/// let y = Float.sin(x) // 0.84147096
/// ```
///
/// There are three broad families of functions defined by `ElementaryFunctions`:
/// 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`.
/// `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:
/// 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.
@@ -50,7 +53,8 @@
///
/// [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.
/// The [exponential function][wiki] e^x whose base `e` is the base of the
/// natural logarithm.
///
/// See also:
/// -
@@ -63,19 +67,20 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// exp(x) - 1, computed in such a way as to maintain accuracy for small x.
///
/// When `x` is close to zero, the expression `.exp(x) - 1` suffers from catastrophic
/// cancellation and the result will not have full accuracy. The `.expMinusOne(x)` function gives
/// you a means to address this problem.
/// When `x` is close to zero, the expression `.exp(x) - 1` suffers from
/// 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` 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:
/// 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:
/// ```
/// let t = .expMinusOne(x)
/// return x*(t+1) + t // x*exp(x) + (exp(x)-1) = (x+1)*exp(x) - 1
/// ```
/// This re-written expression delivers an accurate result for all values of `x`, not just for
/// small values.
/// This re-written expression delivers an accurate result for all values
/// of `x`, not just for small values.
///
/// See also:
/// -
@@ -238,7 +243,8 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// The [arccosine][wiki] (inverse cosine) of `x`.
///
/// For real types, the result may be interpreted as an angle measured in radians.
/// For real types, the result may be interpreted as an angle measured in
/// radians.
/// ```
/// cos(acos(x)) ≅ x
/// ```
@@ -253,7 +259,8 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// The [arcsine][wiki] (inverse sine) of `x`.
///
/// For real types, the result may be interpreted as an angle measured in radians.
/// For real types, the result may be interpreted as an angle measured in
/// radians.
/// ```
/// sin(asin(x)) ≅ x
/// ```
@@ -268,7 +275,8 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// The [arctangent][wiki] (inverse tangent) of `x`.
///
/// For real types, the result may be interpreted as an angle measured in radians.
/// For real types, the result may be interpreted as an angle measured in
/// radians.
/// ```
/// tan(atan(x)) ≅ x
/// ```
+55 -6
View File
@@ -11,11 +11,12 @@
/// A type that models the real numbers.
///
/// Types conforming to this protocol provide the arithmetic and utility operations defined by
/// the `FloatingPoint` protocol, and provide all of the math functions defined by the
/// `ElementaryFunctions` and `RealFunctions` protocols. This protocol does not
/// add any additional conformances itself, but is very useful as a protocol against which to
/// write generic code. For example, we can naturally write a generic version of the a sigmoid
/// Types conforming to this protocol provide the arithmetic and utility
/// operations defined by the `FloatingPoint` protocol, and provide all of the
/// math functions defined by the `ElementaryFunctions` and `RealFunctions`
/// protocols. This protocol does not add any additional conformances itself,
/// but is very useful as a protocol against which to write generic code. For
/// example, we can naturally write a generic implementation of a sigmoid
/// function:
/// ```
/// func sigmoid<T: Real>(_ x: T) -> T {
@@ -34,7 +35,8 @@ public protocol Real: FloatingPoint, RealFunctions, AlgebraicField {
// 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.
// Most math libraries do not provide exp10, so we need a default
// implementation.
@_transparent
public static func exp10(_ x: Self) -> Self {
return pow(10, x)
@@ -97,6 +99,53 @@ extension Real {
return x.squareRoot()
}
/// The (approximate) reciprocal (multiplicative inverse) of this number,
/// if it is representable.
///
/// If `x` if finite and nonzero, and `1/x` overflows or underflows,
/// then `x.reciprocal` is `nil`. Otherwise, `a.reciprocal` is `1/x`.
///
/// 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.
///
/// A typical use case looks something like this:
/// ```
/// func divide<T: Real>(data: [T], by divisor: T) -> [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:
///
/// Multiplying by the reciprocal instead of dividing will slightly
/// perturb results. For example `5.0 / 3` is 1.6666666666666667, but
/// `5.0 * 3.reciprocal!` is 1.6666666666666665.
///
/// The error of a normal division is bounded by half an ulp of the
/// result; we can derive a quick error bound for multiplication by
/// 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 + δ₁ + δ₂ + δ₁δ₂)
/// ```
///
/// 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
/// results obtained using division, you should not use this.
@inlinable
public var reciprocal: Self? {
let recip = 1/self
+7 -6
View File
@@ -53,7 +53,8 @@ public protocol RealFunctions: ElementaryFunctions {
/// - `pow()`
static func exp10(_ x: Self) -> Self
/// `sqrt(x*x + y*y)`, computed in a manner that avoids spurious overflow or underflow.
/// `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 Γ(x).
@@ -97,12 +98,12 @@ public protocol RealFunctions: ElementaryFunctions {
/// 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.
/// 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 logarithm of the
/// absolute value of Γ(x), to recover the sign information.
/// 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.
///