diff --git a/README.md b/README.md index 258d343..a03b9c5 100644 --- a/README.md +++ b/README.md @@ -4,75 +4,51 @@ Swift Numerics provides a set of modules that support numerical computing in Swift. These modules fall broadly in two categories: -- API that is too specialized to go into the standard library, but which is sufficiently -general to be centralized in a single common package. -- API that is under active development toward possible future inclusion in the -standard library. +- API that is too specialized to go into the standard library, but which is sufficiently general to be centralized in a single common package. +- API that is under active development toward possible future inclusion in the standard library. -There is some overlap between these two categories, and API that begins in the first -category may migrate to the second as it matures and new uses are discovered. +There is some overlap between these two categories, and API that begins in the first category may migrate to the second as it matures and new uses are discovered. -Swift Numerics modules are fine-grained; if you need support for Complex numbers, -you can import the Complex module without pulling in everything else in the library as -well: +Swift Numerics modules are fine-grained; if you need support for Complex numbers, you can import the Complex module without pulling in everything else in the library as well: ``` import Complex let z = Complex.i ``` -However, there is also a top-level `Numerics` module that simply re-exports the complete -public interface of swift-numerics: +However, there is also a top-level `Numerics` module that simply re-exports the complete public interface of swift-numerics: ``` import Numerics // All swift-numerics API is now available ``` -Swift Numerics modules have minimal dependencies on other projects. The current -modules assume only the availability of the Swift and C standard libraries, and the -runtime support provided by compiler-rt. Future expansion may assume the availability -of other standard interfaces such as BLAS and LAPACK, but modules with more -specialized dependencies (or dependencies that are not available on all platforms -supported by Swift) belong in a separate package. +Swift Numerics modules have minimal dependencies on other projects. +The current modules assume only the availability of the Swift and C standard libraries, and the runtime support provided by compiler-rt. +Future expansion may assume the availability of other standard interfaces such as BLAS and LAPACK, but modules with more specialized dependencies (or dependencies that are not available on all platforms supported by Swift) belong in a separate package. + +Because our intention is to make it possible to adopt Swift Numerics modules in the standard library at some future point, Swift Numerics uses the same license and contribution guidelines as the Swift project. ## Process -Swift Numerics is a standalone library separate from the core Swift project. In practice -it will act as a staging ground for some APIs that may eventually be incorporated into -the Swift Standard Library, and when that happens such changes will be proposed -to the Swift Standard Library using the established evolution process of the Swift -project. +Swift Numerics is a standalone library separate from the core Swift project. +In practice it will act as a staging ground for some APIs that may eventually be incorporated into the Swift Standard Library, and when that happens such changes will be proposed to the Swift Standard Library using the established evolution process of the Swift project. -It's practice to keep this process in mind, and document *why* you're making the -decisions that you are, so that reviewers can refer to those rationales if a module -comes up for Swift Evolution in the future. - -Because our intention is to make it possible to adopt Swift Numerics modules in the -standard library at some future point, Swift Numerics uses the same license and -contribution guidelines as the Swift project. - -Swift Numerics uses github issues to track bugs and features, and pull requests for -development. +Swift Numerics uses github issues to track bugs and features, and pull requests for development. To propose a new module: 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. +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. To propose a new feature for an existing module: 1. Raise an issue with the [enhancement] tag. 2. Raise a PR with an implementation, and discuss the implementation there. -3. Once there is consensus that the new feature is desirable and the design is suitable, -it can be merged. +3. Once there is consensus that the new feature is desirable and the design is suitable, it can be merged. To fix a bug, or make smaller improvements: -1. Raise a PR with your change. Be sure to add test coverage for whatever changes -you are making. +1. Raise a PR with your change. Be sure to add test coverage for whatever changes you are making. -Questions about how to use Swift Numerics modules, or issues that are not clearly -bugs can be discussed in the "Swift Numerics" section of the Swift forums. +Questions about how to use Swift Numerics modules, or issues that are not clearly bugs can be discussed in the "Swift Numerics" section of the Swift forums. ## Modules 1. [Elementary Functions](Sources/ElementaryFunctions/README.md) diff --git a/Sources/Complex/README.md b/Sources/Complex/README.md index d312ed0..ebbeb15 100644 --- a/Sources/Complex/README.md +++ b/Sources/Complex/README.md @@ -5,14 +5,9 @@ This module provides a `Complex` number type generic over an underlying `RealTyp 1> import Complex 2> let z = Complex(1,1) // z = 1 + i ``` -This module provides approximate feature parity and memory layout compatibility with C, -Fortran, and C++ complex types (although the importer cannot map the types for you, -buffers may be reinterpreted to shim API defined in other languages). +This module provides approximate feature parity and memory layout compatibility with C, Fortran, and C++ complex types (although the importer cannot map the types for you, buffers may be reinterpreted to shim API defined in other languages). -The usual arithmetic operators are provided for Complex numbers, as well as -conversion to and from polar coordinates and many useful properties, plus -conformances to the obvious usual protocols: `Equatable`, `Hashable`, `Codable` -(if the underlying `RealType` is), and `Numeric` (hence also `AdditiveArithmetic`). +The usual arithmetic operators are provided for Complex numbers, as well as conversion to and from polar coordinates and many useful properties, plus conformances to the obvious usual protocols: `Equatable`, `Hashable`, `Codable` (if the underlying `RealType` is), and `Numeric` (hence also `AdditiveArithmetic`). ### Dependencies: - The `ElementaryFunctions` module. @@ -20,22 +15,19 @@ conformances to the obvious usual protocols: `Equatable`, `Hashable`, `Codable` ## Design notes ### Mixed real-complex arithmetic. -It is tempting to define real-complex arithmetic operators, because we use them as -shorthand all the time in mathematics: `z + x` or `2w`. They are not provided by the -Complex module for two reasons: +It is tempting to define real-complex arithmetic operators, because we use them as shorthand all the time in mathematics: `z + x` or `2w`. +They are not provided by the Complex module for two reasons: - Swift generally avoids heterogenous arithmetic operators - They lead to counter-intuitive behavior of type inference. -For a concrete example of the second point, suppose that heterogeneous arithmetic -operators existed, and consider the following snippet: +For a concrete example of the second point, suppose that heterogeneous arithmetic operators existed, and consider the following snippet: ```swift let a: RealType = 1 let b = 2*a ``` what is the type of `b`? -If there is no type context, `b` is ambiguous; `2*a` could be interpreted as -`Complex(2)*a` or as `RealType(2)*a`. That's fairly annoying on its own. However, -suppose that we're in a `Complex` type context: +If there is no type context, `b` is ambiguous; `2*a` could be interpreted as `Complex(2)*a` or as `RealType(2)*a`. +That's annoying on its own. However, suppose that we're in a `Complex` type context: ```swift extension Complex { static func doSomething() { @@ -48,52 +40,34 @@ This is a show-stopper for heterogeneous arithmetic operators in the short term. ### Infinity and nan C and C++ attempt to define precise semantics that interpret the sign of infinity and zero. -This is occasionally useful, but it also results in a lot of extra work. The Swift Numerics -`Complex` type does not assign any semantic meaning to the sign of zero and infinity; -`(±0,±0)`, are all considered to be encodings of the value zero. Similarly, `(±inf, y)`, -`(x, ±inf)`, `(nan, y)` and `(x, nan)` are all considered to be encodings of a single -exceptional value with infinite magnitude and undefined phase. +This is occasionally useful, but it also results in a lot of extra work. +The Swift Numerics `Complex` type does not assign any semantic meaning to the sign of zero and infinity; `(±0,±0)`, are all considered to be encodings of the value zero. +Similarly, `(±inf, y)`, `(x, ±inf)`, `(nan, y)` and `(x, nan)` are all considered to be encodings of a single exceptional value with infinite magnitude and undefined phase. -Because the phase is undefined, the `real` and `imaginary` properties return `.nan` -for non-finite values. This decision might be revisited once users gain some experience -working with the type to make sure that it's a tradeoff that we're happy with, but early -experiments show that it greatly simplifies the implementation of some operations -without significant tradeoffs in usability. +Because the phase is undefined, the `real` and `imaginary` properties return `.nan` for non-finite values. +This decision might be revisited once users gain some experience working with the type to make sure that it's a tradeoff that we're happy with, but early experiments show that it greatly simplifies the implementation of some operations without significant tradeoffs in usability. ### The magnitude property -The `Numeric` protocol requires a `.magnitude` property, but (deliberately) does not -fully specify the semantics. The most obvious choice would be to use the Euclidean -norm (`sqrt(real*real + imaginary*imaginary)`). However, in practice there are -good reasons to use something else instead: +The `Numeric` protocol requires a `.magnitude` property, but (deliberately) does not fully specify the semantics. +The most obvious choice for `Complex` would be to use the Euclidean norm (aka the "2-norm", given by `sqrt(real*real + imaginary*imaginary)`). +However, in practice there are good reasons to use something else instead: -- The two-norm requires special care to avoid spurious overflow/underflow, but the -naive expressions for the 1-norm or ∞-norm are always correct. -- Even when care is used, near the overflow boundary the two-norm may not be -representable. The ∞-norm in particular is always representable (because of this, -the ∞-norm would seem to be the obvious alternative; it gives the nicest API surface). -- Both the 1-norm and ∞-norm are much easier to compute for operators than the -2-norm (O(n) vs. "no closed form expression, but usually O(n^3) iterative methods"), -so it would be nice to establish a precedent of .magnitude binding one of these -cheaper-to-compute norms. +- The 2-norm requires special care to avoid spurious overflow/underflow, but the naive expressions for the 1-norm ("taxicab norm") or ∞-norm ("sup norm") are always correct. +- Even when care is used, near the overflow boundary the 2-norm and the 1-norm are not representable. + As an example, consider `z = Complex(big, big)`, where `big` is `Double.greatestFiniteMagnitude`. The 1-norm and 2-norm of `z` both overflow (the 1-norm would be `2*big`, and the 2-norm would be `sqrt(2)*big`, neither of which are representable as `Double`), but the ∞-norm is always equal to either `real` or `imaginary`, so it is guaranteed to be representable. +Because of this, the ∞-norm is the obvious alternative; it gives the nicest API surface. +- If we consider the magnitude of more exotic types, like operators, the 1-norm and ∞-norm are significantly easier to compute than the 2-norm (O(n) vs. "no closed form expression, but O(n^3) iterative methods"), so it is nice to establish a precedent of `.magnitude` binding one of these cheaper-to-compute norms. +- The ∞-norm is heavily used in other computational libraries; for example, it is used by the `izamax` and `icamax` functions in BLAS. The 2-norm still needs to be available, of course, because sometimes you need it. -Presently, this functionality is accessed via the `.length` and `.unsafeLengthSquared` -properties, but I expect that we will end up iterating on this aspect of the design. +This functionality is accessed via the `.length` and `.unsafeLengthSquared` properties. ### Accuracy of division and multiplication -This library attempts to provide robust division and multiplication operations, with -small relative error in a complex norm. It is a non-goal to deliver small componentwise -errors. See `testDivide_BaudinSmithApprox` for examples of cases where we have -tiny relative error but large error in one of the result components considered in isolation. -This is the right tradeoff for a general-purpose library because it allows us to use the -naive formulas for multiplication and division (which are fast), and do a simple check to -see if we need to re-do the computation more carefully to avoid spurious overflow or -underflow. +This library attempts to provide robust division and multiplication operations, with small relative error in a complex norm. It is a non-goal to deliver small componentwise errors. +See `testBaudinSmith` in `ComplexTests.swift` for examples of cases where we have tiny relative error but large error in one of the result components considered in isolation. +This is the right tradeoff for a general-purpose library because it allows us to use the naive formulas for multiplication and division (which are fast), and do a simple check to see if we need to re-do the computation more carefully to avoid spurious overflow or underflow. +It's also about as accurate as multiplication. -Implementing the method of Baudin and Smith (or any other method that delivers -similarly small componentwise error) would unduly slow down the common case for -relatively little benefit--componentwise error bounds are rarely necessary when -working over the complex numbers. +Implementing the method of Baudin and Smith (or any other method that delivers similarly small componentwise error) would unduly slow down the common case for relatively little benefit--componentwise error bounds are rarely necessary when working over the complex numbers. -That said, a PR that implements multiplication and division *functions* with tight -componentwise error bounds would be a welcome addition to the library. +That said, a PR that implements multiplication and division *functions* with tight componentwise error bounds would be a welcome addition to the library. diff --git a/Sources/ElementaryFunctions/README.md b/Sources/ElementaryFunctions/README.md index a0cde5f..a86d2ef 100644 --- a/Sources/ElementaryFunctions/README.md +++ b/Sources/ElementaryFunctions/README.md @@ -1,33 +1,20 @@ # Elementary Functions -This module implements [SE-0246]. It is implemented in Swift Numerics to work -around difficulties that blocked adding these operations to the standard library for 5.1: +This module implements [SE-0246]. +It is implemented in Swift Numerics to work around difficulties that blocked adding these operations to the standard library for 5.1: -- Swift does not yet have a way to back-deploy protocol conformances; this prevents -making this useful feature available on older Apple OS targets. +- Swift does not yet have a way to back-deploy protocol conformances; this prevents making this useful feature available on older Apple OS targets. +- The lack of means to back-deploy prevents obsoleting the existing concrete math functions defined in the Darwin (Apple platforms), Glibc (Linux), and MSVCRT (Windows) modules. +- There is an outstanding bug with name resolution, which causes the new static functions (`Float.sin`) to shadow the existing free functions (`sin(_ x: Float) -> Float`) even in contexts where static functions are not allowed, leading to a number of spurious errors. + See https://github.com/apple/swift/pull/25316 for discussion of how this might be addressed in the future +- There are some typechecker performance regressions (partially resulting from the issues described above). -- The lack of means to back-deploy prevents obsoleting the existing concrete -math functions defined in the Darwin (Apple platforms), Glibc (Linux), and MSVCRT -(Windows) modules. - -- There is an outstanding bug with name resolution, which causes the new static functions -(`Float.sin`) to shadow the existing free functions (`sin(_ x: Float) -> Float`) even -in contexts where static functions are not allowed, leading to a number of spurious errors. -See https://github.com/apple/swift/pull/25316 for discussion of how to fix this. - -- There are some typechecker performance regressions (partially resulting from the issues -described above). - -Placing this module in Swift Numerics first gives the community a chance to address -some of the compiler limitations that this feature ran into *before* it lands in the standard -library (avoiding unnecessary source churn for projects that use these features), while also -making it available *now*, including back-deployment to older Apple OS targets. +Placing this module in Swift Numerics first gives the community a chance to address some of the compiler limitations that this feature ran into *before* it lands in the standard library (avoiding unnecessary source churn for projects that use these features), while also making it available *now*, including back-deployment to older Apple OS targets. ## Using Elementary Functions -First, either import `ElementaryFunctions` directly or import the `Numerics` umbrella -module. This makes all the elementary functions available on `Float`, `Double`, -and--on platforms that support it--`Float80`: +First, either import `ElementaryFunctions` directly or import the `Numerics` umbrella module. +This makes all the elementary functions available on `Float`, `Double`, and--on platforms that support it--`Float80`: ``` import Numerics @@ -35,16 +22,13 @@ func sigmoid(_ x: Double) -> Double { 1 / (1 + Double.exp(-x)) } ``` -As always, in many contexts we can elide the explicit type on the static -method, which yields a more fluent alternative style: +As always, in many contexts we can elide the explicit type on the static method, which yields a more fluent alternative style: ``` func sigmoid(_ x: Double) -> Double { 1 / (1 + .exp(-x)) } ``` - -When writing generic code, you will most often want to use the `Real` protocol, which -implies conformance to `ElementaryFunctions`, `RealFunctions`, and `FloatingPoint`: +When writing generic code, you will most often want to use the `Real` protocol, which implies conformance to `ElementaryFunctions`, `RealFunctions`, and `FloatingPoint`: ``` func sigmoid(_ x: T) -> T { 1 / (1 + .exp(-x)) @@ -62,28 +46,19 @@ Types conforming to `ElementaryFunctions` provide the following static methods: - Inverse hyperbolic functions: `acosh`, `asinh`, `atanh` - Power and root functions: `pow`, `sqrt`, `root` -The protocol `RealFunctions` refines `ElementaryFunctions`, and adds -the following static methods, which either only make sense for real types, -or are unusually difficult to implement well for arbitrary types: +The protocol `RealFunctions` refines `ElementaryFunctions`, and adds the following static methods, which either only make sense for real types, or are unusually difficult to implement well for arbitrary types: -- `atan2(y:x:)`, which computes `atan(y/x)` with sign chosen by the -quadrant of the point `(x,y)` in the Cartesian plane. -- `hypot`, which computes `sqrt(x*x + y*y)` without intermediate -overflow or underflow. +- `atan2(y:x:)`, which computes `atan(y/x)` with sign chosen by the quadrant of the point `(x,y)` in the Cartesian plane. +- `hypot`, which computes `sqrt(x*x + y*y)` without intermediate overflow or underflow. - `erf` and `erfc`, the [error function][ErrorFunction] and its complement. - Exponential functions: `exp2` and `exp10` - Logarithmetic functions: `log2` and `log10` -- Gamma functions: `gamma`, `logGamma`, and `signGamma`, which evaluate -the [gamma function][GammaFunction], its logarithm, and its sign. -Note that the Windows runtime does not implement the `lgamma_r` or `lgamma` -C functions, so `logGamma` and `signGamma` are not available when targeting Windows. +- Gamma functions: `gamma`, `logGamma`, and `signGamma`, which evaluate the [gamma function][GammaFunction], its logarithm, and its sign. + Note that the Windows runtime does not implement the `lgamma_r` or `lgamma` C functions, so `logGamma` and `signGamma` are not available when targeting Windows. -The protocol `Real` further refines `RealFunctions`, adding conformance -to `FloatingPoint` and no additional operations. This is the protocol -that you will want to use most often while writing generic code; it provides -a good set of useful operations without being overly restrictive. In -particular, algorithms written against `Real` will work with `Float`, `Double` -and `Float80`. +The protocol `Real` further refines `RealFunctions`, adding conformance to `FloatingPoint` and no additional operations. +This is the protocol that you will want to use most often while writing generic code; it provides a good set of useful operations without being overly restrictive. +In particular, algorithms written against `Real` will work with `Float`, `Double` and `Float80`. Further details can be found in the [SE-0246 proposal document][SE-0246]. diff --git a/Sources/Numerics/README.md b/Sources/Numerics/README.md new file mode 100644 index 0000000..d9de275 --- /dev/null +++ b/Sources/Numerics/README.md @@ -0,0 +1,7 @@ +# Numerics + +This umbrella module provides an easy way to get access to *all* of the Swift Numerics +API with a single import statement: +``` +import Numerics +``` diff --git a/Sources/NumericsShims/README.md b/Sources/NumericsShims/README.md new file mode 100644 index 0000000..90a0a21 --- /dev/null +++ b/Sources/NumericsShims/README.md @@ -0,0 +1,6 @@ +# Numerics Shims + +This module provides no stable Swift API. +It is an internal implementation detail of other Swift Numerics modules, providing access to builtins and assembly by wrapping them in static inline C functions. + +Within the standard library, this is achieved via the Builtin module instead, but because Swift Numerics is a separate project, it should not be built with the flags that are needed to enable access to the Builtin module.