mirror of
https://github.com/apple/swift-numerics
synced 2026-11-22 04:30:45 +00:00
Compare commits
95
Commits
0.0.7
...
release/1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
876f439c4a | ||
|
|
96df03d007 | ||
|
|
f412cea212 | ||
|
|
8b28aba874 | ||
|
|
e29c31deb4 | ||
|
|
e0ec0f5f3a | ||
|
|
aa76ee5658 | ||
|
|
d42ab140f7 | ||
|
|
77b98fab75 | ||
|
|
ba43341621 | ||
|
|
6a3ecdb480 | ||
|
|
803aae1ef0 | ||
|
|
db4ef5686a | ||
|
|
a85dd8c2bb | ||
|
|
0a5bc04095 | ||
|
|
a6bea6639c | ||
|
|
0a23770641 | ||
|
|
d560765047 | ||
|
|
1e5cbc4e21 | ||
|
|
b4ec7556e9 | ||
|
|
79f6025798 | ||
|
|
03c5840722 | ||
|
|
ed66862a2c | ||
|
|
bcde4bc513 | ||
|
|
58f95289a0 | ||
|
|
832dac1ef8 | ||
|
|
419caa222f | ||
|
|
5a0aedbccd | ||
|
|
8e3d889b5f | ||
|
|
92f0095962 | ||
|
|
f50a1acf2d | ||
|
|
2aa93ccf24 | ||
|
|
50161d39df | ||
|
|
d34cff5a13 | ||
|
|
9f55a78685 | ||
|
|
5827f9a943 | ||
|
|
3cad9b69a0 | ||
|
|
6583ac70c3 | ||
|
|
97852afaf5 | ||
|
|
105b59b8a4 | ||
|
|
0cf166da79 | ||
|
|
4a2cbc186b | ||
|
|
5a7eb37c19 | ||
|
|
198da2adf9 | ||
|
|
26c51aca1b | ||
|
|
c5a3504143 | ||
|
|
00c6183670 | ||
|
|
ae364a28f0 | ||
|
|
e042c13415 | ||
|
|
16837299c1 | ||
|
|
0c066bd268 | ||
|
|
2b4c6701f2 | ||
|
|
874c767424 | ||
|
|
0ee972ff92 | ||
|
|
754cbd9e2e | ||
|
|
209a794eb6 | ||
|
|
af19aec6ff | ||
|
|
ed8fc21f1e | ||
|
|
1cbb94ac71 | ||
|
|
0b2dc469ed | ||
|
|
efbe11a734 | ||
|
|
4798b68203 | ||
|
|
5f408c0121 | ||
|
|
09beddce47 | ||
|
|
2179fa1f82 | ||
|
|
6d9de5d4ce | ||
|
|
e20b32d40f | ||
|
|
21282166fa | ||
|
|
6b24333510 | ||
|
|
e07b39453b | ||
|
|
0f02c65854 | ||
|
|
a76404b263 | ||
|
|
298ea7d3f5 | ||
|
|
8e580358d4 | ||
|
|
4b4dd42ad4 | ||
|
|
7be984de7e | ||
|
|
6f96e6522d | ||
|
|
e95124c81f | ||
|
|
2aeb3f8475 | ||
|
|
ecfc4db4e9 | ||
|
|
f3e99a9c70 | ||
|
|
6d8d614bf2 | ||
|
|
beb85076a5 | ||
|
|
6d396dfb44 | ||
|
|
f49d1af281 | ||
|
|
82b04be57e | ||
|
|
5eb865d25d | ||
|
|
81e76b1a9a | ||
|
|
dcad77ec73 | ||
|
|
6ae59362f8 | ||
|
|
694e5ae6de | ||
|
|
c26e60c6ba | ||
|
|
96a5383b0a | ||
|
|
38b5251804 | ||
|
|
aaec0af9c8 |
No files matched your search
@@ -1,15 +0,0 @@
|
||||
name: Swift
|
||||
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: macOS-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Build
|
||||
run: swift build -v
|
||||
- name: Run tests
|
||||
run: swift test -v -c release
|
||||
@@ -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
|
||||
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<array/>
|
||||
</plist>
|
||||
@@ -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}
|
||||
|
||||
+17
-4
@@ -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
|
||||
@@ -13,23 +13,36 @@
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
|
||||
name: "swift-numerics",
|
||||
products: [
|
||||
.library(name: "ComplexModule", targets: ["ComplexModule"]),
|
||||
.library(name: "Numerics", targets: ["Numerics"]),
|
||||
.library(name: "RealModule", targets: ["RealModule"]),
|
||||
],
|
||||
dependencies: [
|
||||
],
|
||||
|
||||
targets: [
|
||||
// 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: []),
|
||||
.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")
|
||||
]
|
||||
)
|
||||
@@ -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")
|
||||
]
|
||||
)
|
||||
@@ -1,89 +1,131 @@
|
||||
# Swift Numerics
|
||||
|
||||
## Introduction
|
||||
|
||||
Swift Numerics provides a set of modules that support numerical computing in Swift.
|
||||
These modules fall broadly into 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.
|
||||
|
||||
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 an API that begins in the first category may migrate into the second as it matures and new uses are discovered.
|
||||
|
||||
Swift Numerics modules are fine-grained.
|
||||
For example, if you need support for Complex numbers, you can import ComplexModule¹ as a standalone module:
|
||||
|
||||
Swift Numerics modules are fine-grained; if you need support for Complex numbers, you can import ComplexModule¹ without pulling in everything else in the library as well:
|
||||
```swift
|
||||
import ComplexModule
|
||||
|
||||
let z = Complex<Double>.i
|
||||
```
|
||||
However, there is also a top-level `Numerics` module that simply re-exports the complete public interface of swift-numerics:
|
||||
|
||||
There is also a top-level `Numerics` module that re-exports the complete public interface of Swift Numerics:
|
||||
|
||||
```swift
|
||||
import Numerics
|
||||
|
||||
// All swift-numerics API is now available
|
||||
// The entire 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 (Basic Linear Algebra Subprograms)](https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms) and [LAPACK (Linear Algebra Package)](https://en.wikipedia.org/wiki/LAPACK), but modules with more specialized dependencies (or dependencies that are not available on all platforms supported by Swift) belong in a separate package.
|
||||
|
||||
Future expansion may assume the availability of other standard interfaces, such as [BLAS (Basic Linear Algebra Subprograms)](https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms) and [LAPACK (Linear Algebra Package)](https://en.wikipedia.org/wiki/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 we intend 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.
|
||||
|
||||
## Using Swift Numerics in your project
|
||||
To use Swift Numerics in a SwiftPM project, add the following line to the dependencies in your `Package.swift` file:
|
||||
|
||||
To use Swift Numerics in a SwiftPM project:
|
||||
|
||||
1. Add the following line to the dependencies in your `Package.swift` file:
|
||||
|
||||
```swift
|
||||
.package(url: "https://github.com/apple/swift-numerics", from: "0.0.5"),
|
||||
.package(url: "https://github.com/apple/swift-numerics", from: "1.0.0"),
|
||||
```
|
||||
add `Numerics` as a dependency for your target:
|
||||
|
||||
2. Add `Numerics` as a dependency for your target:
|
||||
|
||||
```swift
|
||||
.target(name: "MyTarget", dependencies: [
|
||||
.product(name: "Numerics", package: "swift-numerics"),
|
||||
"AnotherModule"
|
||||
]),
|
||||
```
|
||||
and finally, add `import Numerics` in your source code.
|
||||
|
||||
|
||||
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 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 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.
|
||||
When that happens, such changes will be proposed to the Swift Standard Library using the established evolution process of the Swift project.
|
||||
|
||||
Swift Numerics uses GitHub issues to track bugs and features. We use pull requests for development.
|
||||
|
||||
To propose a new module:
|
||||
### How 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.
|
||||
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
|
||||
|
||||
To propose a new feature for an existing module:
|
||||
1. Raise an issue with the [enhancement] tag.
|
||||
2. Raise a PR with your implementation, and discuss the implementation there.
|
||||
3. Once there is a 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.
|
||||
### How 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.](https://forums.swift.org/c/related-projects/swift-numerics)
|
||||
1. Raise a PR with your change.
|
||||
2. Make sure to add test coverage for whatever changes you are making.
|
||||
|
||||
### 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](https://forums.swift.org/c/related-projects/swift-numerics).
|
||||
|
||||
## Modules
|
||||
1. [RealModule](Sources/RealModule/README.md)
|
||||
2. [ComplexModule](Sources/ComplexModule/README.md)
|
||||
|
||||
1. [`RealModule`](Sources/RealModule/README.md)
|
||||
2. [`ComplexModule`](Sources/ComplexModule/README.md)
|
||||
|
||||
## Future expansion
|
||||
1. [Approximate Equality](https://github.com/apple/swift-numerics/issues/3)
|
||||
2. [Large Fixed-Width Integers](https://github.com/apple/swift-numerics/issues/4)
|
||||
3. [Arbitrary-Precision Integers](https://github.com/apple/swift-numerics/issues/5)
|
||||
4. [Shaped Arrays](https://github.com/apple/swift-numerics/issues/6)
|
||||
5. [Decimal Floating-point](https://github.com/apple/swift-numerics/issues/7)
|
||||
|
||||
1. [Large Fixed-Width Integers](https://github.com/apple/swift-numerics/issues/4)
|
||||
2. [Arbitrary-Precision Integers](https://github.com/apple/swift-numerics/issues/5)
|
||||
3. [Shaped Arrays](https://github.com/apple/swift-numerics/issues/6)
|
||||
4. [Decimal Floating-point](https://github.com/apple/swift-numerics/issues/7)
|
||||
|
||||
## Notes
|
||||
|
||||
¹ Swift is currently unable to use the fully-qualified name for types when a type and module have the same name (discussion here: https://forums.swift.org/t/pitch-fully-qualified-name-syntax/28482).
|
||||
This would prevent users of Swift Numerics who don't need generic types from doing things like:
|
||||
This would prevent users of Swift Numerics who don't need generic types from doing things such as:
|
||||
|
||||
```swift
|
||||
import Complex
|
||||
// I know I only ever want Complex<Double>, so I shouldn't need the generic parameter.
|
||||
typealias Complex = Complex.Complex<Double> // doesn't work, because name lookup fails.
|
||||
typealias Complex = Complex.Complex<Double> // This doesn't work, because name lookup fails.
|
||||
```
|
||||
|
||||
For this reason, modules that would have this ambiguity are suffixed with `Module` within Swift Numerics:
|
||||
|
||||
```swift
|
||||
import ComplexModule
|
||||
// I know I only ever want Complex<Double>, so I shouldn't need the generic parameter.
|
||||
@@ -91,6 +133,8 @@ typealias Complex = ComplexModule.Complex<Double>
|
||||
// But I can still refer to the generic type by qualifying the name if I need it occasionally:
|
||||
let a = ComplexModule.Complex<Float>
|
||||
```
|
||||
The `Real` module does not contain a `Real` type, but does contain a `Real` protocol, and users may want to define their own `Real` type (and possibly re-export the `Real` module), so the suffix is also applied there.
|
||||
New modules have to evaluate this decision carefully, but can err on the side of adding the suffix.
|
||||
It's expected that most users will simply `import Numerics`, so this isn't an issue for them.
|
||||
|
||||
The `Real` module does not contain a `Real` type, but does contain a `Real` protocol.
|
||||
Users may want to define their own `Real` type (and possibly re-export the `Real` module)--that is why the suffix is also applied there.
|
||||
New modules have to evaluate this decision carefully, but can err on the side of adding the suffix.
|
||||
It's expected that most users will simply `import Numerics`, so this isn't an issue for them.
|
||||
@@ -52,13 +52,31 @@ extension Complex: AdditiveArithmetic {
|
||||
// and turn these into operators if/when we have it.
|
||||
// (https://github.com/apple/swift-numerics/issues/12)
|
||||
extension Complex {
|
||||
/// `self` scaled by `a`.
|
||||
@usableFromInline @_transparent
|
||||
internal func multiplied(by a: RealType) -> Complex {
|
||||
// This can be viewed in two different ways, which are mathematically
|
||||
// equivalent: either we are computing `self * Complex(a)` (i.e.
|
||||
// converting `a` to be a complex value, and then using the complex
|
||||
// multiplication) or we are using the scalar product of the vector
|
||||
// space structure: `Complex(a*real, a*imaginary)`.
|
||||
//
|
||||
// Although these two interpretations are _mathematically_ equivalent,
|
||||
// they will generate different representations of the point at
|
||||
// infinity in general. For example, suppose `self` is represented by
|
||||
// `(infinity, 0)`. Then `self * Complex(1)` would evaluate as
|
||||
// `(1*infinity - 0*0, 0*infinity + 1*0) = (infinity, nan)`, but
|
||||
// the vector space interpretation produces `(infinity, 0)`. This does
|
||||
// not matter much, because these are two representations of the same
|
||||
// semantic value, but note that one requires four multiplies and two
|
||||
// additions, while the one we use requires only two real multiplications.
|
||||
Complex(x*a, y*a)
|
||||
}
|
||||
|
||||
/// `self` unscaled by `a`.
|
||||
@usableFromInline @_transparent
|
||||
internal func divided(by a: RealType) -> Complex {
|
||||
// See implementation notes for `multiplied` above.
|
||||
Complex(x/a, y/a)
|
||||
}
|
||||
}
|
||||
@@ -126,8 +144,8 @@ extension Complex: AlgebraicField {
|
||||
|
||||
/// A normalized complex number with the same phase as this value.
|
||||
///
|
||||
/// If such a value cannot be produced (because the phase of zero and infinity is undefined),
|
||||
/// `nil` is returned.
|
||||
/// If such a value cannot be produced (because the phase of zero and
|
||||
/// infinity is undefined), `nil` is returned.
|
||||
@inlinable
|
||||
public var normalized: Complex? {
|
||||
if length.isNormal {
|
||||
@@ -139,16 +157,18 @@ extension Complex: AlgebraicField {
|
||||
return self.divided(by: magnitude).normalized
|
||||
}
|
||||
|
||||
/// The reciprocal of this value, if it can be computed without undue overflow or underflow.
|
||||
/// The reciprocal of this value, if it can be computed without undue
|
||||
/// overflow or underflow.
|
||||
///
|
||||
/// If z.reciprocal is non-nil, you can safely replace division by z with multiplication by this value. It is
|
||||
/// not advantageous to do this for an isolated division, but if you are dividing many values by a single
|
||||
/// denominator, this will often be a significant performance win.
|
||||
/// If z.reciprocal is non-nil, you can safely replace division by z with
|
||||
/// multiplication by this value. It is not advantageous to do this for an
|
||||
/// isolated division, but if you are dividing many values by a single
|
||||
/// denominator, this may sometimes be a significant performance win.
|
||||
///
|
||||
/// Typical use looks like this:
|
||||
/// A typical use case looks something like this:
|
||||
/// ```
|
||||
/// func divide<T: Real>(data: [Complex<T>], by divisor: Complex<T>) -> [Complex<T>] {
|
||||
/// // If divisor is well-scaled, use multiply by reciprocal.
|
||||
/// // If divisor is well-scaled, multiply by reciprocal.
|
||||
/// if let recip = divisor.reciprocal {
|
||||
/// return data.map { $0 * recip }
|
||||
/// }
|
||||
@@ -156,6 +176,12 @@ extension Complex: AlgebraicField {
|
||||
/// return data.map { $0 / divisor }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Error Bounds:
|
||||
///
|
||||
/// Unlike real types, when working with complex types, multiplying by the
|
||||
/// reciprocal instead of dividing cannot change the result. If the
|
||||
/// reciprocal is non-nil, the two computations are always equivalent.
|
||||
@inlinable
|
||||
public var reciprocal: Complex? {
|
||||
let recip = 1/self
|
||||
|
||||
@@ -10,7 +10,8 @@ See https://swift.org/LICENSE.txt for license information
|
||||
add_library(ComplexModule
|
||||
Arithmetic.swift
|
||||
Complex.swift
|
||||
Differentiable.swift)
|
||||
Differentiable.swift
|
||||
ElementaryFunctions.swift)
|
||||
set_target_properties(ComplexModule PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
target_link_libraries(ComplexModule PUBLIC
|
||||
|
||||
@@ -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.
|
||||
@@ -163,9 +167,10 @@ extension Complex {
|
||||
|
||||
/// True if this value is normal.
|
||||
///
|
||||
/// A complex number is normal if it is finite and *either* the real or imaginary component is normal.
|
||||
/// A floating-point number representing one of the components is normal if its exponent allows a full-
|
||||
/// precision representation.
|
||||
/// A complex number is normal if it is finite and *either* the real or
|
||||
/// imaginary component is normal. A floating-point number representing
|
||||
/// one of the components is normal if its exponent allows a full-precision
|
||||
/// representation.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
@@ -179,9 +184,10 @@ extension Complex {
|
||||
|
||||
/// True if this value is subnormal.
|
||||
///
|
||||
/// A complex number is subnormal if it is finite, not normal, and not zero. When the result of a
|
||||
/// computation is subnormal, underflow has occurred and the result generally does not have full
|
||||
/// precision.
|
||||
/// A complex number is subnormal if it is finite, not normal, and not zero.
|
||||
/// When the result of a computation is subnormal, underflow has occurred and
|
||||
/// the result generally does not have full precision.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `.isFinite`
|
||||
@@ -194,7 +200,8 @@ extension Complex {
|
||||
|
||||
/// True if this value is zero.
|
||||
///
|
||||
/// A complex number is zero if *both* the real and imaginary components are zero.
|
||||
/// A complex number is zero if *both* the real and imaginary components
|
||||
/// are zero.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
@@ -208,8 +215,8 @@ extension Complex {
|
||||
|
||||
/// The ∞-norm of the value (`max(abs(real), abs(imaginary))`).
|
||||
///
|
||||
/// If you need the Euclidean norm (a.k.a. 2-norm) use the `length` or `lengthSquared`
|
||||
/// properties instead.
|
||||
/// If you need the Euclidean norm (a.k.a. 2-norm) use the `length` or
|
||||
/// `lengthSquared` properties instead.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// -
|
||||
@@ -240,8 +247,8 @@ extension Complex {
|
||||
/// This is mainly useful for interoperation with other languages, where
|
||||
/// you may want to reduce each equivalence class to a single representative
|
||||
/// before passing across language boundaries, but it may also be useful
|
||||
/// for some serialization tasks. It's also a useful implementation detail for
|
||||
/// some primitive operations.
|
||||
/// for some serialization tasks. It's also a useful implementation detail
|
||||
/// for some primitive operations.
|
||||
@_transparent
|
||||
public var canonicalized: Self {
|
||||
if isZero { return .zero }
|
||||
@@ -491,7 +498,8 @@ extension Complex {
|
||||
///
|
||||
/// Edge cases:
|
||||
/// -
|
||||
/// - Negative lengths are interpreted as reflecting the point through the origin, i.e.:
|
||||
/// - Negative lengths are interpreted as reflecting the point through the
|
||||
/// origin, i.e.:
|
||||
/// ```
|
||||
/// Complex(length: -r, phase: θ) == -Complex(length: r, phase: θ)
|
||||
/// ```
|
||||
|
||||
@@ -0,0 +1,482 @@
|
||||
//===--- ElementaryFunctions.swift ----------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// Implementation goals, in order of priority:
|
||||
//
|
||||
// 1. Get the branch cuts right. We should match Kahan's /Much Ado/
|
||||
// paper for finite values.
|
||||
// 2. Have good relative accuracy in the complex norm.
|
||||
// 3. Preserve sign symmetries where possible.
|
||||
// 4. Handle the point at infinity consistently with basic operations.
|
||||
// This means diverging from what C and C++ do for non-finite inputs.
|
||||
// 5. Get good componentwise accuracy /when possible/. I don't know how
|
||||
// to do that for all of these functions off the top of my head, and
|
||||
// I don't think that other libraries have tried to do so in general,
|
||||
// so this is a research project. We should not sacrifice 1-4 for it.
|
||||
// Note that multiplication and division don't even provide good
|
||||
// componentwise relative accuracy, so it's _totally OK_ to not get
|
||||
// it for these functions too. But: it's a dynamite long-term research
|
||||
// project.
|
||||
// 6. Give the best performance we can. We should care about performance,
|
||||
// but with lower precedence than the other considerations.
|
||||
//
|
||||
// Except where derivations are given, the expressions used here are all
|
||||
// adapted from Kahan's 1986 paper "Branch Cuts for Complex Elementary
|
||||
// Functions; or: Much Ado About Nothing's Sign Bit".
|
||||
|
||||
import RealModule
|
||||
|
||||
extension Complex: ElementaryFunctions {
|
||||
|
||||
// MARK: - exp-like functions
|
||||
|
||||
/// The complex exponential function e^z whose base `e` is the base of the
|
||||
/// natural logarithm.
|
||||
///
|
||||
/// Mathematically, this operation can be expanded in terms of the `Real`
|
||||
/// operations `exp`, `cos` and `sin` as follows:
|
||||
/// ```
|
||||
/// exp(x + iy) = exp(x) exp(iy)
|
||||
/// = exp(x) cos(y) + i exp(x) sin(y)
|
||||
/// ```
|
||||
/// Note that naive evaluation of this expression in floating-point would be
|
||||
/// prone to premature overflow, since `cos` and `sin` both have magnitude
|
||||
/// less than 1 for most inputs (i.e. `exp(x)` may be infinity when
|
||||
/// `exp(x) cos(y)` would not be).
|
||||
@inlinable
|
||||
public static func exp(_ z: Complex) -> Complex {
|
||||
guard z.isFinite else { return z }
|
||||
// If x < log(greatestFiniteMagnitude), then exp(x) does not overflow.
|
||||
// To protect ourselves against sketchy log or exp implementations in
|
||||
// an unknown host library, or slight rounding disagreements between
|
||||
// the two, subtract one from the bound for a little safety margin.
|
||||
guard z.x < RealType.log(.greatestFiniteMagnitude) - 1 else {
|
||||
let halfScale = RealType.exp(z.x/2)
|
||||
let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))
|
||||
return phase.multiplied(by: halfScale).multiplied(by: halfScale)
|
||||
}
|
||||
return Complex(.cos(z.y), .sin(z.y)).multiplied(by: .exp(z.x))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func expMinusOne(_ z: Complex) -> Complex {
|
||||
// exp(x + iy) - 1 = (exp(x) cos(y) - 1) + i exp(x) sin(y)
|
||||
// -------- u --------
|
||||
// Note that the imaginary part is just the usual exp(x) sin(y);
|
||||
// the only trick is computing the real part ("u"):
|
||||
//
|
||||
// u = exp(x) cos(y) - 1
|
||||
// = exp(x) cos(y) - cos(y) + cos(y) - 1
|
||||
// = (exp(x) - 1) cos(y) + (cos(y) - 1)
|
||||
// = expMinusOne(x) cos(y) + cosMinusOne(y)
|
||||
//
|
||||
// Note: most implementations of expm1 for complex (e.g. Julia's)
|
||||
// factor the real part as follows instead:
|
||||
//
|
||||
// exp(x) cosMinuxOne(y) + expMinusOne(x)
|
||||
//
|
||||
// The other implementation that is sometimes seen is:
|
||||
//
|
||||
// expMinusOne(z) = 2*exp(z/2)*sinh(z/2)
|
||||
//
|
||||
// All three of these implementations provide good relative error
|
||||
// bounds _in the complex norm_, but the cosineMinusOne-based
|
||||
// implementation has the best _componentwise_ error characteristics,
|
||||
// which is why we use it here:
|
||||
//
|
||||
// Implementation | Real | Imaginary |
|
||||
// ---------------+--------------------+----------------+
|
||||
// Ours | Hybrid bound | Relative bound |
|
||||
// Standard | No bound | Relative bound |
|
||||
// Half Angle | Hybrid bound | Hybrid bound |
|
||||
//
|
||||
// FUTURE WORK: devise an algorithm that achieves good _relative_ error
|
||||
// in the real component as well. Doing this efficiently is a research
|
||||
// project--exp(x) cos(y) - 1 can be very nearly zero along a curve in
|
||||
// the complex plane, not only at zero. Evaluating it accurately
|
||||
// _without_ depending on arbitrary-precision exp and cos is an
|
||||
// interesting challenge.
|
||||
guard z.isFinite else { return z }
|
||||
// If exp(z) is close to the overflow boundary, we don't need to
|
||||
// worry about the "MinusOne" part of this function; we're just
|
||||
// computing exp(z). (Even when z.y is near a multiple of π/2,
|
||||
// it can't be close enough to overcome the scaling from exp(z.x),
|
||||
// so the -1 term is _always_ negligable). So we simply handle
|
||||
// these cases exactly the same as exp(z).
|
||||
guard z.x < RealType.log(.greatestFiniteMagnitude) - 1 else {
|
||||
let halfScale = RealType.exp(z.x/2)
|
||||
let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))
|
||||
return phase.multiplied(by: halfScale).multiplied(by: halfScale)
|
||||
}
|
||||
// Special cases out of the way, evaluate as discussed above.
|
||||
return Complex(
|
||||
RealType._mulAdd(.cos(z.y), .expMinusOne(z.x), .cosMinusOne(z.y)),
|
||||
.exp(z.x) * .sin(z.y)
|
||||
)
|
||||
}
|
||||
|
||||
// cosh(x + iy) = cosh(x) cos(y) + i sinh(x) sin(y).
|
||||
//
|
||||
// Like exp, cosh is entire, so we do not need to worry about where
|
||||
// branch cuts fall. Also like exp, cancellation never occurs in the
|
||||
// evaluation of the naive expression, so all we need to be careful
|
||||
// about is the behavior near the overflow boundary.
|
||||
//
|
||||
// Fortunately, if |x| >= -log(ulpOfOne), cosh(x) and sinh(x) are
|
||||
// both just exp(|x|)/2, and we already know how to compute that.
|
||||
//
|
||||
// This function and sinh should stay in sync; if you make a
|
||||
// modification here, you should almost surely make a parallel
|
||||
// modification to sinh below.
|
||||
@inlinable
|
||||
public static func cosh(_ z: Complex) -> Complex {
|
||||
guard z.isFinite else { return z }
|
||||
guard z.x.magnitude < -RealType.log(.ulpOfOne) else {
|
||||
let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))
|
||||
let firstScale = RealType.exp(z.x.magnitude/2)
|
||||
let secondScale = firstScale/2
|
||||
return phase.multiplied(by: firstScale).multiplied(by: secondScale)
|
||||
}
|
||||
// Future optimization opportunity: expm1 is faster than cosh/sinh
|
||||
// on most platforms, and division is now commonly pipelined, so we
|
||||
// might replace the check above with a much more conservative one,
|
||||
// and then evaluate cosh(x) and sinh(x) as
|
||||
//
|
||||
// cosh(x) = 1 + 0.5*expm1(x)*expm1(x) / (1 + expm1(x))
|
||||
// sinh(x) = expm1(x) + 0.5*expm1(x) / (1 + expm1(x))
|
||||
//
|
||||
// This won't be a _big_ win except on platforms with a crappy sinh
|
||||
// and cosh, and for those we should probably just provide our own
|
||||
// implementations of _those_, so for now let's keep it simple and
|
||||
// obviously correct.
|
||||
return Complex(
|
||||
RealType.cosh(z.x) * RealType.cos(z.y),
|
||||
RealType.sinh(z.x) * RealType.sin(z.y)
|
||||
)
|
||||
}
|
||||
|
||||
// sinh(x + iy) = sinh(x) cos(y) + i cosh(x) sinh(y)
|
||||
//
|
||||
// See cosh above for algorithm details.
|
||||
@inlinable
|
||||
public static func sinh(_ z: Complex) -> Complex {
|
||||
guard z.isFinite else { return z }
|
||||
guard z.x.magnitude < -RealType.log(.ulpOfOne) else {
|
||||
let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))
|
||||
let firstScale = RealType.exp(z.x.magnitude/2)
|
||||
let secondScale = RealType(signOf: z.x, magnitudeOf: firstScale/2)
|
||||
return phase.multiplied(by: firstScale).multiplied(by: secondScale)
|
||||
}
|
||||
return Complex(
|
||||
RealType.sinh(z.x) * RealType.cos(z.y),
|
||||
RealType.cosh(z.x) * RealType.sin(z.y)
|
||||
)
|
||||
}
|
||||
|
||||
// tanh(z) = sinh(z) / cosh(z)
|
||||
@inlinable
|
||||
public static func tanh(_ z: Complex) -> Complex {
|
||||
guard z.isFinite else { return z }
|
||||
// Note that when |x| is larger than -log(.ulpOfOne),
|
||||
// sinh(x + iy) == ±cosh(x + iy), so tanh(x + iy) is just ±1.
|
||||
guard z.x.magnitude < -RealType.log(.ulpOfOne) else {
|
||||
return Complex(
|
||||
RealType(signOf: z.x, magnitudeOf: 1),
|
||||
RealType(signOf: z.y, magnitudeOf: 0)
|
||||
)
|
||||
}
|
||||
// Now we have z in a vertical strip where exp(x) is reasonable,
|
||||
// and y is finite, so we can simply evaluate sinh(z) and cosh(z).
|
||||
//
|
||||
// TODO: Kahan uses a different expression for evaluation here; it
|
||||
// isn't strictly necessary for numerics reasons--it's to avoid
|
||||
// doing the complex division, but it probably provides better
|
||||
// componentwise error bounds, and is likely more efficient (because
|
||||
// it avoids the complex division, which is painful even when well-
|
||||
// scaled). This suffices to get us up and running.
|
||||
return sinh(z) / cosh(z)
|
||||
}
|
||||
|
||||
// cos(z) = cosh(iz)
|
||||
@inlinable
|
||||
public static func cos(_ z: Complex) -> Complex {
|
||||
return cosh(Complex(-z.y, z.x))
|
||||
}
|
||||
|
||||
// sin(z) = -i*sinh(iz)
|
||||
@inlinable
|
||||
public static func sin(_ z: Complex) -> Complex {
|
||||
let w = sinh(Complex(-z.y, z.x))
|
||||
return Complex(w.y, -w.x)
|
||||
}
|
||||
|
||||
// tan(z) = -i*tanh(iz)
|
||||
@inlinable
|
||||
public static func tan(_ z: Complex) -> Complex {
|
||||
let w = tanh(Complex(-z.y, z.x))
|
||||
return Complex(w.y, -w.x)
|
||||
}
|
||||
|
||||
// MARK: - log-like functions
|
||||
@inlinable
|
||||
public static func log(_ z: Complex) -> Complex {
|
||||
// If z is zero or infinite, the phase is undefined, so the result is
|
||||
// the single exceptional value.
|
||||
guard z.isFinite && !z.isZero else { return .infinity }
|
||||
// Having eliminated non-finite values and zero, the imaginary part is
|
||||
// easy; it's just the phase, which is always computed with good
|
||||
// relative accuracy via atan2.
|
||||
let θ = z.phase
|
||||
// The real part of the result is trickier. In exact arithmetic, the
|
||||
// real part is just log |z|--many implementations of complex functions
|
||||
// simply use this expression as is. However, there are two problems
|
||||
// lurking here:
|
||||
//
|
||||
// - length can overflow even when log(z) is finite.
|
||||
//
|
||||
// - when length is close to 1, catastrophic cancellation is hidden
|
||||
// in this expression. Consider, e.g. z = 1 + δi for small δ.
|
||||
//
|
||||
// Because δ ≪ 1, |z| rounds to 1, and so log |z| produces zero.
|
||||
// We can expand using Taylor series to see that the result should
|
||||
// be:
|
||||
//
|
||||
// log |z| = log √(1 + δ²)
|
||||
// = log(1 + δ²)/2
|
||||
// = δ²/2 + O(δ⁴)
|
||||
//
|
||||
// So naively using log |z| results in a total loss of relative
|
||||
// accuracy for this case. Note that this is _not_ constrained near
|
||||
// a single point; it occurs everywhere close to the circle |z| = 1.
|
||||
//
|
||||
// Note that this case still _does_ deliver a result with acceptable
|
||||
// relative accuracy in the complex norm, because
|
||||
//
|
||||
// Im(log z) ≈ δ ≫ δ²/2 ≈ Re(log z).
|
||||
//
|
||||
// There are a number of ways to try to tackle this problem. I'll begin
|
||||
// with a simple one that solves the first issue, and _sometimes_ the
|
||||
// second, then analyze when it doesn't work for the second case.
|
||||
//
|
||||
// To handle very large arguments without overflow, the standard
|
||||
// approach is to _rescale_ the problem. We can do this by finding
|
||||
// whichever of x and y has greater magnitude, and dividing through
|
||||
// by it. You can think of this as changing coordinates by reflections
|
||||
// so that we get a new value w = u + iv with |w| = |z| (and hence
|
||||
// Re(log w) = Re(log z), and 0 ≤ u, 0 ≤ v ≤ u.
|
||||
let u = max(z.x.magnitude, z.y.magnitude)
|
||||
let v = min(z.x.magnitude, z.y.magnitude)
|
||||
// Now expand out log |w|:
|
||||
//
|
||||
// log |w| = log(u² + v²)/2
|
||||
// = log u + log(onePlus: (v/u)²)/2
|
||||
//
|
||||
// This looks promising! It handles overflow well, because log(u) is
|
||||
// finite for every finite u, and we have 0 ≤ v/u ≤ 1, so the second
|
||||
// term is bounded by 0 ≤ log(1 + (v/u)²)/2 ≤ (log 2)/2. It also
|
||||
// handles the example I gave above well: we have u = 1, v = δ, and
|
||||
//
|
||||
// log(1) + log(onePlus: δ²)/2 = 0 + δ²/2
|
||||
//
|
||||
// as expected.
|
||||
//
|
||||
// Unfortunately, it does not handle all points close to the unit
|
||||
// circle so well; it's easy to see why if we look at the two terms
|
||||
// that contribute to the result. Cancellation occurs when the result
|
||||
// is close to zero and the terms have opposing signs. By construction,
|
||||
// the second term is always positive, so the easiest observation is
|
||||
// that cancellation is only a problem for u < 1 (because otherwise
|
||||
// log u is also positive, and there can be no cancellation).
|
||||
//
|
||||
// We are not trying for sub-ulp accuracy, just a good relative error
|
||||
// bound, so for our purposes it suffices to have log u dominate the
|
||||
// result:
|
||||
if u >= 1 || u >= RealType._mulAdd(u,u,v*v) {
|
||||
let r = v / u
|
||||
return Complex(.log(u) + .log(onePlus: r*r)/2, θ)
|
||||
}
|
||||
// Here we're in the tricky case; cancellation is likely to occur.
|
||||
// Instead of the factorization used above, we will want to evaluate
|
||||
// log(onePlus: u² + v² - 1)/2. This all boils down to accurately
|
||||
// evaluating u² + v² - 1. To begin, calculate both squared terms
|
||||
// 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.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.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
|
||||
// there is no significant cancellation, and the exact assembly doesn't
|
||||
// matter.
|
||||
s = (s + c) + e + b + d
|
||||
return Complex(.log(onePlus: s)/2, θ)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func log(onePlus z: Complex) -> Complex {
|
||||
// If either |x| or |y| is bounded away from the origin, we don't need
|
||||
// any extra precision, and can just literally compute log(1+z). Note
|
||||
// that this includes part of the circle |1+z| = 1 where log(onePlus:)
|
||||
// vanishes (where x <= -0.5), but on this portion of the circle 1+x
|
||||
// is always exact by Sterbenz' lemma, so as long as log( ) produces
|
||||
// a good result, log(1+z) will too.
|
||||
guard 2*z.x.magnitude < 1 && z.y.magnitude < 1 else { return log(1+z) }
|
||||
// z is in (±0.5, ±1), so we need to evaluate more carefully.
|
||||
// The imaginary part is straightforward:
|
||||
let θ = (1+z).phase
|
||||
// For the real part, we _could_ use the same approach that we do for
|
||||
// log( ), but we'd need an extra-precise (1+x)², which can potentially
|
||||
// be quite painful to calculate. Instead, we can use an approach that
|
||||
// NevinBR suggested on the Swift forums:
|
||||
//
|
||||
// Re(log(1+z)) = (log(1+z) + log(1+z̅)) / 2
|
||||
// = log((1+z)(1+z̅)) / 2
|
||||
// = log(1 + z + z̅ + zz̅) / 2
|
||||
// = log(1 + 2x + x² + y²) / 2
|
||||
// = log(onePlus: (2+x)x + y²) / 2
|
||||
//
|
||||
// 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.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, θ)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func acos(_ z: Complex) -> Complex {
|
||||
Complex(
|
||||
2*RealType.atan2(y: sqrt(1-z).real, x: sqrt(1+z).real),
|
||||
RealType.asinh((sqrt(1+z).conjugate * sqrt(1-z)).imaginary)
|
||||
)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func asin(_ z: Complex) -> Complex {
|
||||
Complex(
|
||||
RealType.atan2(y: z.x, x: (sqrt(1-z) * sqrt(1+z)).real),
|
||||
RealType.asinh((sqrt(1-z).conjugate * sqrt(1+z)).imaginary)
|
||||
)
|
||||
}
|
||||
|
||||
// atan(z) = -i*atanh(iz)
|
||||
@inlinable
|
||||
public static func atan(_ z: Complex) -> Complex {
|
||||
let w = atanh(Complex(-z.y, z.x))
|
||||
return Complex(w.y, -w.x)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func acosh(_ z: Complex) -> Complex {
|
||||
Complex(
|
||||
RealType.asinh((sqrt(z-1).conjugate * sqrt(z+1)).real),
|
||||
2*RealType.atan2(y: sqrt(z-1).imaginary, x: sqrt(z+1).real)
|
||||
)
|
||||
}
|
||||
|
||||
// asinh(z) = -i*asin(iz)
|
||||
@inlinable
|
||||
public static func asinh(_ z: Complex) -> Complex {
|
||||
let w = asin(Complex(-z.y, z.x))
|
||||
return Complex(w.y, -w.x)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func atanh(_ z: Complex) -> Complex {
|
||||
// TODO: Kahan uses a much more complicated expression here; possibly
|
||||
// simply because he didn't have a complex log(1+z) with good
|
||||
// characteristics. Investigate tradeoffs further.
|
||||
//
|
||||
// Further TODO: decide policy for point at infinity / NaN. Unlike most
|
||||
// of these functions, atanh doesn't have a pole at infinity; convention
|
||||
// in C-family languages is use one value in the upper half plane, and
|
||||
// another in the lower. Requires some thought about the most appropriate
|
||||
// way to handle this case in Swift.
|
||||
(log(onePlus: z) - log(onePlus:-z))/2
|
||||
}
|
||||
|
||||
// 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 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.
|
||||
//
|
||||
// Note that this does not have the same problems that a similar
|
||||
// implementation for a real type would have, because there's no
|
||||
// parity/sign interaction in the complex plane.
|
||||
return exp(log(z).multiplied(by: RealType(n)))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func sqrt(_ z: Complex) -> Complex {
|
||||
let lengthSquared = z.lengthSquared
|
||||
if lengthSquared.isNormal {
|
||||
// If |z|^2 doesn't overflow, then define u and v by:
|
||||
//
|
||||
// u = sqrt((|z|+|x|)/2)
|
||||
// v = y/2u
|
||||
//
|
||||
// If x is positive, the result is just w = (u, v). If x is negative,
|
||||
// the result is (|v|, copysign(u, y)) instead.
|
||||
let norm = RealType.sqrt(lengthSquared)
|
||||
let u = RealType.sqrt((norm + abs(z.x))/2)
|
||||
let v: RealType = z.y / (2*u)
|
||||
if z.x.sign == .plus {
|
||||
return Complex(u, v)
|
||||
} else {
|
||||
return Complex(abs(v), RealType(signOf: z.y, magnitudeOf: u))
|
||||
}
|
||||
}
|
||||
// Handle edge cases:
|
||||
if z.isZero { return Complex(0, z.y) }
|
||||
if !z.isFinite { return z }
|
||||
// z is finite but badly-scaled. Rescale and replay by factoring out
|
||||
// the larger of x and y.
|
||||
let scale = RealType.maximum(abs(z.x), abs(z.y))
|
||||
return Complex.sqrt(z.divided(by: scale)).multiplied(by: .sqrt(scale))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func root(_ z: Complex, _ n: Int) -> Complex {
|
||||
if z.isZero { return .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.
|
||||
//
|
||||
// Note that this does not have the same problems that a similar
|
||||
// implementation for a real type would have, because there's no
|
||||
// parity/sign interaction in the complex plane.
|
||||
return exp(log(z).divided(by: RealType(n)))
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ set_target_properties(Numerics PROPERTIES
|
||||
# NOTE: generate the force load symbol to ensure that the import library is
|
||||
# generated on Windows for autolinking.
|
||||
target_compile_options(Numerics PUBLIC
|
||||
-autolink-force-load
|
||||
$<$<NOT:$<PLATFORM_ID:Darwin>>:-autolink-force-load>
|
||||
# SR-12254: workaround for the swift compiler not properly tracking the force
|
||||
# load symbol when validating the TBD
|
||||
-Xfrontend -validate-tbd-against-ir=none)
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
|
||||
@@ -22,9 +22,10 @@ extension Numeric where Magnitude: FloatingPoint {
|
||||
/// ```
|
||||
///
|
||||
/// The default value of `relativeTolerance` is `.ulpOfOne.squareRoot()`,
|
||||
/// which corresponds to expecting "about half the digits" in the computed results to be good.
|
||||
/// This is the usual guidance in numerical analysis, if you don't know anything about the
|
||||
/// computation being performed, but is not suitable for all use cases.
|
||||
/// which corresponds to expecting "about half the digits" in the computed
|
||||
/// results to be good. This is the usual guidance in numerical analysis,
|
||||
/// if you don't know anything about the computation being performed, but
|
||||
/// is not suitable for all use cases.
|
||||
///
|
||||
/// Mathematical Properties:
|
||||
/// ------------------------
|
||||
@@ -34,16 +35,21 @@ extension Numeric where Magnitude: FloatingPoint {
|
||||
///
|
||||
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _symmetric_.
|
||||
///
|
||||
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is __not__ _transitive_.
|
||||
/// Because of this, approximately equality is __not an equivalence relation__,
|
||||
/// even when restricted to non-exceptional values.
|
||||
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is __not__
|
||||
/// _transitive_. Because of this, approximately equality is __not an
|
||||
/// equivalence relation__, even when restricted to non-exceptional values.
|
||||
///
|
||||
/// - For any point `a`, the set of values that compare approximately equal to `a` is _convex_.
|
||||
/// (Under the assumption that the `.magnitude` property implements a valid norm.)
|
||||
/// This means that you must not use approximate equality to implement
|
||||
/// a conformance to Equatable, as it will violate the invariants of
|
||||
/// code written against that protocol.
|
||||
///
|
||||
/// - For any point `a`, the set of values that compare approximately equal
|
||||
/// to `a` is _convex_. (Under the assumption that the `.magnitude`
|
||||
/// property implements a valid norm.)
|
||||
///
|
||||
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _scale invariant_,
|
||||
/// so long as no underflow or overflow has occured, and no exceptional value is produced
|
||||
/// by the scaling.
|
||||
/// so long as no underflow or overflow has occured, and no exceptional
|
||||
/// value is produced by the scaling.
|
||||
///
|
||||
/// See Also:
|
||||
/// -------
|
||||
@@ -57,8 +63,9 @@ extension Numeric where Magnitude: FloatingPoint {
|
||||
/// Defaults to `.ulpOfOne.squareRoot()`.
|
||||
///
|
||||
/// This value should be non-negative and less than or equal to 1.
|
||||
/// This constraint on is only checked in debug builds, because a mathematically
|
||||
/// well-defined result exists for any tolerance, even one out of range.
|
||||
/// This constraint on is only checked in debug builds, because a
|
||||
/// mathematically well-defined result exists for any tolerance,
|
||||
/// even one out of range.
|
||||
///
|
||||
/// - norm: The [norm] to use for the comparison.
|
||||
/// Defaults to `\.magnitude`.
|
||||
@@ -99,13 +106,17 @@ extension Numeric where Magnitude: FloatingPoint {
|
||||
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:)`
|
||||
/// is _symmetric_.
|
||||
///
|
||||
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:)`
|
||||
/// is __not__ _transitive_. Because of this, approximately equality is
|
||||
/// __not an equivalence relation__, even when restricted to non-exceptional values.
|
||||
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is __not__
|
||||
/// _transitive_. Because of this, approximately equality is __not an
|
||||
/// equivalence relation__, even when restricted to non-exceptional values.
|
||||
///
|
||||
/// - For any point `a`, the set of values that compare approximately equal to `a` is _convex_.
|
||||
/// (Under the assumption that `norm` implements a valid norm, which cannot be checked
|
||||
/// by this function.)
|
||||
/// This means that you must not use approximate equality to implement
|
||||
/// a conformance to Equatable, as it will violate the invariants of
|
||||
/// code written against that protocol.
|
||||
///
|
||||
/// - For any point `a`, the set of values that compare approximately equal
|
||||
/// to `a` is _convex_. (Under the assumption that `norm` implements a
|
||||
/// valid norm, which cannot be checked by this function.)
|
||||
///
|
||||
/// See Also:
|
||||
/// -------
|
||||
@@ -118,15 +129,17 @@ extension Numeric where Magnitude: FloatingPoint {
|
||||
/// - absoluteTolerance: The absolute tolerance to use in the comparison.
|
||||
///
|
||||
/// This value should be non-negative and finite.
|
||||
/// This constraint on is only checked in debug builds, because a mathematically
|
||||
/// well-defined result exists for any tolerance, even one out of range.
|
||||
/// This constraint on is only checked in debug builds, because a
|
||||
/// mathematically well-defined result exists for any tolerance,
|
||||
/// even one out of range.
|
||||
///
|
||||
/// - relativeTolerance: The relative tolerance to use in the comparison.
|
||||
/// Defaults to zero.
|
||||
///
|
||||
/// This value should be non-negative and less than or equal to 1.
|
||||
/// This constraint on is only checked in debug builds, because a mathematically
|
||||
/// well-defined result exists for any tolerance, even one out of range.
|
||||
/// This constraint on is only checked in debug builds, because a
|
||||
/// mathematically well-defined result exists for any tolerance,
|
||||
/// even one out of range.
|
||||
@inlinable @inline(__always)
|
||||
public func isApproximatelyEqual(
|
||||
to other: Self,
|
||||
@@ -143,7 +156,8 @@ extension Numeric where Magnitude: FloatingPoint {
|
||||
}
|
||||
|
||||
extension AdditiveArithmetic {
|
||||
/// Test if `self` and `other` are approximately equal with specified tolerances and norm.
|
||||
/// Test if `self` and `other` are approximately equal with specified
|
||||
/// tolerances and norm.
|
||||
///
|
||||
/// `true` if `self` and `other` are equal, or if they are finite and either
|
||||
/// ```
|
||||
@@ -166,11 +180,16 @@ extension AdditiveArithmetic {
|
||||
///
|
||||
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:norm:)`
|
||||
/// is __not__ _transitive_. Because of this, approximately equality is
|
||||
/// __not an equivalence relation__, even when restricted to non-exceptional values.
|
||||
/// __not an equivalence relation__, even when restricted to
|
||||
/// non-exceptional values.
|
||||
///
|
||||
/// - For any point `a`, the set of values that compare approximately equal to `a` is _convex_.
|
||||
/// (Under the assumption that `norm` implements a valid norm, which cannot be checked
|
||||
/// by this function.)
|
||||
/// This means that you must not use approximate equality to implement
|
||||
/// a conformance to Equatable, as it will violate the invariants of
|
||||
/// code written against that protocol.
|
||||
///
|
||||
/// - For any point `a`, the set of values that compare approximately equal
|
||||
/// to `a` is _convex_ (under the assumption that `norm` implements a
|
||||
/// valid norm, which cannot be checked by this function or a protocol).
|
||||
///
|
||||
/// See Also:
|
||||
/// -------
|
||||
@@ -184,21 +203,23 @@ extension AdditiveArithmetic {
|
||||
/// - absoluteTolerance: The absolute tolerance to use in the comparison.
|
||||
///
|
||||
/// This value should be non-negative and finite.
|
||||
/// This constraint on is only checked in debug builds, because a mathematically
|
||||
/// well-defined result exists for any tolerance, even one out of range.
|
||||
/// This constraint on is only checked in debug builds, because a
|
||||
/// mathematically well-defined result exists for any tolerance, even
|
||||
/// one out of range.
|
||||
///
|
||||
/// - relativeTolerance: The relative tolerance to use in the comparison.
|
||||
/// Defaults to zero.
|
||||
///
|
||||
/// This value should be non-negative and less than or equal to 1.
|
||||
/// This constraint on is only checked in debug builds, because a mathematically
|
||||
/// well-defined result exists for any tolerance, even one out of range.
|
||||
/// This constraint on is only checked in debug builds, because a
|
||||
/// mathematically well-defined result exists for any tolerance,
|
||||
/// even one out of range.
|
||||
///
|
||||
/// - norm: The norm to use for the comparison.
|
||||
/// Defaults to `\.magnitude`.
|
||||
///
|
||||
/// For example, if we wanted to test if a complex value was inside a circle of
|
||||
/// radius 0.001 centered at (1 + 0i), we could use:
|
||||
/// For example, if we wanted to test if a complex value was inside a
|
||||
/// circle of radius 0.001 centered at (1 + 0i), we could use:
|
||||
/// ```
|
||||
/// z.isApproximatelyEqual(
|
||||
/// to: 1,
|
||||
@@ -206,8 +227,8 @@ extension AdditiveArithmetic {
|
||||
/// norm: \.length
|
||||
/// )
|
||||
/// ```
|
||||
/// (if we used the default, we would be testing if `z` were inside a square region
|
||||
/// instead.)
|
||||
/// (if we used the default norm, `.magnitude`, we would be testing if
|
||||
/// `z` were inside a square region instead.)
|
||||
@inlinable
|
||||
public func isApproximatelyEqual<Magnitude>(
|
||||
to other: Self,
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
//===--- AugmentedArithmetic.swift ----------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2020 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// 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 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 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)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ See https://swift.org/LICENSE.txt for license information
|
||||
add_library(RealModule
|
||||
AlgebraicField.swift
|
||||
ApproximateEquality.swift
|
||||
AugmentedArithmetic.swift
|
||||
Double+Real.swift
|
||||
ElementaryFunctions.swift
|
||||
Float+Real.swift
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -24,18 +24,21 @@
|
||||
/// let y = Float.sin(x) // 0.84147096
|
||||
/// ```
|
||||
///
|
||||
/// There are three broad families of functions defined by `ElementaryFunctions`:
|
||||
/// There are three broad families of functions defined by
|
||||
/// `ElementaryFunctions`:
|
||||
/// - Exponential, trigonometric, and hyperbolic functions:
|
||||
/// `exp`, `expMinusOne`, `cos`, `sin`, `tan`, `cosh`, `sinh`, and `tanh`.
|
||||
/// - Logarithmic, inverse trigonometric, and inverse hyperbolic functions:
|
||||
/// `log`, `log(onePlus:)`, `acos`, `asin`, `atan`, `acosh`, `asinh`, and `atanh`.
|
||||
/// `log`, `log(onePlus:)`, `acos`, `asin`, `atan`, `acosh`, `asinh`, and
|
||||
/// `atanh`.
|
||||
/// - Power and root functions:
|
||||
/// `pow`, `sqrt`, and `root`.
|
||||
///
|
||||
/// `ElementaryFunctions` conformance implies `AdditiveArithmetic`, so addition
|
||||
/// and subtraction and the `.zero` property are also available.
|
||||
///
|
||||
/// There are two other protocols that you are more likely to want to use directly:
|
||||
/// There are two other protocols that you are more likely to want to use
|
||||
/// directly:
|
||||
///
|
||||
/// `RealFunctions` refines `ElementaryFunctions` and includes
|
||||
/// additional functions specific to real number types.
|
||||
@@ -50,7 +53,8 @@
|
||||
///
|
||||
/// [elfn]: http://en.wikipedia.org/wiki/Elementary_function
|
||||
public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
/// The [exponential function][wiki] e^x whose base `e` is the base of the natural logarithm.
|
||||
/// The [exponential function][wiki] e^x whose base `e` is the base of the
|
||||
/// natural logarithm.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
@@ -63,19 +67,20 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
|
||||
/// exp(x) - 1, computed in such a way as to maintain accuracy for small x.
|
||||
///
|
||||
/// When `x` is close to zero, the expression `.exp(x) - 1` suffers from catastrophic
|
||||
/// cancellation and the result will not have full accuracy. The `.expMinusOne(x)` function gives
|
||||
/// you a means to address this problem.
|
||||
/// When `x` is close to zero, the expression `.exp(x) - 1` suffers from
|
||||
/// catastrophic cancellation and the result will not have full accuracy.
|
||||
/// The `.expMinusOne(x)` function gives you a means to address this problem.
|
||||
///
|
||||
/// As an example, consider the expression `(x + 1)*exp(x) - 1`. When `x` is smaller
|
||||
/// than `.ulpOfOne`, this expression evaluates to `0.0`, when it should actually round to
|
||||
/// `2*x`. We can get a full-accuracy result by using the following instead:
|
||||
/// As an example, consider the expression `(x + 1)*exp(x) - 1`. When `x`
|
||||
/// is smaller than `.ulpOfOne`, this expression evaluates to `0.0`, when it
|
||||
/// should actually round to `2*x`. We can get a full-accuracy result by
|
||||
/// using the following instead:
|
||||
/// ```
|
||||
/// let t = .expMinusOne(x)
|
||||
/// return x*(t+1) + t // x*exp(x) + (exp(x)-1) = (x+1)*exp(x) - 1
|
||||
/// ```
|
||||
/// This re-written expression delivers an accurate result for all values of `x`, not just for
|
||||
/// small values.
|
||||
/// This re-written expression delivers an accurate result for all values
|
||||
/// of `x`, not just for small values.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
@@ -238,7 +243,8 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
|
||||
/// The [arccosine][wiki] (inverse cosine) of `x`.
|
||||
///
|
||||
/// For real types, the result may be interpreted as an angle measured in radians.
|
||||
/// For real types, the result may be interpreted as an angle measured in
|
||||
/// radians.
|
||||
/// ```
|
||||
/// cos(acos(x)) ≅ x
|
||||
/// ```
|
||||
@@ -253,7 +259,8 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
|
||||
/// The [arcsine][wiki] (inverse sine) of `x`.
|
||||
///
|
||||
/// For real types, the result may be interpreted as an angle measured in radians.
|
||||
/// For real types, the result may be interpreted as an angle measured in
|
||||
/// radians.
|
||||
/// ```
|
||||
/// sin(asin(x)) ≅ x
|
||||
/// ```
|
||||
@@ -268,7 +275,8 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
|
||||
/// The [arctangent][wiki] (inverse tangent) of `x`.
|
||||
///
|
||||
/// For real types, the result may be interpreted as an angle measured in radians.
|
||||
/// For real types, the result may be interpreted as an angle measured in
|
||||
/// radians.
|
||||
/// ```
|
||||
/// tan(atan(x)) ≅ x
|
||||
/// ```
|
||||
@@ -284,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`.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,12 +9,13 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if swift(>=5.3)
|
||||
import _NumericsShims
|
||||
|
||||
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, *)
|
||||
@available(macOS, unavailable)
|
||||
@available(macCatalyst, unavailable)
|
||||
// When building with a Swift 5.4 or later toolchain, Float16 is available on
|
||||
// non-x86 macOS from 11.0 onward.
|
||||
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
|
||||
|
||||
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
|
||||
extension Float16: Real {
|
||||
@_transparent
|
||||
public static func cos(_ x: Float16) -> Float16 {
|
||||
@@ -173,4 +174,170 @@ extension Float16: Real {
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// When building with older Swift toolchains for macOS, Float16 is not
|
||||
// available. We will drop support for these older toolchains at some
|
||||
// future point and remove this duplication.
|
||||
#elseif swift(>=5.3) && !(os(macOS) || targetEnvironment(macCatalyst))
|
||||
|
||||
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, *)
|
||||
extension Float16: Real {
|
||||
@_transparent
|
||||
public static func cos(_ x: Float16) -> Float16 {
|
||||
Float16(.cos(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sin(_ x: Float16) -> Float16 {
|
||||
Float16(.sin(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func tan(_ x: Float16) -> Float16 {
|
||||
Float16(.tan(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func acos(_ x: Float16) -> Float16 {
|
||||
Float16(.acos(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func asin(_ x: Float16) -> Float16 {
|
||||
Float16(.asin(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atan(_ x: Float16) -> Float16 {
|
||||
Float16(.atan(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func cosh(_ x: Float16) -> Float16 {
|
||||
Float16(.cosh(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sinh(_ x: Float16) -> Float16 {
|
||||
Float16(.sinh(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func tanh(_ x: Float16) -> Float16 {
|
||||
Float16(.tanh(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func acosh(_ x: Float16) -> Float16 {
|
||||
Float16(.acosh(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func asinh(_ x: Float16) -> Float16 {
|
||||
Float16(.asinh(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atanh(_ x: Float16) -> Float16 {
|
||||
Float16(.atanh(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func exp(_ x: Float16) -> Float16 {
|
||||
Float16(.exp(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func expMinusOne(_ x: Float16) -> Float16 {
|
||||
Float16(.expMinusOne(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log(_ x: Float16) -> Float16 {
|
||||
Float16(.log(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log(onePlus x: Float16) -> Float16 {
|
||||
Float16(.log(onePlus: Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func erf(_ x: Float16) -> Float16 {
|
||||
Float16(.erf(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func erfc(_ x: Float16) -> Float16 {
|
||||
Float16(.erfc(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func exp2(_ x: Float16) -> Float16 {
|
||||
Float16(.exp2(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func exp10(_ x: Float16) -> Float16 {
|
||||
Float16(.exp10(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func hypot(_ x: Float16, _ y: Float16) -> Float16 {
|
||||
if x.isInfinite || y.isInfinite { return .infinity }
|
||||
let xf = Float(x)
|
||||
let yf = Float(y)
|
||||
return Float16(.sqrt(xf*xf + yf*yf))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func gamma(_ x: Float16) -> Float16 {
|
||||
Float16(.gamma(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log2(_ x: Float16) -> Float16 {
|
||||
Float16(.log2(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log10(_ x: Float16) -> Float16 {
|
||||
Float16(.log10(Float(x)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func pow(_ x: Float16, _ y: Float16) -> Float16 {
|
||||
Float16(.pow(Float(x), Float(y)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func pow(_ x: Float16, _ n: Int) -> Float16 {
|
||||
// Float16 is simpler than Float or Double, because the range of
|
||||
// "interesting" exponents is pretty small; anything outside of
|
||||
// -22707 ... 34061 simply overflows or underflows for every
|
||||
// x that isn't zero or one. This whole range is representable
|
||||
// as Float, so we can just use powf as long as we're a little
|
||||
// bit (get it?) careful to preserve parity.
|
||||
let clamped = min(max(n, -0x10000), 0x10000) | (n & 1)
|
||||
return Float16(libm_powf(Float(x), Float(clamped)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func root(_ x: Float16, _ n: Int) -> Float16 {
|
||||
Float16(.root(Float(x), n))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atan2(y: Float16, x: Float16) -> Float16 {
|
||||
Float16(.atan2(y: Float(y), x: Float(x)))
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_transparent
|
||||
public static func logGamma(_ x: Float16) -> Float16 {
|
||||
Float16(.logGamma(Float(x)))
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -11,11 +11,12 @@
|
||||
|
||||
/// A type that models the real numbers.
|
||||
///
|
||||
/// Types conforming to this protocol provide the arithmetic and utility operations defined by
|
||||
/// the `FloatingPoint` protocol, and provide all of the math functions defined by the
|
||||
/// `ElementaryFunctions` and `RealFunctions` protocols. This protocol does not
|
||||
/// add any additional conformances itself, but is very useful as a protocol against which to
|
||||
/// write generic code. For example, we can naturally write a generic version of the a sigmoid
|
||||
/// Types conforming to this protocol provide the arithmetic and utility
|
||||
/// operations defined by the `FloatingPoint` protocol, and provide all of the
|
||||
/// math functions defined by the `ElementaryFunctions` and `RealFunctions`
|
||||
/// protocols. This protocol does not add any additional conformances itself,
|
||||
/// but is very useful as a protocol against which to write generic code. For
|
||||
/// example, we can naturally write a generic implementation of a sigmoid
|
||||
/// function:
|
||||
/// ```
|
||||
/// func sigmoid<T: Real>(_ x: T) -> T {
|
||||
@@ -34,7 +35,8 @@ public protocol Real: FloatingPoint, RealFunctions, AlgebraicField {
|
||||
// it does allow us to default the implementation of a few operations,
|
||||
// and also provides `signGamma`.
|
||||
extension Real {
|
||||
// Most math libraries do not provide exp10, so we need a default implementation.
|
||||
// Most math libraries do not provide exp10, so we need a default
|
||||
// implementation.
|
||||
@_transparent
|
||||
public static func exp10(_ x: Self) -> Self {
|
||||
return pow(10, x)
|
||||
@@ -97,6 +99,53 @@ extension Real {
|
||||
return x.squareRoot()
|
||||
}
|
||||
|
||||
/// The (approximate) reciprocal (multiplicative inverse) of this number,
|
||||
/// if it is representable.
|
||||
///
|
||||
/// If `x` if finite and nonzero, and `1/x` overflows or underflows,
|
||||
/// then `x.reciprocal` is `nil`. Otherwise, `a.reciprocal` is `1/x`.
|
||||
///
|
||||
/// If `x.reciprocal` is non-nil, you may be able to replace division by `x`
|
||||
/// with multiplication by this value. It is not advantageous to do this
|
||||
/// for an isolated division unless it is a compile-time constant visible
|
||||
/// to the compiler, but if you are dividing many values by a single
|
||||
/// denominator, this will often be a significant performance win.
|
||||
///
|
||||
/// A typical use case looks something like this:
|
||||
/// ```
|
||||
/// func divide<T: Real>(data: [T], by divisor: T) -> [T] {
|
||||
/// // If divisor is well-scaled, multiply by reciprocal.
|
||||
/// if let recip = divisor.reciprocal {
|
||||
/// return data.map { $0 * recip }
|
||||
/// }
|
||||
/// // Fallback on using division.
|
||||
/// return data.map { $0 / divisor }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Error Bounds:
|
||||
///
|
||||
/// Multiplying by the reciprocal instead of dividing will slightly
|
||||
/// perturb results. For example `5.0 / 3` is 1.6666666666666667, but
|
||||
/// `5.0 * 3.reciprocal!` is 1.6666666666666665.
|
||||
///
|
||||
/// The error of a normal division is bounded by half an ulp of the
|
||||
/// result; we can derive a quick error bound for multiplication by
|
||||
/// the real reciprocal (when it exists) as follows (I will use circle
|
||||
/// operators to denote real-number arithmetic, and normal operators
|
||||
/// for floating-point arithmetic):
|
||||
///
|
||||
/// ```
|
||||
/// a * b.reciprocal! = a * (1/b)
|
||||
/// = a * (1 ⊘ b)(1 + δ₁)
|
||||
/// = (a ⊘ b)(1 + δ₁)(1 + δ₂)
|
||||
/// = (a ⊘ b)(1 + δ₁ + δ₂ + δ₁δ₂)
|
||||
/// ```
|
||||
///
|
||||
/// where `0 < δᵢ <= ulpOfOne/2`. This gives a roughly 1-ulp error,
|
||||
/// about twice the error bound we get using division. For most
|
||||
/// purposes this is an acceptable error, but if you need to match
|
||||
/// results obtained using division, you should not use this.
|
||||
@inlinable
|
||||
public var reciprocal: Self? {
|
||||
let recip = 1/self
|
||||
|
||||
@@ -53,7 +53,8 @@ public protocol RealFunctions: ElementaryFunctions {
|
||||
/// - `pow()`
|
||||
static func exp10(_ x: Self) -> Self
|
||||
|
||||
/// `sqrt(x*x + y*y)`, computed in a manner that avoids spurious overflow or underflow.
|
||||
/// `sqrt(x*x + y*y)`, computed in a manner that avoids spurious overflow or
|
||||
/// underflow.
|
||||
static func hypot(_ x: Self, _ y: Self) -> Self
|
||||
|
||||
/// The gamma function Γ(x).
|
||||
@@ -97,12 +98,12 @@ public protocol RealFunctions: ElementaryFunctions {
|
||||
|
||||
/// The sign of the gamma function, Γ(x).
|
||||
///
|
||||
/// For `x >= 0`, `signGamma(x)` is `.plus`. For negative `x`, `signGamma(x)` is `.plus`
|
||||
/// when `x` is an integer, and otherwise it is `.minus` whenever `trunc(x)` is even, and `.plus`
|
||||
/// when `trunc(x)` is odd.
|
||||
/// For `x >= 0`, `signGamma(x)` is `.plus`. For negative `x`, `signGamma(x)`
|
||||
/// is `.plus` when `x` is an integer, and otherwise it is `.minus` whenever
|
||||
/// `trunc(x)` is even, and `.plus` when `trunc(x)` is odd.
|
||||
///
|
||||
/// This function is used together with `logGamma`, which computes the logarithm of the
|
||||
/// absolute value of Γ(x), to recover the sign information.
|
||||
/// This function is used together with `logGamma`, which computes the
|
||||
/// logarithm of the absolute value of Γ(x), to recover the sign information.
|
||||
///
|
||||
/// Not available on Windows targets.
|
||||
///
|
||||
|
||||
@@ -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
|
||||
@@ -398,23 +402,6 @@ 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).
|
||||
|
||||
// MARK: - shims to import C complex operations for timing purposes
|
||||
// Clang doesn't provide complex arithmetic on Windows (because MSVC
|
||||
// doesn't), so we can't define these there, or we'll get link errors.
|
||||
#if !defined _WIN32
|
||||
typedef struct { double real; double imag; } CComplex;
|
||||
|
||||
HEADER_SHIM CComplex libm_cdiv(CComplex z, CComplex w) {
|
||||
double _Complex a = { z.real, z.imag };
|
||||
double _Complex b = { w.real, w.imag };
|
||||
double _Complex c = a/b;
|
||||
return (CComplex){ __real__ c, __imag__ c };
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
|
||||
HEADER_SHIM CComplex libm_cmul(CComplex z, CComplex w) {
|
||||
double _Complex a = { z.real, z.imag };
|
||||
double _Complex b = { w.real, w.imag };
|
||||
double _Complex c = a*b;
|
||||
return (CComplex){ __real__ c, __imag__ c };
|
||||
}
|
||||
#endif // !defined _WIN32
|
||||
#endif
|
||||
@@ -8,6 +8,8 @@ See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
add_library(_TestSupport
|
||||
Error.swift
|
||||
Interval.swift
|
||||
RealTestSupport.swift)
|
||||
set_target_properties(_TestSupport PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
//===--- Error.swift ------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import RealModule
|
||||
import ComplexModule
|
||||
|
||||
public func relativeError(_ tst: Float, _ ref: Double) -> Double {
|
||||
let scale = max(ref.magnitude, Double(Float.leastNormalMagnitude))
|
||||
let error = (Double(tst) - ref).magnitude
|
||||
return error / scale
|
||||
}
|
||||
|
||||
public func componentwiseError(_ tst: Complex<Float>, _ ref: Complex<Double>) -> Double {
|
||||
return max(relativeError(tst.real, ref.real),
|
||||
relativeError(tst.imaginary, ref.imaginary))
|
||||
}
|
||||
|
||||
public func relativeError(_ tst: Complex<Float>, _ ref: Complex<Double>) -> Double {
|
||||
let scale = max(ref.magnitude, Double(Float.leastNormalMagnitude))
|
||||
let dtst = Complex(Double(tst.real), Double(tst.imaginary))
|
||||
let error = (dtst - ref).magnitude
|
||||
return error / scale
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//===--- Interval.swift ---------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// A not-particularly-clever floating-point iterval that is iterable for the
|
||||
// purposes of testing.
|
||||
public struct Interval<Element>: Sequence where Element: FloatingPoint {
|
||||
|
||||
let lower: Element
|
||||
|
||||
let upper: Element
|
||||
|
||||
public init(from: Element, through: Element) {
|
||||
precondition(from <= through)
|
||||
lower = from
|
||||
upper = through
|
||||
}
|
||||
|
||||
public init(from: Element, to: Element) {
|
||||
self.init(from: from, through: to.nextDown)
|
||||
}
|
||||
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(self)
|
||||
}
|
||||
|
||||
public struct Iterator: IteratorProtocol {
|
||||
let interval: Interval
|
||||
var nextOutput: Element?
|
||||
|
||||
init(_ interval: Interval) {
|
||||
self.interval = interval
|
||||
self.nextOutput = interval.lower
|
||||
}
|
||||
|
||||
public mutating func next() -> Element? {
|
||||
let result = nextOutput
|
||||
if nextOutput == interval.upper { nextOutput = nil }
|
||||
else { nextOutput = nextOutput?.nextUp }
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,94 +2,21 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019-2020 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 XCTest
|
||||
import RealModule
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
public typealias TestLiteralType = Float80
|
||||
#else
|
||||
public typealias TestLiteralType = Double
|
||||
#endif
|
||||
|
||||
@discardableResult
|
||||
public func assertClose<T>(
|
||||
_ expected: TestLiteralType,
|
||||
_ observed: T,
|
||||
allowedError: T = 16,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) -> T where T: BinaryFloatingPoint {
|
||||
// Shortcut relative-error check if we got the sign wrong; it's OK to
|
||||
// underflow to zero, but we do not want to allow going right through
|
||||
// zero and getting the sign wrong.
|
||||
guard observed.sign == expected.sign else {
|
||||
print("Sign was wrong: expected \(expected) but saw \(observed).")
|
||||
XCTFail(file: file, line: line)
|
||||
return .infinity
|
||||
}
|
||||
if observed.isNaN && expected.isNaN { return 0 }
|
||||
// If T(expected) is zero or infinite, and matches observed, the error
|
||||
// is zero.
|
||||
let expectedT = T(expected)
|
||||
if observed.isZero && expectedT.isZero { return 0 }
|
||||
if observed.isInfinite && expectedT.isInfinite { return 0 }
|
||||
// Special-case where only one of expectedT or observed is infinity.
|
||||
// Artificially knock everything down a binade, treat actual infinity as
|
||||
// the base of the next binade up.
|
||||
func topBinade(signOf x: T) -> T {
|
||||
T(signOf: x, magnitudeOf: T.greatestFiniteMagnitude.binade)
|
||||
}
|
||||
if observed.isInfinite {
|
||||
return assertClose(
|
||||
expected/2, topBinade(signOf: observed),
|
||||
allowedError: allowedError, file: file, line: line
|
||||
)
|
||||
}
|
||||
if expectedT.isInfinite {
|
||||
return assertClose(
|
||||
TestLiteralType(topBinade(signOf: expectedT)), observed/2,
|
||||
allowedError: allowedError, file: file, line: line
|
||||
)
|
||||
}
|
||||
// Compute error in ulp, compare to tolerance.
|
||||
let absoluteError = (TestLiteralType(observed) - expected).magnitude
|
||||
let scale = max(expectedT.magnitude, T.leastNormalMagnitude).ulp
|
||||
let ulps = T(absoluteError/TestLiteralType(scale))
|
||||
if ulps > allowedError {
|
||||
print("ULP error was unacceptably large: expected \(expected) but saw \(observed) (\(ulps)-ulp error).")
|
||||
XCTFail(file: file, line: line)
|
||||
}
|
||||
return ulps
|
||||
}
|
||||
|
||||
public func assertClose<T>(
|
||||
_ expected: TestLiteralType,
|
||||
_ observed: T,
|
||||
allowedError: T = 16,
|
||||
worstError: inout T,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) where T: BinaryFloatingPoint {
|
||||
worstError = max(worstError, assertClose(
|
||||
expected, observed, allowedError: allowedError, file: file, line: line
|
||||
))
|
||||
}
|
||||
|
||||
public protocol FixedWidthFloatingPoint: BinaryFloatingPoint
|
||||
where Exponent: FixedWidthInteger,
|
||||
RawSignificand: FixedWidthInteger { }
|
||||
|
||||
#if swift(>=5.3)
|
||||
@available(iOS 14.0, watchOS 14.0, tvOS 7.0, *)
|
||||
@available(macOS, unavailable)
|
||||
@available(macCatalyst, unavailable)
|
||||
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
|
||||
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
|
||||
extension Float16: FixedWidthFloatingPoint { }
|
||||
#endif
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -11,6 +11,7 @@ add_library(ComplexTests
|
||||
ApproximateEqualityTests.swift
|
||||
ArithmeticTests.swift
|
||||
DifferentiableTests.swift
|
||||
ElementaryFunctionTests.swift
|
||||
PropertyTests.swift)
|
||||
set_target_properties(ComplexTests PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
|
||||
@@ -69,10 +69,6 @@ final class DifferentiableTests: XCTestCase {
|
||||
XCTAssertEqual(φDivide(Complex(1, 0)), Complex(0.25, -0.25))
|
||||
XCTAssertEqual(φDivide(Complex(0, 1)), Complex(0.25, 0.25))
|
||||
}
|
||||
|
||||
func testZeroTangentVectorInitializer() {
|
||||
XCTAssertEqual(Complex<Float>(-5, 5).zeroTangentVector, Complex(0, 0))
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,443 @@
|
||||
//===--- ElementaryFunctionTests.swift ------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import ComplexModule
|
||||
import RealModule
|
||||
import _TestSupport
|
||||
|
||||
final class ElementaryFunctionTests: XCTestCase {
|
||||
|
||||
func testExp<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
|
||||
// exp(0) = 1
|
||||
XCTAssertEqual(1, Complex<T>.exp(Complex( 0, 0)))
|
||||
XCTAssertEqual(1, Complex<T>.exp(Complex(-0, 0)))
|
||||
XCTAssertEqual(1, Complex<T>.exp(Complex(-0,-0)))
|
||||
XCTAssertEqual(1, Complex<T>.exp(Complex( 0,-0)))
|
||||
// In general, exp(Complex(r,0)) should be exp(r), but that breaks down
|
||||
// when r is infinity or NaN, because we want all non-finite complex
|
||||
// values to be semantically a single point at infinity. This is fine
|
||||
// for most inputs, but exp(Complex(-.infinity, 0)) would produce
|
||||
// 0 if we evaluated it in the usual way.
|
||||
XCTAssertFalse(Complex<T>.exp(Complex( .infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.exp(Complex( .infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.exp(Complex( 0, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.exp(Complex(-.infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.exp(Complex(-.infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.exp(Complex(-.infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.exp(Complex( 0,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.exp(Complex( .infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.exp(Complex( .nan, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.exp(Complex( .infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.exp(Complex( .nan, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.exp(Complex(-.infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.exp(Complex( .nan,-.infinity)).isFinite)
|
||||
// Find a value of x such that exp(x) just overflows. Then exp((x, π/4))
|
||||
// should not overflow, but will do so if it is not computed carefully.
|
||||
// The correct value is:
|
||||
//
|
||||
// exp((log(gfm) + log(9/8), π/4) = exp((log(gfm*9/8), π/4))
|
||||
// = gfm*9/8 * (1/sqrt(2), 1/(sqrt(2))
|
||||
let x = T.log(.greatestFiniteMagnitude) + T.log(9/8)
|
||||
let huge = Complex<T>.exp(Complex(x, .pi/4))
|
||||
let mag = T.greatestFiniteMagnitude/T.sqrt(2) * (9/8)
|
||||
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
|
||||
XCTAssert(huge.imaginary.isApproximatelyEqual(to: mag))
|
||||
// For randomly-chosen well-scaled finite values, we expect to have the
|
||||
// usual identities:
|
||||
//
|
||||
// exp(z + w) = exp(z) * exp(w)
|
||||
// exp(z - w) = exp(z) / exp(w)
|
||||
var g = SystemRandomNumberGenerator()
|
||||
let values: [Complex<T>] = (0..<100).map { _ in
|
||||
Complex(T.random(in: -1 ... 1, using: &g),
|
||||
T.random(in: -.pi ... .pi, using: &g))
|
||||
}
|
||||
for z in values {
|
||||
for w in values {
|
||||
let p = Complex.exp(z) * Complex.exp(w)
|
||||
let q = Complex.exp(z) / Complex.exp(w)
|
||||
XCTAssert(Complex.exp(z + w).isApproximatelyEqual(to: p))
|
||||
XCTAssert(Complex.exp(z - w).isApproximatelyEqual(to: q))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testExpMinusOne<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
|
||||
// expMinusOne(0) = 0
|
||||
XCTAssertEqual(0, Complex<T>.expMinusOne(Complex( 0, 0)))
|
||||
XCTAssertEqual(0, Complex<T>.expMinusOne(Complex(-0, 0)))
|
||||
XCTAssertEqual(0, Complex<T>.expMinusOne(Complex(-0,-0)))
|
||||
XCTAssertEqual(0, Complex<T>.expMinusOne(Complex( 0,-0)))
|
||||
// In general, expMinusOne(Complex(r,0)) should be expMinusOne(r), but
|
||||
// that breaks down when r is infinity or NaN, because we want all non-
|
||||
// finite complex values to be semantically a single point at infinity.
|
||||
// This is fine for most inputs, but expMinusOne(Complex(-.infinity, 0))
|
||||
// would produce 0 if we evaluated it in the usual way.
|
||||
XCTAssertFalse(Complex<T>.expMinusOne(Complex( .infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.expMinusOne(Complex( .infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.expMinusOne(Complex( 0, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.expMinusOne(Complex(-.infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.expMinusOne(Complex(-.infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.expMinusOne(Complex(-.infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.expMinusOne(Complex( 0,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.expMinusOne(Complex( .infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.expMinusOne(Complex( .nan, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.expMinusOne(Complex( .infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.expMinusOne(Complex( .nan, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.expMinusOne(Complex(-.infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.expMinusOne(Complex( .nan,-.infinity)).isFinite)
|
||||
// Near-overflow test, same as exp() above.
|
||||
let x = T.log(.greatestFiniteMagnitude) + T.log(9/8)
|
||||
let huge = Complex<T>.expMinusOne(Complex(x, .pi/4))
|
||||
let mag = T.greatestFiniteMagnitude/T.sqrt(2) * (9/8)
|
||||
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
|
||||
XCTAssert(huge.imaginary.isApproximatelyEqual(to: mag))
|
||||
// For small values, expMinusOne should be approximately the identity.
|
||||
var g = SystemRandomNumberGenerator()
|
||||
let small = T.ulpOfOne
|
||||
for _ in 0 ..< 100 {
|
||||
let z = Complex<T>(T.random(in: -small ... small, using: &g),
|
||||
T.random(in: -small ... small, using: &g))
|
||||
XCTAssert(z.isApproximatelyEqual(to: Complex.expMinusOne(z), relativeTolerance: 16 * .ulpOfOne))
|
||||
}
|
||||
}
|
||||
|
||||
func testLogOnePlus<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
|
||||
// log(onePlus: 0) = 0
|
||||
XCTAssertEqual(0, Complex<T>.log(onePlus: Complex( 0, 0)))
|
||||
XCTAssertEqual(0, Complex<T>.log(onePlus: Complex(-0, 0)))
|
||||
XCTAssertEqual(0, Complex<T>.log(onePlus: Complex(-0,-0)))
|
||||
XCTAssertEqual(0, Complex<T>.log(onePlus: Complex( 0,-0)))
|
||||
// log(onePlus:) is the identity at infinity.
|
||||
XCTAssertFalse(Complex<T>.log(onePlus: Complex( .infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.log(onePlus: Complex( .infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.log(onePlus: Complex( 0, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.log(onePlus: Complex(-.infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.log(onePlus: Complex(-.infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.log(onePlus: Complex(-.infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.log(onePlus: Complex( 0,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.log(onePlus: Complex( .infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.log(onePlus: Complex( .nan, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.log(onePlus: Complex( .infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.log(onePlus: Complex( .nan, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.log(onePlus: Complex(-.infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.log(onePlus: Complex( .nan,-.infinity)).isFinite)
|
||||
// For randomly-chosen well-scaled finite values, we expect to have
|
||||
// log(onePlus: expMinusOne(z)) ≈ z
|
||||
var g = SystemRandomNumberGenerator()
|
||||
let values: [Complex<T>] = (0..<1000).map { _ in
|
||||
Complex(T.random(in: -2 ... 2, using: &g),
|
||||
T.random(in: -2 ... 2, using: &g))
|
||||
}
|
||||
for z in values {
|
||||
let w = Complex.expMinusOne(z)
|
||||
let u = Complex.log(onePlus: w)
|
||||
if !u.isApproximatelyEqual(to: z) {
|
||||
print("log(onePlus: expMinusOne()) was not close to identity at z = \(z).")
|
||||
print("expMinusOne(\(z)) = \(w).")
|
||||
print("long(onePlus: \(w)) = \(u).")
|
||||
XCTFail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testCosh<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
|
||||
// cosh(0) = 1
|
||||
XCTAssertEqual(1, Complex<T>.cosh(Complex( 0, 0)))
|
||||
XCTAssertEqual(1, Complex<T>.cosh(Complex(-0, 0)))
|
||||
XCTAssertEqual(1, Complex<T>.cosh(Complex(-0,-0)))
|
||||
XCTAssertEqual(1, Complex<T>.cosh(Complex( 0,-0)))
|
||||
// cosh is the identity at infinity.
|
||||
XCTAssertFalse(Complex<T>.cosh(Complex( .infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.cosh(Complex( .infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.cosh(Complex( 0, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.cosh(Complex(-.infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.cosh(Complex(-.infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.cosh(Complex(-.infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.cosh(Complex( 0,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.cosh(Complex( .infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.cosh(Complex( .nan, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.cosh(Complex( .infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.cosh(Complex( .nan, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.cosh(Complex(-.infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.cosh(Complex( .nan,-.infinity)).isFinite)
|
||||
// Near-overflow test, same as exp() above, but it happens later, because
|
||||
// for large x, cosh(x + iy) ~ exp(x + iy)/2.
|
||||
let x = T.log(.greatestFiniteMagnitude) + T.log(18/8)
|
||||
let mag = T.greatestFiniteMagnitude/T.sqrt(2) * (9/8)
|
||||
var huge = Complex<T>.cosh(Complex(x, .pi/4))
|
||||
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
|
||||
XCTAssert(huge.imaginary.isApproximatelyEqual(to: mag))
|
||||
huge = Complex<T>.cosh(Complex(-x, .pi/4))
|
||||
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
|
||||
XCTAssert(huge.imaginary.isApproximatelyEqual(to: mag))
|
||||
}
|
||||
|
||||
func testSinh<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
|
||||
// sinh(0) = 0
|
||||
XCTAssertEqual(0, Complex<T>.sinh(Complex( 0, 0)))
|
||||
XCTAssertEqual(0, Complex<T>.sinh(Complex(-0, 0)))
|
||||
XCTAssertEqual(0, Complex<T>.sinh(Complex(-0,-0)))
|
||||
XCTAssertEqual(0, Complex<T>.sinh(Complex( 0,-0)))
|
||||
// sinh is the identity at infinity.
|
||||
XCTAssertFalse(Complex<T>.sinh(Complex( .infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.sinh(Complex( .infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.sinh(Complex( 0, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.sinh(Complex(-.infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.sinh(Complex(-.infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.sinh(Complex(-.infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.sinh(Complex( 0,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.sinh(Complex( .infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.sinh(Complex( .nan, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.sinh(Complex( .infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.sinh(Complex( .nan, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.sinh(Complex(-.infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.sinh(Complex( .nan,-.infinity)).isFinite)
|
||||
// Near-overflow test, same as exp() above, but it happens later, because
|
||||
// for large x, sinh(x + iy) ~ ±exp(x + iy)/2.
|
||||
let x = T.log(.greatestFiniteMagnitude) + T.log(18/8)
|
||||
let mag = T.greatestFiniteMagnitude/T.sqrt(2) * (9/8)
|
||||
var huge = Complex<T>.sinh(Complex(x, .pi/4))
|
||||
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
|
||||
XCTAssert(huge.imaginary.isApproximatelyEqual(to: mag))
|
||||
huge = Complex<T>.sinh(Complex(-x, .pi/4))
|
||||
XCTAssert(huge.real.isApproximatelyEqual(to: -mag))
|
||||
XCTAssert(huge.imaginary.isApproximatelyEqual(to: -mag))
|
||||
// For randomly-chosen well-scaled finite values, we expect to have
|
||||
// cosh² - sinh² ≈ 1. Note that this test would break down due to
|
||||
// catastrophic cancellation as we get further away from the origin.
|
||||
var g = SystemRandomNumberGenerator()
|
||||
let values: [Complex<T>] = (0..<1000).map { _ in
|
||||
Complex(T.random(in: -2 ... 2, using: &g),
|
||||
T.random(in: -2 ... 2, using: &g))
|
||||
}
|
||||
for z in values {
|
||||
let c = Complex.cosh(z)
|
||||
let s = Complex.sinh(z)
|
||||
XCTAssert((c*c - s*s).isApproximatelyEqual(to: 1))
|
||||
}
|
||||
}
|
||||
|
||||
func testAcos<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
|
||||
// acos(1) = 0
|
||||
XCTAssertEqual(0, Complex<T>.acos(1))
|
||||
// acos(0) = π/2
|
||||
XCTAssert(Complex<T>.acos(0).real.isApproximatelyEqual(to: .pi/2))
|
||||
XCTAssertEqual(Complex<T>.acos(0).imaginary, 0)
|
||||
// acos(-1) = π
|
||||
XCTAssert(Complex<T>.acos(-1).real.isApproximatelyEqual(to: .pi))
|
||||
XCTAssertEqual(Complex<T>.acos(-1).imaginary, 0)
|
||||
// acos is the identity at infinity.
|
||||
XCTAssertFalse(Complex<T>.acos(Complex( .infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acos(Complex( .infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acos(Complex( 0, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acos(Complex(-.infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acos(Complex(-.infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acos(Complex(-.infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acos(Complex( 0,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acos(Complex( .infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acos(Complex( .nan, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acos(Complex( .infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acos(Complex( .nan, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acos(Complex(-.infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acos(Complex( .nan,-.infinity)).isFinite)
|
||||
// For randomly-chosen well-scaled finite values, we expect to have
|
||||
// cos(acos(z)) ≈ z and acos(z) ≈ π - acos(-z)
|
||||
var g = SystemRandomNumberGenerator()
|
||||
let values: [Complex<T>] = (0..<1000).map { _ in
|
||||
Complex(T.random(in: -2 ... 2, using: &g),
|
||||
T.random(in: -2 ... 2, using: &g))
|
||||
}
|
||||
for z in values {
|
||||
let w = Complex.acos(z)
|
||||
XCTAssert(Complex.cos(w).isApproximatelyEqual(to: z))
|
||||
XCTAssert(w.isApproximatelyEqual(to: Complex(.pi) - .acos(-z)))
|
||||
}
|
||||
}
|
||||
|
||||
func testAsin<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
|
||||
// asin(1) = π/2
|
||||
XCTAssert(Complex<T>.asin(1).real.isApproximatelyEqual(to: .pi/2))
|
||||
XCTAssertEqual(Complex<T>.asin(1).imaginary, 0)
|
||||
// asin(0) = 0
|
||||
XCTAssertEqual(0, Complex<T>.asin(0))
|
||||
// asin(-1) = -π/2
|
||||
XCTAssert(Complex<T>.asin(-1).real.isApproximatelyEqual(to: -.pi/2))
|
||||
XCTAssertEqual(Complex<T>.asin(-1).imaginary, 0)
|
||||
// asin is the identity at infinity.
|
||||
XCTAssertFalse(Complex<T>.asin(Complex( .infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asin(Complex( .infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asin(Complex( 0, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asin(Complex(-.infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asin(Complex(-.infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asin(Complex(-.infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asin(Complex( 0,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asin(Complex( .infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asin(Complex( .nan, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asin(Complex( .infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asin(Complex( .nan, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asin(Complex(-.infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asin(Complex( .nan,-.infinity)).isFinite)
|
||||
// For randomly-chosen well-scaled finite values, we expect to have
|
||||
// sin(asin(z)) ≈ z and asin(z) ≈ -asin(-z)
|
||||
var g = SystemRandomNumberGenerator()
|
||||
let values: [Complex<T>] = (0..<1000).map { _ in
|
||||
Complex(T.random(in: -2 ... 2, using: &g),
|
||||
T.random(in: -2 ... 2, using: &g))
|
||||
}
|
||||
for z in values {
|
||||
let w = Complex.asin(z)
|
||||
XCTAssert(Complex.sin(w).isApproximatelyEqual(to: z))
|
||||
XCTAssert(w.isApproximatelyEqual(to: -.asin(-z)))
|
||||
}
|
||||
}
|
||||
|
||||
func testAcosh<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
|
||||
// acosh(1) = 0
|
||||
XCTAssertEqual(0, Complex<T>.acosh(1))
|
||||
// acosh(0) = iπ/2
|
||||
XCTAssert(Complex<T>.acosh(0).imaginary.isApproximatelyEqual(to: .pi/2))
|
||||
XCTAssertEqual(Complex<T>.acosh(0).real, 0)
|
||||
// acosh(-1) = iπ
|
||||
XCTAssert(Complex<T>.acosh(-1).imaginary.isApproximatelyEqual(to: .pi))
|
||||
XCTAssertEqual(Complex<T>.acosh(-1).real, 0)
|
||||
// acosh is the identity at infinity.
|
||||
XCTAssertFalse(Complex<T>.acosh(Complex( .infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acosh(Complex( .infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acosh(Complex( 0, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acosh(Complex(-.infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acosh(Complex(-.infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acosh(Complex(-.infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acosh(Complex( 0,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acosh(Complex( .infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acosh(Complex( .nan, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acosh(Complex( .infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acosh(Complex( .nan, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acosh(Complex(-.infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.acosh(Complex( .nan,-.infinity)).isFinite)
|
||||
// For randomly-chosen well-scaled finite values, we expect to have
|
||||
// cosh(acosh(z)) ≈ z
|
||||
var g = SystemRandomNumberGenerator()
|
||||
let values: [Complex<T>] = (0..<1000).map { _ in
|
||||
Complex(T.random(in: -2 ... 2, using: &g),
|
||||
T.random(in: -2 ... 2, using: &g))
|
||||
}
|
||||
for z in values {
|
||||
let w = Complex.acosh(z)
|
||||
XCTAssert(Complex.cosh(w).isApproximatelyEqual(to: z))
|
||||
}
|
||||
}
|
||||
|
||||
func testAsinh<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
|
||||
// asinh(1) = π/2
|
||||
XCTAssert(Complex<T>.asin(1).real.isApproximatelyEqual(to: .pi/2))
|
||||
XCTAssertEqual(Complex<T>.asin(1).imaginary, 0)
|
||||
// asinh(0) = 0
|
||||
XCTAssertEqual(0, Complex<T>.asin(0))
|
||||
// asinh(-1) = -π/2
|
||||
XCTAssert(Complex<T>.asin(-1).real.isApproximatelyEqual(to: -.pi/2))
|
||||
XCTAssertEqual(Complex<T>.asin(-1).imaginary, 0)
|
||||
// asinh is the identity at infinity.
|
||||
XCTAssertFalse(Complex<T>.asinh(Complex( .infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asinh(Complex( .infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asinh(Complex( 0, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asinh(Complex(-.infinity, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asinh(Complex(-.infinity, 0)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asinh(Complex(-.infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asinh(Complex( 0,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asinh(Complex( .infinity,-.infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asinh(Complex( .nan, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asinh(Complex( .infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asinh(Complex( .nan, .infinity)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asinh(Complex(-.infinity, .nan)).isFinite)
|
||||
XCTAssertFalse(Complex<T>.asinh(Complex( .nan,-.infinity)).isFinite)
|
||||
// For randomly-chosen well-scaled finite values, we expect to have
|
||||
// sinh(asinh(z)) ≈ z
|
||||
var g = SystemRandomNumberGenerator()
|
||||
let values: [Complex<T>] = (0..<1000).map { _ in
|
||||
Complex(T.random(in: -2 ... 2, using: &g),
|
||||
T.random(in: -2 ... 2, using: &g))
|
||||
}
|
||||
for z in values {
|
||||
let w = Complex.asinh(z)
|
||||
let u = Complex.sinh(w)
|
||||
if !u.isApproximatelyEqual(to: z) {
|
||||
print("sinh(asinh()) was not close to identity at z = \(z).")
|
||||
print("asinh(\(z)) = \(w).")
|
||||
print("sinh(\(w)) = \(u).")
|
||||
XCTFail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testAtanh<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
|
||||
// For randomly-chosen well-scaled finite values, we expect to have
|
||||
// atanh(tanh(z)) ≈ z
|
||||
var g = SystemRandomNumberGenerator()
|
||||
let values: [Complex<T>] = (0..<1000).map { _ in
|
||||
Complex(T.random(in: -2 ... 2, using: &g),
|
||||
T.random(in: -2 ... 2, using: &g))
|
||||
}
|
||||
for z in values {
|
||||
let w = Complex.atanh(z)
|
||||
let u = Complex.tanh(w)
|
||||
if !u.isApproximatelyEqual(to: z) {
|
||||
print("tanh(atanh()) was not close to identity at z = \(z).")
|
||||
print("atanh(\(z)) = \(w).")
|
||||
print("tanh(\(w)) = \(u).")
|
||||
XCTFail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFloat() {
|
||||
testExp(Float.self)
|
||||
testExpMinusOne(Float.self)
|
||||
testLogOnePlus(Float.self)
|
||||
testCosh(Float.self)
|
||||
testSinh(Float.self)
|
||||
testAcos(Float.self)
|
||||
testAsin(Float.self)
|
||||
testAcosh(Float.self)
|
||||
testAsinh(Float.self)
|
||||
testAtanh(Float.self)
|
||||
}
|
||||
|
||||
func testDouble() {
|
||||
testExp(Double.self)
|
||||
testExpMinusOne(Double.self)
|
||||
testLogOnePlus(Float.self)
|
||||
testCosh(Double.self)
|
||||
testSinh(Double.self)
|
||||
testAcos(Double.self)
|
||||
testAsin(Double.self)
|
||||
testAcosh(Double.self)
|
||||
testAsinh(Double.self)
|
||||
testAtanh(Double.self)
|
||||
}
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
func testFloat80() {
|
||||
testExp(Float80.self)
|
||||
testExpMinusOne(Float80.self)
|
||||
testLogOnePlus(Float.self)
|
||||
testCosh(Float80.self)
|
||||
testSinh(Float80.self)
|
||||
testAcos(Float80.self)
|
||||
testAsin(Float80.self)
|
||||
testAcosh(Float80.self)
|
||||
testAsinh(Float80.self)
|
||||
testAtanh(Float80.self)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
//===--- main.swift -------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Numerics
|
||||
import _TestSupport
|
||||
|
||||
#if DEBUG
|
||||
fatalError("Run this test in Release configuration")
|
||||
#else
|
||||
|
||||
var componentError = Double(Float.ulpOfOne/2)
|
||||
var complexError = Double(Float.ulpOfOne/2)
|
||||
var componentMaxInput = Complex<Float>.zero
|
||||
var complexMaxInput = Complex<Float>.zero
|
||||
|
||||
func test(_ z: Complex<Float>) {
|
||||
let tst = Complex.log(z)
|
||||
// TODO: we _should_ be able to say Complex<Double>(z), but that goes through
|
||||
// the slow, generic path for BinaryFloatingPoint conversion; once we get
|
||||
// that resolved in the standard library, we can replace the conversion on
|
||||
// this and the next line. Currently it dominate testing time if we do that.
|
||||
let ref = Complex.log(Complex(Double(z.real), Double(z.imaginary)))
|
||||
if tst == Complex(Float(ref.real), Float(ref.imaginary)) { return }
|
||||
let thisError = relativeError(tst, ref)
|
||||
if thisError > complexError {
|
||||
complexMaxInput = z
|
||||
complexError = thisError
|
||||
}
|
||||
let thisComponentError = componentwiseError(tst, ref)
|
||||
if thisComponentError > componentError {
|
||||
componentMaxInput = z
|
||||
componentError = thisComponentError
|
||||
}
|
||||
}
|
||||
|
||||
func testWithSymmetries(_ x: Float, _ y: Float) {
|
||||
test(Complex( x, y))
|
||||
test(Complex( y, x))
|
||||
test(Complex(-y, x))
|
||||
test(Complex(-x, y))
|
||||
test(Complex(-x,-y))
|
||||
test(Complex(-y,-x))
|
||||
test(Complex( y,-x))
|
||||
test(Complex( x,-y))
|
||||
}
|
||||
|
||||
// The hardest to evaluate cases for log are those close to the unit circle,
|
||||
// where log(z) is nearly zero. We want to have plausibly dense test coverage
|
||||
// close to the circle.
|
||||
let radii: [Float] = [0.9,
|
||||
0.95,
|
||||
0.99,
|
||||
0.999,
|
||||
0.9999,
|
||||
1 - 10 * .ulpOfOne,
|
||||
1,
|
||||
1 + 10 * .ulpOfOne,
|
||||
1.0001,
|
||||
1.001,
|
||||
1.01,
|
||||
1.05,
|
||||
1.1]
|
||||
|
||||
for r in radii {
|
||||
for x in Interval(from: 1/Float.sqrt(2), to: r) {
|
||||
// Generate the two y values that put us closest to the circle of radius r
|
||||
let base = Double.sqrt(Double(r).addingProduct(Double(-x), Double(x)))
|
||||
let a, b: Float
|
||||
if Double(Float(base)) < base { a = Float(base); b = a.nextUp }
|
||||
else { b = Float(base); a = b.nextDown }
|
||||
testWithSymmetries(x, a)
|
||||
testWithSymmetries(x, b)
|
||||
}
|
||||
}
|
||||
|
||||
// Away from the unit circle is "easy" but we still want to get some coverage.
|
||||
// Generate 1 million uniform random points inside the circle, and then test
|
||||
// both z and 1/z.
|
||||
var g = SystemRandomNumberGenerator()
|
||||
var count = 0
|
||||
while count < 1_000_000 {
|
||||
let z = Complex<Float>(.random(in: -1 ... 1, using: &g), .random(in: -1 ... 1, using: &g))
|
||||
if z.length > 1 { continue }
|
||||
count += 1
|
||||
test(z)
|
||||
test(1/z)
|
||||
}
|
||||
|
||||
print("Worst complex norm error seen for log was \(complexError)")
|
||||
print("For input \(complexMaxInput).")
|
||||
print("Reference result: \(Complex.log(Complex<Double>(complexMaxInput)))")
|
||||
print(" Observed result: \(Complex.log(complexMaxInput))")
|
||||
|
||||
print("Worst componentwise error seen for log was \(componentError)")
|
||||
print("For input \(componentMaxInput).")
|
||||
print("Reference result: \(Complex.log(Complex<Double>(componentMaxInput)))")
|
||||
print(" Observed result: \(Complex.log(componentMaxInput))")
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,108 @@
|
||||
//===--- main.swift -------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Numerics
|
||||
import _TestSupport
|
||||
|
||||
#if DEBUG
|
||||
fatalError("Run this test in Release configuration")
|
||||
#else
|
||||
|
||||
var componentError = Double(Float.ulpOfOne/2)
|
||||
var complexError = Double(Float.ulpOfOne/2)
|
||||
var componentMaxInput = Complex<Float>.zero
|
||||
var complexMaxInput = Complex<Float>.zero
|
||||
|
||||
func test(_ z: Complex<Float>) {
|
||||
let tst = Complex.log(onePlus: z)
|
||||
// TODO: we _should_ be able to say Complex<Double>(z), but that goes through
|
||||
// the slow, generic path for BinaryFloatingPoint conversion; once we get
|
||||
// that resolved in the standard library, we can replace the conversion on
|
||||
// this and the next line. Currently it dominate testing time if we do that.
|
||||
let ref = Complex.log(onePlus: Complex(Double(z.real), Double(z.imaginary)))
|
||||
if tst == Complex(Float(ref.real), Float(ref.imaginary)) { return }
|
||||
let thisError = relativeError(tst, ref)
|
||||
if thisError > complexError {
|
||||
complexMaxInput = z
|
||||
complexError = thisError
|
||||
}
|
||||
let thisComponentError = componentwiseError(tst, ref)
|
||||
if thisComponentError > componentError {
|
||||
componentMaxInput = z
|
||||
componentError = thisComponentError
|
||||
}
|
||||
}
|
||||
|
||||
func testWithSymmetry(_ x: Float, _ y: Float) {
|
||||
test(Complex( x-1, y))
|
||||
test(Complex( y-1, x))
|
||||
test(Complex(-y-1, x))
|
||||
test(Complex(-x-1, y))
|
||||
test(Complex(-x-1,-y))
|
||||
test(Complex(-y-1,-x))
|
||||
test(Complex( y-1,-x))
|
||||
test(Complex( x-1,-y))
|
||||
}
|
||||
|
||||
// The hardest to evaluate cases for log are those close to the unit circle
|
||||
// centered at -1, where log(1+z) is nearly zero. We want to have plausibly
|
||||
// dense test coverage close to the circle.
|
||||
let radii: [Float] = [0.9,
|
||||
0.95,
|
||||
0.99,
|
||||
0.999,
|
||||
0.9999,
|
||||
1 - 10 * .ulpOfOne,
|
||||
1,
|
||||
1 + 10 * .ulpOfOne,
|
||||
1.0001,
|
||||
1.001,
|
||||
1.01,
|
||||
1.05,
|
||||
1.1]
|
||||
|
||||
for r in radii {
|
||||
for x in Interval(from: 1/Float.sqrt(2), to: r) {
|
||||
// Generate the two y values that put us closest to the circle of radius r
|
||||
let base = Double.sqrt(Double(r).addingProduct(Double(-x), Double(x)))
|
||||
let a, b: Float
|
||||
if Double(Float(base)) < base { a = Float(base); b = a.nextUp }
|
||||
else { b = Float(base); a = b.nextDown }
|
||||
testWithSymmetry(x, a)
|
||||
testWithSymmetry(x, b)
|
||||
}
|
||||
}
|
||||
|
||||
// Away from the unit circle is "easy" but we still want to get some coverage.
|
||||
// Generate 1 million uniform random points inside the circle, and then test
|
||||
// both z and 1/z.
|
||||
var g = SystemRandomNumberGenerator()
|
||||
var count = 0
|
||||
while count < 1_000_000 {
|
||||
let z = Complex<Float>(.random(in: -1 ... 1, using: &g), .random(in: -1 ... 1, using: &g))
|
||||
if z.length > 1 { continue }
|
||||
count += 1
|
||||
test(z - 1)
|
||||
test(1/z - 1)
|
||||
}
|
||||
|
||||
print("Worst complex norm error seen for log(onePlus:) was \(complexError)")
|
||||
print("For input \(complexMaxInput).")
|
||||
print("Reference result: \(Complex.log(onePlus: Complex<Double>(complexMaxInput)))")
|
||||
print(" Observed result: \(Complex.log(onePlus: complexMaxInput))")
|
||||
|
||||
print("Worst componentwise error seen for log(onePlus:) was \(componentError)")
|
||||
print("For input \(componentMaxInput).")
|
||||
print("Reference result: \(Complex.log(onePlus: Complex<Double>(componentMaxInput)))")
|
||||
print(" Observed result: \(Complex.log(onePlus: componentMaxInput))")
|
||||
|
||||
#endif
|
||||
@@ -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.")
|
||||
@@ -13,6 +13,76 @@ import XCTest
|
||||
import RealModule
|
||||
import _TestSupport
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
public typealias TestLiteralType = Float80
|
||||
#else
|
||||
public typealias TestLiteralType = Double
|
||||
#endif
|
||||
|
||||
@discardableResult
|
||||
internal func assertClose<T>(
|
||||
_ expected: TestLiteralType,
|
||||
_ observed: T,
|
||||
allowedError: T = 16,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) -> T where T: BinaryFloatingPoint {
|
||||
// Shortcut relative-error check if we got the sign wrong; it's OK to
|
||||
// underflow to zero, but we do not want to allow going right through
|
||||
// zero and getting the sign wrong.
|
||||
guard observed.sign == expected.sign else {
|
||||
print("Sign was wrong: expected \(expected) but saw \(observed).")
|
||||
XCTFail(file: file, line: line)
|
||||
return .infinity
|
||||
}
|
||||
if observed.isNaN && expected.isNaN { return 0 }
|
||||
// If T(expected) is zero or infinite, and matches observed, the error
|
||||
// is zero.
|
||||
let expectedT = T(expected)
|
||||
if observed.isZero && expectedT.isZero { return 0 }
|
||||
if observed.isInfinite && expectedT.isInfinite { return 0 }
|
||||
// Special-case where only one of expectedT or observed is infinity.
|
||||
// Artificially knock everything down a binade, treat actual infinity as
|
||||
// the base of the next binade up.
|
||||
func topBinade(signOf x: T) -> T {
|
||||
T(signOf: x, magnitudeOf: T.greatestFiniteMagnitude.binade)
|
||||
}
|
||||
if observed.isInfinite {
|
||||
return assertClose(
|
||||
expected/2, topBinade(signOf: observed),
|
||||
allowedError: allowedError, file: file, line: line
|
||||
)
|
||||
}
|
||||
if expectedT.isInfinite {
|
||||
return assertClose(
|
||||
TestLiteralType(topBinade(signOf: expectedT)), observed/2,
|
||||
allowedError: allowedError, file: file, line: line
|
||||
)
|
||||
}
|
||||
// Compute error in ulp, compare to tolerance.
|
||||
let absoluteError = (TestLiteralType(observed) - expected).magnitude
|
||||
let scale = max(expectedT.magnitude, T.leastNormalMagnitude).ulp
|
||||
let ulps = T(absoluteError/TestLiteralType(scale))
|
||||
if ulps > allowedError {
|
||||
print("ULP error was unacceptably large: expected \(expected) but saw \(observed) (\(ulps)-ulp error).")
|
||||
XCTFail(file: file, line: line)
|
||||
}
|
||||
return ulps
|
||||
}
|
||||
|
||||
internal func assertClose<T>(
|
||||
_ expected: TestLiteralType,
|
||||
_ observed: T,
|
||||
allowedError: T = 16,
|
||||
worstError: inout T,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) where T: BinaryFloatingPoint {
|
||||
worstError = max(worstError, assertClose(
|
||||
expected, observed, allowedError: allowedError, file: file, line: line
|
||||
))
|
||||
}
|
||||
|
||||
internal extension ElementaryFunctions where Self: BinaryFloatingPoint {
|
||||
static func elementaryFunctionChecks() {
|
||||
assertClose(1.1863995522992575361931268186727044683, Self.acos(0.375))
|
||||
@@ -58,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.3) && !os(macOS)
|
||||
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
|
||||
func testFloat16() {
|
||||
if #available(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
|
||||
@@ -72,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
|
||||
}
|
||||
@@ -77,9 +77,8 @@ internal extension Real where Self: FixedWidthFloatingPoint {
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.3)
|
||||
@available(iOS 14.0, watchOS 14.0, tvOS 7.0, *)
|
||||
@available(macOS, unavailable)
|
||||
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
|
||||
@available(macOS 11.0, iOS 14.0, watchOS 14.0, tvOS 7.0, *)
|
||||
extension Float16 {
|
||||
static func testIntegerExponent() {
|
||||
testIntegerExponentCommon()
|
||||
@@ -136,9 +135,9 @@ extension Float {
|
||||
extension Double {
|
||||
static func testIntegerExponent() {
|
||||
testIntegerExponentCommon()
|
||||
testIntegerExponentDoubleAndSmaller()
|
||||
// Following tests only make sense (and are only necessary) on 64b platforms.
|
||||
#if arch(arm64) || arch(x86_64)
|
||||
testIntegerExponentDoubleAndSmaller()
|
||||
let u: Double = 1.nextUp
|
||||
let d: Double = 1.nextDown
|
||||
// Smallest exponent not exactly representable as Double.
|
||||
@@ -174,10 +173,12 @@ extension Double {
|
||||
}
|
||||
|
||||
final class IntegerExponentTests: XCTestCase {
|
||||
|
||||
#if swift(>=5.3) && !os(macOS)
|
||||
|
||||
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
|
||||
func testFloat16() {
|
||||
Float16.testIntegerExponent()
|
||||
if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
|
||||
Float16.testIntegerExponent()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -1,111 +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.3)
|
||||
extension ElementaryFunctionChecks {
|
||||
static var all = testCase([
|
||||
("testFloat16", ElementaryFunctionChecks.testFloat16),
|
||||
("testFloat", ElementaryFunctionChecks.testFloat),
|
||||
("testDouble", ElementaryFunctionChecks.testDouble),
|
||||
])
|
||||
}
|
||||
#else
|
||||
extension ElementaryFunctionChecks {
|
||||
static var all = testCase([
|
||||
("testFloat", ElementaryFunctionChecks.testFloat),
|
||||
("testDouble", ElementaryFunctionChecks.testDouble),
|
||||
])
|
||||
}
|
||||
#endif
|
||||
|
||||
#if swift(>=5.3)
|
||||
extension IntegerExponentTests {
|
||||
static var all = testCase([
|
||||
("testFloat16", IntegerExponentTests.testFloat16),
|
||||
("testFloat", IntegerExponentTests.testFloat),
|
||||
("testDouble", IntegerExponentTests.testDouble),
|
||||
])
|
||||
}
|
||||
#else
|
||||
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
|
||||
@@ -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")
|
||||
|
||||
Reference in new issue
Block a user