30 Commits
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
26 changed files with 351 additions and 187 deletions

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
name: Pull request
on:
pull_request:
types: [opened, reopened, synchronize]
jobs:
tests:
name: Test
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
with:
license_header_check_project_name: "Swift Numerics"
# https://github.com/apple/swift-numerics/issues/303
license_header_check_enabled: false
# https://github.com/apple/swift-numerics/issues/302
format_check_enabled: false
-3
View File
@@ -22,9 +22,6 @@ include(CTest)
include(SwiftSupport)
add_subdirectory(Sources)
if(BUILD_TESTING)
add_subdirectory(Tests)
endif()
get_property(SWIFT_NUMERICS_EXPORTS GLOBAL PROPERTY SWIFT_NUMERICS_EXPORTS)
export(TARGETS ${SWIFT_NUMERICS_EXPORTS}
+8 -2
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.0
// swift-tools-version:5.2
//===--- Package.swift ----------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
@@ -25,7 +25,13 @@ let package = Package(
// User-facing modules
.target(name: "ComplexModule", dependencies: ["RealModule"]),
.target(name: "Numerics", dependencies: ["ComplexModule", "RealModule"]),
.target(name: "RealModule", dependencies: ["_NumericsShims"]),
.target(
name: "RealModule",
dependencies: ["_NumericsShims"],
linkerSettings: [
.linkedLibrary("m", .when(platforms: [.linux, .android]))
]
),
// Implementation details
.target(name: "_NumericsShims", dependencies: []),
+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")
]
)
+18 -2
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.1.0"),
.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.
@@ -68,7 +84,7 @@ Swift Numerics uses GitHub issues to track bugs and features. We use pull reques
1. Raise an issue with the [new module] tag.
2. Raise a PR with an implementation sketch.
3. Once you have some consensus, ask an admin to create a feature branch against which PRs can be raised.
4. When the design has stabilized and is functional enough to be useful, raise a PR to merge the new module to master.
4. When the design has stabilized and is functional enough to be useful, raise a PR to merge the new module to main.
### How to propose a new feature for an existing module
+27 -3
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)
}
}
@@ -145,12 +163,12 @@ extension Complex: AlgebraicField {
/// 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.
/// 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 }
/// }
@@ -158,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
+4
View File
@@ -69,6 +69,10 @@ public struct Complex<RealType> where RealType: Real {
}
}
#if swift(>=5.5)
extension Complex: Sendable where RealType: Sendable { }
#endif
// MARK: - Basic properties
extension Complex {
/// The real part of this complex value.
@@ -311,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
@@ -353,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, θ)
}
@@ -413,14 +413,21 @@ extension Complex: ElementaryFunctions {
}
// MARK: - pow-like functions
/// `exp(w*log(z))`
///
/// Edge cases for this function are defined according to the defining
/// expression exp(w log(z)), except that we define pow(0, w) to be 0
/// instead of infinity when w is in the (strict) right half-plane, so that
/// we agree with RealType.pow on the positive real line.
@inlinable
public static func pow(_ z: Complex, _ w: Complex) -> Complex {
if z.isZero { return w.real > 0 ? zero : infinity }
return exp(w * log(z))
}
@inlinable
public static func pow(_ z: Complex, _ n: Int) -> Complex {
if z.isZero { return .zero }
if z.isZero { return n < 0 ? infinity : n == 0 ? one : zero }
// TODO: this implementation is not quite correct, because n may be
// rounded in conversion to RealType. This only effects very extreme
// cases, so we'll leave it alone for now.
+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 }
}
+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)
}
}
+1
View File
@@ -150,6 +150,7 @@ extension Double: Real {
@_transparent
public static func pow(_ x: Double, _ y: Double) -> Double {
guard x >= 0 else { return .nan }
if x == 0 && y == 0 { return .nan }
return libm_pow(x, y)
}
+12 -8
View File
@@ -292,20 +292,24 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// exp(y * log(x)) computed with additional internal precision.
///
/// See also:
/// -
/// - `sqrt()`
/// - `root()`
/// The edge-cases of this function are defined based on the behavior of the
/// expression `exp(y log x)`, matching IEEE 754's `powr` operation.
/// 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 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.
///
/// See also:
/// -
/// - `sqrt()`
/// - `root()`
/// 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`.
+1
View File
@@ -137,6 +137,7 @@ extension Float: Real {
@_transparent
public static func pow(_ x: Float, _ y: Float) -> Float {
guard x >= 0 else { return .nan }
if x == 0 && y == 0 { return .nan }
return libm_powf(x, y)
}
+1
View File
@@ -132,6 +132,7 @@ extension Float80: Real {
@_transparent
public static func pow(_ x: Float80, _ y: Float80) -> Float80 {
guard x >= 0 else { return .nan }
if x == 0 && y == 0 { return .nan }
return libm_powl(x, y)
}
+1 -1
View File
@@ -73,5 +73,5 @@ Not having this protocol is a significant missing feature for numerical computin
[ErrorFunction]: https://en.wikipedia.org/wiki/Error_function
[GammaFunction]: https://en.wikipedia.org/wiki/Gamma_function
[SE-0246]: https://github.com/apple/swift-evolution/blob/master/proposals/0246-mathable.md
[SE-0246]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0246-mathable.md
[Sigmoid]: https://en.wikipedia.org/wiki/Sigmoid_function
+47
View File
@@ -99,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
+2
View File
@@ -10,5 +10,7 @@ See https://swift.org/LICENSE.txt for license information
add_library(_NumericsShims INTERFACE)
target_include_directories(_NumericsShims INTERFACE
include)
target_link_libraries(_NumericsShims INTERFACE
$<$<PLATFORM_ID:Linux>:m>)
set_property(GLOBAL APPEND PROPERTY SWIFT_NUMERICS_EXPORTS _NumericsShims)
@@ -9,6 +9,10 @@
//
//===----------------------------------------------------------------------===//
#ifdef __cplusplus
extern "C" {
#endif
#define HEADER_SHIM static inline __attribute__((__always_inline__))
// This header uses most of the libm functions, but we don't want to end up
@@ -397,3 +401,7 @@ HEADER_SHIM double _numerics_muladd(double a, double b, double c) {
// No long-double muladd operation, because no one has built an FMA for it
// (except for Itanium, which Swift doesn't support).
#ifdef __cplusplus
}
#endif
+1
View File
@@ -10,6 +10,7 @@
//
//===----------------------------------------------------------------------===//
import RealModule
import ComplexModule
public func relativeError(_ tst: Float, _ ref: Double) -> Double {
+1 -1
View File
@@ -16,7 +16,7 @@ where Exponent: FixedWidthInteger,
RawSignificand: FixedWidthInteger { }
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
@available(macOS 11.0, iOS 14.0, watchOS 14.0, tvOS 7.0, *)
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
extension Float16: FixedWidthFloatingPoint { }
#endif
-24
View File
@@ -1,24 +0,0 @@
#[[
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
#]]
find_package(dispatch CONFIG QUIET)
find_package(Foundation CONFIG QUIET)
find_package(XCTest CONFIG QUIET)
add_subdirectory(ComplexTests)
add_subdirectory(RealTests)
add_executable(SwiftNumericsTestRunner
WindowsMain.swift)
target_link_libraries(SwiftNumericsTestRunner PRIVATE
ComplexTests
RealTests)
add_test(NAME SwiftNumericsTestRunner
COMMAND SwiftNumericsTestRunner)
-12
View File
@@ -1,12 +0,0 @@
//===--- LinuxMain.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
//
//===----------------------------------------------------------------------===//
fatalError("Use --enable-test-discovery to run Swift Numerics tests on Linux.")
+21 -1
View File
@@ -128,13 +128,30 @@ internal extension Real where Self: BinaryFloatingPoint {
}
}
extension Real {
static func powZeroChecks() {
// pow(_:Self,_:Self) is defined by exp(y log(x)) and has edge-cases to
// match. In particular, if x is zero, log(x) is -infinity, so pow(0,0)
// is exp(0 * -infinity) = exp(nan) = nan.
XCTAssertEqual(pow(0, -1 as Self), infinity)
XCTAssert(pow(0, 0 as Self).isNaN)
XCTAssertEqual(pow(0, 1 as Self), zero)
// pow(_:Self,_:Int) is defined by repeated multiplication or division,
// and hence pow(0, 0) is 1.
XCTAssertEqual(pow(0, -1), infinity)
XCTAssertEqual(pow(0, 0), 1)
XCTAssertEqual(pow(0, 1), zero)
}
}
final class ElementaryFunctionChecks: XCTestCase {
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
func testFloat16() {
if #available(macOS 11.0, iOS 14.0, watchOS 14.0, tvOS 7.0, *) {
if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
Float16.elementaryFunctionChecks()
Float16.realFunctionChecks()
Float16.powZeroChecks()
}
}
#endif
@@ -142,17 +159,20 @@ final class ElementaryFunctionChecks: XCTestCase {
func testFloat() {
Float.elementaryFunctionChecks()
Float.realFunctionChecks()
Float.powZeroChecks()
}
func testDouble() {
Double.elementaryFunctionChecks()
Double.realFunctionChecks()
Double.powZeroChecks()
}
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
func testFloat80() {
Float80.elementaryFunctionChecks()
Float80.realFunctionChecks()
Float80.powZeroChecks()
}
#endif
}
+1 -1
View File
@@ -176,7 +176,7 @@ final class IntegerExponentTests: XCTestCase {
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
func testFloat16() {
if #available(macOS 11.0, iOS 14.0, watchOS 14.0, tvOS 7.0, *) {
if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
Float16.testIntegerExponent()
}
}
-109
View File
@@ -1,109 +0,0 @@
//===--- WindowsMain.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
//
//===----------------------------------------------------------------------===//
#if os(Windows)
import XCTest
@testable
import RealTests
@testable
import ComplexTests
extension ComplexTests.ApproximateEqualityTests {
static var all = testCase([
("testFloat", ComplexTests.ApproximateEqualityTests.testFloat),
("testDouble", ComplexTests.ApproximateEqualityTests.testDouble),
])
}
extension RealTests.ApproximateEqualityTests {
static var all = testCase([
("testFloat", RealTests.ApproximateEqualityTests.testFloat),
("testDouble", RealTests.ApproximateEqualityTests.testDouble),
])
}
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
extension ElementaryFunctionChecks {
static var all = testCase([
("testFloat16", ElementaryFunctionChecks.testFloat16),
("testFloat", ElementaryFunctionChecks.testFloat),
("testDouble", ElementaryFunctionChecks.testDouble),
])
}
extension IntegerExponentTests {
static var all = testCase([
("testFloat16", IntegerExponentTests.testFloat16),
("testFloat", IntegerExponentTests.testFloat),
("testDouble", IntegerExponentTests.testDouble),
])
}
#else
extension ElementaryFunctionChecks {
static var all = testCase([
("testFloat", ElementaryFunctionChecks.testFloat),
("testDouble", ElementaryFunctionChecks.testDouble),
])
}
extension IntegerExponentTests {
static var all = testCase([
("testFloat", IntegerExponentTests.testFloat),
("testDouble", IntegerExponentTests.testDouble),
])
}
#endif
extension ArithmeticTests {
static var all = testCase([
("testPolar", ArithmeticTests.testPolar),
("testBaudinSmith", ArithmeticTests.testBaudinSmith),
("testDivisionByZero", ArithmeticTests.testDivisionByZero),
])
}
extension PropertyTests {
static var all = testCase([
("testProperties", PropertyTests.testProperties),
("testEquatableHashable", PropertyTests.testEquatableHashable),
("testCodable", PropertyTests.testCodable),
])
}
var testCases = [
ComplexTests.ApproximateEqualityTests.all,
RealTests.ApproximateEqualityTests.all,
ElementaryFunctionChecks.all,
IntegerExponentTests.all,
ArithmeticTests.all,
PropertyTests.all,
]
#if swift(>=5.3) && canImport(_Differentiation)
extension DifferentiableTests {
static var all = testCase([
("testComponentGetter", DifferentiableTests.testComponentGetter),
("testInitializer", DifferentiableTests.testInitializer),
("testConjugate", DifferentiableTests.testConjugate),
("testArithmetics", DifferentiableTests.testArithmetics),
])
}
testCases += [
DifferentiableTests.all
]
#endif
XCTMain(testCases)
#endif
+6 -2
View File
@@ -17,8 +17,12 @@ See https://swift.org/LICENSE.txt for license information
function(get_swift_host_arch result_var_name)
if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64")
set("${result_var_name}" "x86_64" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "aarch64")
set("${result_var_name}" "aarch64" PARENT_SCOPE)
elseif ("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "AArch64|aarch64|arm64")
if(CMAKE_SYSTEM_NAME MATCHES Darwin)
set("${result_var_name}" "arm64" PARENT_SCOPE)
else()
set("${result_var_name}" "aarch64" PARENT_SCOPE)
endif()
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64")
set("${result_var_name}" "powerpc64" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64le")