Merge pull request #30 from stephentyrone/rename-elfns

Rename `ElementaryFunctions` module -> `Real`
This commit is contained in:
Stephen Canon authored and GitHub committed 2019-11-06 16:50:32 -05:00
commit 89df234fb6
14 files changed
+227 -208

No files matched your search

+6 -6
View File
@@ -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"]),
]
)
+1 -1
View File
@@ -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
+1 -1
View File
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
import ElementaryFunctions
import Real
/// A complex number represented by real and imaginary parts.
///
+1 -1
View File
@@ -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
-70
View File
@@ -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<T: Real>(_ 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
+1 -1
View File
@@ -10,5 +10,5 @@
//===----------------------------------------------------------------------===//
// A module that re-exports the complete Swift Numerics public API.
@_exported import ElementaryFunctions
@_exported import Real
@_exported import Complex
@@ -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<T: Real>(_ x: T) -> T {
/// return 1/(1 + .exp(-x))
/// }
/// ```
public protocol Real: FloatingPoint, RealFunctions {
}
+70
View File
@@ -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<T: Real>(_ 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
@@ -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<T: Real>(_ 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`.
+115
View File
@@ -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
}
+1 -1
View File
@@ -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<T>(_ a: Complex<T>, _ b: Complex<T>) -> T {
+1 -1
View File
@@ -11,7 +11,7 @@
import XCTest
import Complex
import ElementaryFunctions
import Real
final class PropertyTests: XCTestCase {
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
import XCTest
import ElementaryFunctions
import Real
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
typealias TestLiteralType = Float80