diff --git a/Package.swift b/Package.swift index e7d6c85..f91f441 100644 --- a/Package.swift +++ b/Package.swift @@ -16,18 +16,18 @@ let package = Package( name: "swift-numerics", products: [ .library(name: "Complex", targets: ["Complex"]), - .library(name: "ElementaryFunctions", targets: ["ElementaryFunctions"]), .library(name: "Numerics", targets: ["Numerics"]), + .library(name: "Real", targets: ["Real"]), ], dependencies: [ ], targets: [ - .target(name: "Complex", dependencies: ["ElementaryFunctions"]), - .target(name: "ElementaryFunctions", dependencies: ["NumericsShims"]), - .target(name: "Numerics", dependencies: ["Complex", "ElementaryFunctions"]), + .target(name: "Complex", dependencies: ["Real"]), + .target(name: "Numerics", dependencies: ["Complex", "Real"]), .target(name: "NumericsShims", dependencies: []), + .target(name: "Real", dependencies: ["NumericsShims"]), - .testTarget(name: "ComplexTests", dependencies: ["Complex"]), - .testTarget(name: "ElementaryFunctionTests", dependencies: ["ElementaryFunctions"]), + .testTarget(name: "ComplexTests", dependencies: ["Complex", "NumericsShims"]), + .testTarget(name: "RealTests", dependencies: ["Real"]), ] ) diff --git a/README.md b/README.md index a03b9c5..1f95eee 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ To fix a bug, or make smaller improvements: 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) +1. [Real](Sources/Real/README.md) 2. [Complex](Sources/Complex/README.md) ## Future expansion diff --git a/Sources/Complex/Complex.swift b/Sources/Complex/Complex.swift index 3f97e05..5707784 100644 --- a/Sources/Complex/Complex.swift +++ b/Sources/Complex/Complex.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -import ElementaryFunctions +import Real /// A complex number represented by real and imaginary parts. /// diff --git a/Sources/Complex/README.md b/Sources/Complex/README.md index 2f6e274..65195b5 100644 --- a/Sources/Complex/README.md +++ b/Sources/Complex/README.md @@ -10,7 +10,7 @@ This module provides approximate feature parity and memory layout compatibility 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. +- The `Real` module. ## Design notes diff --git a/Sources/ElementaryFunctions/README.md b/Sources/ElementaryFunctions/README.md deleted file mode 100644 index a86d2ef..0000000 --- a/Sources/ElementaryFunctions/README.md +++ /dev/null @@ -1,70 +0,0 @@ -# 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: - -- 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). - -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`: -``` -import Numerics - -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: -``` -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`: -``` -func sigmoid(_ x: T) -> T { - 1 / (1 + .exp(-x)) -} -``` -## Protocols and Methods - -Types conforming to `ElementaryFunctions` provide the following static methods: - -- Exponential functions: `exp`, `expMinusOne` -- Logarithmic functions: `log`, `log(onePlus:)` -- Trigonometric functions: `cos`, `sin`, `tan` -- Inverse trigonometric functions: `acos`, `asin`, `atan` -- Hyperbolic functions: `cosh`, `sinh`, `tanh` -- 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: - -- `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. - -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]. - -### Dependencies: -- The C standard math library (`libm`) via the `NumericShims` target. - -[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 diff --git a/Sources/Numerics/Numerics.swift b/Sources/Numerics/Numerics.swift index 720613e..72e83f1 100644 --- a/Sources/Numerics/Numerics.swift +++ b/Sources/Numerics/Numerics.swift @@ -10,5 +10,5 @@ //===----------------------------------------------------------------------===// // A module that re-exports the complete Swift Numerics public API. -@_exported import ElementaryFunctions +@_exported import Real @_exported import Complex diff --git a/Sources/ElementaryFunctions/ElementaryFunctions.swift b/Sources/Real/ElementaryFunctions.swift similarity index 72% rename from Sources/ElementaryFunctions/ElementaryFunctions.swift rename to Sources/Real/ElementaryFunctions.swift index 3117466..4bba67a 100644 --- a/Sources/ElementaryFunctions/ElementaryFunctions.swift +++ b/Sources/Real/ElementaryFunctions.swift @@ -32,13 +32,18 @@ /// - Power and root functions: /// `pow`, `sqrt`, and `root`. /// -/// There is a second protocol, `RealFunctions`, which refines `ElementaryFunctions` -/// and includes additional operations which are more commonly used specifically with real -/// number types. +/// There are two other protocols that you are more likely to want to use directly: +/// +/// `RealFunctions` refines `ElementaryFunctions` and includes +/// additional functions specific to real number types. +/// +/// `Real` conforms to `RealFunctions` and `FloatingPoint`, and is the +/// protocol that you will want to use most often for generic code. /// /// See Also: /// - /// - `RealFunctions` +/// - `Real` /// /// [elfn]: http://en.wikipedia.org/wiki/Elementary_function public protocol ElementaryFunctions { @@ -311,124 +316,3 @@ public protocol ElementaryFunctions { /// static func root(_ x: Self, _ n: Int) -> Self } - -public protocol RealFunctions: ElementaryFunctions { - /// `atan(y/x)`, with sign selected according to the quadrant of `(x, y)`. - /// - /// See also: - /// - - /// - `atan()` - static func atan2(y: Self, x: Self) -> Self - - /// The error function evaluated at `x`. - /// - /// See also: - /// - - /// - `erfc()` - static func erf(_ x: Self) -> Self - - /// The complimentary error function evaluated at `x`. - /// - /// See also: - /// - - /// - `erf()` - static func erfc(_ x: Self) -> Self - - /// 2^x - /// - /// See also: - /// - - /// - `exp()` - /// - `expMinusOne()` - /// - `exp10()` - /// - `log2()` - /// - `pow()` - static func exp2(_ x: Self) -> Self - - /// 10^x - /// - /// See also: - /// - - /// - `exp()` - /// - `expMinusOne()` - /// - `exp2()` - /// - `log10()` - /// - `pow()` - static func exp10(_ x: Self) -> Self - - /// `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). - /// - /// See also: - /// - - /// - `logGamma()` - /// - `signGamma()` - static func gamma(_ x: Self) -> Self - - /// The base-2 logarithm of `x`. - /// - /// See also: - /// - - /// - `exp2()` - /// - `log()` - /// - `log(onePlus:)` - /// - `log10()` - static func log2(_ x: Self) -> Self - - /// The base-10 logarithm of `x`. - /// - /// See also: - /// - - /// - `exp10()` - /// - `log()` - /// - `log(onePlus:)` - /// - `log2()` - static func log10(_ x: Self) -> Self - -#if !os(Windows) - /// The logarithm of the absolute value of the gamma function, log(|Γ(x)|). - /// - /// Not available on Windows targets. - /// - /// See also: - /// - - /// - `gamma()` - /// - `signGamma()` - static func logGamma(_ x: Self) -> Self - - /// 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` whenver `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. - /// - /// Not available on Windows targets. - /// - /// See also: - /// - - /// - `gamma()` - /// - `logGamma()` - static func signGamma(_ x: Self) -> FloatingPointSign -#endif -} - -/// 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 -/// function: -/// ``` -/// func sigmoid(_ x: T) -> T { -/// return 1/(1 + .exp(-x)) -/// } -/// ``` -public protocol Real: FloatingPoint, RealFunctions { -} diff --git a/Sources/Real/README.md b/Sources/Real/README.md new file mode 100644 index 0000000..d17290c --- /dev/null +++ b/Sources/Real/README.md @@ -0,0 +1,70 @@ +# Real + +[SE-0246] proposed an API for "basic math functions" that would make operations like sine and logarithm available in generic contexts. +It was accepted, but because of limitations in the compiler, the API could not be added to the standard library in a source-stable manner. +The `Real` [module][Real] provides that API as a separate module so that you can use it right away to get access to the improved API for these operations in your projects. + +## Protocols and Methods + +The module defines three protocols. The most general is `ElementaryFunctions`, which makes the following functions available: +- Exponential functions: `exp`, `expMinusOne` +- Logarithmic functions: `log`, `log(onePlus:)` +- Trigonometric functions: `cos`, `sin`, `tan` +- Inverse trigonometric functions: `acos`, `asin`, `atan` +- Hyperbolic functions: `cosh`, `sinh`, `tanh` +- Inverse hyperbolic functions: `acosh`, `asinh`, `atanh` +- Power and root functions: `pow`, `sqrt`, `root` + +The `RealFunctions` protocol refines `ElementaryFunctions`, and adds operations that are difficult to define or implement over fields more general than the real numbers: +- `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. + +The protocol that you will use most often is `Real`, which describes a floating-point type equipped with the full set of basic math functions. +This is a great protocol to use in writing generic code, because it has all the basics that you need to implement most numeric functions. + +## Using Real + +First, either import `Real` directly or import the `Numerics` umbrella module. + +Suppose we were experimenting with some basic machine learning, and needed a generic [sigmoid function][Sigmoid] activation function: + +```swift +import Numerics + +func sigmoid(_ x: T) -> T { + 1 / (1 + .exp(-x)) +} +``` + +Or suppose we were implementing a DFT, and wanted to precompute weights for the transform; DFT weights are roots of unity: + +```swift +import Numerics + +extension Real { + // The real and imaginary parts of e^{-2πik/n} + static func dftWeight(k: Int, n: Int) -> (r: Self, i: Self) { + precondition(0 <= k && k < n, "k is out of range") + guard let N = Self(exactly: n) else { + preconditionFailure("n cannot be represented exactly.") + } + let theta = -2 * .pi * (Self(k) / N) + return (r: .cos(theta), i: .sin(theta)) + } +} +``` + +This gives us an implementation that works for `Float`, `Double`, and `Float80` if the target supports it. +When new basic floating-point types are added to Swift, like `Float16` or `Float128`, it will work for them as well. +Not having this protocol is a significant missing feature for numerical computing in Swift, and I'm really looking forward to seeing what people do with it. + +### Dependencies: +- The C standard math library (`libm`) via the `NumericShims` target. + +[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 diff --git a/Sources/ElementaryFunctions/Implementations.swift b/Sources/Real/Real.swift similarity index 77% rename from Sources/ElementaryFunctions/Implementations.swift rename to Sources/Real/Real.swift index af945ae..e1c246c 100644 --- a/Sources/ElementaryFunctions/Implementations.swift +++ b/Sources/Real/Real.swift @@ -1,4 +1,4 @@ -//===--- Implementations.swift --------------------------------*- swift -*-===// +//===--- Real.swift -------------------------------------------*- swift -*-===// // // This source file is part of the Swift Numerics open source project // @@ -9,6 +9,26 @@ // //===----------------------------------------------------------------------===// +/// 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 +/// function: +/// ``` +/// func sigmoid(_ x: T) -> T { +/// return 1/(1 + .exp(-x)) +/// } +/// ``` +/// See Also: +/// - +/// - `ElementaryFunctions` +/// - `RealFunctions` +public protocol Real: FloatingPoint, RealFunctions { +} + // While `Real` does not provide any additional customization points, // it does allow us to default the implementation of a few operations, // and also provides `signGamma`. diff --git a/Sources/Real/RealFunctions.swift b/Sources/Real/RealFunctions.swift new file mode 100644 index 0000000..10d4b5c --- /dev/null +++ b/Sources/Real/RealFunctions.swift @@ -0,0 +1,115 @@ +//===--- RealFunctions.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 +// +//===----------------------------------------------------------------------===// + +public protocol RealFunctions: ElementaryFunctions { + /// `atan(y/x)`, with sign selected according to the quadrant of `(x, y)`. + /// + /// See also: + /// - + /// - `atan()` + static func atan2(y: Self, x: Self) -> Self + + /// The error function evaluated at `x`. + /// + /// See also: + /// - + /// - `erfc()` + static func erf(_ x: Self) -> Self + + /// The complimentary error function evaluated at `x`. + /// + /// See also: + /// - + /// - `erf()` + static func erfc(_ x: Self) -> Self + + /// 2^x + /// + /// See also: + /// - + /// - `exp()` + /// - `expMinusOne()` + /// - `exp10()` + /// - `log2()` + /// - `pow()` + static func exp2(_ x: Self) -> Self + + /// 10^x + /// + /// See also: + /// - + /// - `exp()` + /// - `expMinusOne()` + /// - `exp2()` + /// - `log10()` + /// - `pow()` + static func exp10(_ x: Self) -> Self + + /// `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). + /// + /// See also: + /// - + /// - `logGamma()` + /// - `signGamma()` + static func gamma(_ x: Self) -> Self + + /// The base-2 logarithm of `x`. + /// + /// See also: + /// - + /// - `exp2()` + /// - `log()` + /// - `log(onePlus:)` + /// - `log10()` + static func log2(_ x: Self) -> Self + + /// The base-10 logarithm of `x`. + /// + /// See also: + /// - + /// - `exp10()` + /// - `log()` + /// - `log(onePlus:)` + /// - `log2()` + static func log10(_ x: Self) -> Self + +#if !os(Windows) + /// The logarithm of the absolute value of the gamma function, log(|Γ(x)|). + /// + /// Not available on Windows targets. + /// + /// See also: + /// - + /// - `gamma()` + /// - `signGamma()` + static func logGamma(_ x: Self) -> Self + + /// 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` whenver `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. + /// + /// Not available on Windows targets. + /// + /// See also: + /// - + /// - `gamma()` + /// - `logGamma()` + static func signGamma(_ x: Self) -> FloatingPointSign +#endif +} diff --git a/Sources/ElementaryFunctions/ScalarConformances.swift b/Sources/Real/ScalarConformances.swift similarity index 100% rename from Sources/ElementaryFunctions/ScalarConformances.swift rename to Sources/Real/ScalarConformances.swift diff --git a/Tests/ComplexTests/ArithmeticTests.swift b/Tests/ComplexTests/ArithmeticTests.swift index 17d49f0..000154d 100644 --- a/Tests/ComplexTests/ArithmeticTests.swift +++ b/Tests/ComplexTests/ArithmeticTests.swift @@ -11,7 +11,7 @@ import XCTest import Complex -import ElementaryFunctions +import Real // TODO: improve this to be a general-purpose complex comparison with tolerance func relativeError(_ a: Complex, _ b: Complex) -> T { diff --git a/Tests/ComplexTests/PropertyTests.swift b/Tests/ComplexTests/PropertyTests.swift index f9a55e3..475fd27 100644 --- a/Tests/ComplexTests/PropertyTests.swift +++ b/Tests/ComplexTests/PropertyTests.swift @@ -11,7 +11,7 @@ import XCTest import Complex -import ElementaryFunctions +import Real final class PropertyTests: XCTestCase { diff --git a/Tests/ElementaryFunctionTests/ElementaryFunctionTests.swift b/Tests/RealTests/RealTests.swift similarity index 99% rename from Tests/ElementaryFunctionTests/ElementaryFunctionTests.swift rename to Tests/RealTests/RealTests.swift index ce753bb..1f618ae 100644 --- a/Tests/ElementaryFunctionTests/ElementaryFunctionTests.swift +++ b/Tests/RealTests/RealTests.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// import XCTest -import ElementaryFunctions +import Real #if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android) typealias TestLiteralType = Float80