mirror of
https://github.com/apple/swift-numerics
synced 2026-11-22 04:30:45 +00:00
Compare commits
212
Commits
0.0.2
...
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 | ||
|
|
3d7462a834 | ||
|
|
0f8ef268d0 | ||
|
|
694e5ae6de | ||
|
|
c26e60c6ba | ||
|
|
96a5383b0a | ||
|
|
38b5251804 | ||
|
|
aaec0af9c8 | ||
|
|
3811e3bc7a | ||
|
|
a0501be80a | ||
|
|
cda1b5e6f4 | ||
|
|
fa16d7db6a | ||
|
|
a4372aa8d6 | ||
|
|
145156c40e | ||
|
|
c2d6cb716d | ||
|
|
4077cd3461 | ||
|
|
337be4044e | ||
|
|
ddbc41f80b | ||
|
|
2342ba6314 | ||
|
|
6af70e51ea | ||
|
|
d32bb739d4 | ||
|
|
6b89e8d4b0 | ||
|
|
ce58d083a1 | ||
|
|
555340e882 | ||
|
|
7109a22972 | ||
|
|
ea6d7ffd5e | ||
|
|
97824411d9 | ||
|
|
d368762c95 | ||
|
|
7e032e20fc | ||
|
|
1ec79f5270 | ||
|
|
44cb9f2d4a | ||
|
|
af3912cd4a | ||
|
|
4771ef24d2 | ||
|
|
336740bd6d | ||
|
|
189f072825 | ||
|
|
e6a343a205 | ||
|
|
66ac02125c | ||
|
|
4cd11553db | ||
|
|
13b74ae5f4 | ||
|
|
2828bec340 | ||
|
|
e69f12617b | ||
|
|
80522b2bee | ||
|
|
a7ef6cd74c | ||
|
|
18ce9c0bbd | ||
|
|
06c17a9a0f | ||
|
|
2327363b24 | ||
|
|
8b73836979 | ||
|
|
1dcd7f314b | ||
|
|
30627f2d06 | ||
|
|
c07076e917 | ||
|
|
968d004d54 | ||
|
|
cfeda4df2d | ||
|
|
f275f7df53 | ||
|
|
7c0eb30664 | ||
|
|
91ecc8a3b6 | ||
|
|
40b5a03063 | ||
|
|
110beefe0b | ||
|
|
085f6dab2e | ||
|
|
e97070e36c | ||
|
|
93b8e9f0df | ||
|
|
697e9351e8 | ||
|
|
f30f73ed10 | ||
|
|
c634b5ddce | ||
|
|
86f0b33c65 | ||
|
|
593946d4aa | ||
|
|
5f09b7ef22 | ||
|
|
6d75786ee0 | ||
|
|
4297fbee6a | ||
|
|
a410fd7029 | ||
|
|
c111cd001e | ||
|
|
52fa265ac9 | ||
|
|
750170404a | ||
|
|
a5cc950a86 | ||
|
|
5ae8cd103a | ||
|
|
488e250259 | ||
|
|
6e77726ac9 | ||
|
|
c14381db8c | ||
|
|
8978159f21 | ||
|
|
59444343c4 | ||
|
|
ee082efdaf | ||
|
|
6dc8bb4d17 | ||
|
|
ff6a0ff2a5 | ||
|
|
4db6faa3e7 | ||
|
|
75e4116989 | ||
|
|
9e1645a495 | ||
|
|
29d25b62c5 | ||
|
|
a35f5ba889 | ||
|
|
fc9ff1401d | ||
|
|
33d10c02cd | ||
|
|
5dfc460876 | ||
|
|
014ce562a4 | ||
|
|
9dba38cc1a | ||
|
|
0fa2cd458e | ||
|
|
be3d09ab26 | ||
|
|
ba4469d3fd | ||
|
|
6951647e4c | ||
|
|
a7c141e818 | ||
|
|
76954c06a7 | ||
|
|
4352c3a6a1 | ||
|
|
43052f0819 | ||
|
|
119377cc49 | ||
|
|
016cd6a2fc | ||
|
|
a2aa24d236 | ||
|
|
eda432142d | ||
|
|
7bd2909875 | ||
|
|
323542cba1 | ||
|
|
98f3d25fe8 | ||
|
|
f3e1e15312 | ||
|
|
8cbda03867 | ||
|
|
b6839260cb | ||
|
|
1879299216 | ||
|
|
53af148f0f | ||
|
|
2c12891617 | ||
|
|
f25a870cec | ||
|
|
3d637e1302 | ||
|
|
b7e48c538c | ||
|
|
7ff707f6f8 | ||
|
|
de5399615c | ||
|
|
f7842a76db | ||
|
|
5bf2f828ef | ||
|
|
65aac0be46 | ||
|
|
55f33b7769 | ||
|
|
5e978d85a2 |
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
|
||||
@@ -4,3 +4,4 @@
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
/.swiftpm
|
||||
.*.sw?
|
||||
@@ -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>
|
||||
@@ -0,0 +1,30 @@
|
||||
#[[
|
||||
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
|
||||
#]]
|
||||
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
project(swift-numerics
|
||||
LANGUAGES Swift)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/modules)
|
||||
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift)
|
||||
|
||||
include(CTest)
|
||||
include(SwiftSupport)
|
||||
|
||||
add_subdirectory(Sources)
|
||||
|
||||
get_property(SWIFT_NUMERICS_EXPORTS GLOBAL PROPERTY SWIFT_NUMERICS_EXPORTS)
|
||||
export(TARGETS ${SWIFT_NUMERICS_EXPORTS}
|
||||
NAMESPACE SwiftNumerics::
|
||||
FILE swift-numerics-config.cmake
|
||||
EXPORT_LINK_INTERFACE_LIBRARIES)
|
||||
+26
-11
@@ -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,21 +13,36 @@
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
|
||||
name: "swift-numerics",
|
||||
products: [
|
||||
.library(name: "Complex", targets: ["Complex"]),
|
||||
.library(name: "ComplexModule", targets: ["ComplexModule"]),
|
||||
.library(name: "Numerics", targets: ["Numerics"]),
|
||||
.library(name: "Real", targets: ["Real"]),
|
||||
],
|
||||
dependencies: [
|
||||
.library(name: "RealModule", targets: ["RealModule"]),
|
||||
],
|
||||
|
||||
targets: [
|
||||
.target(name: "Complex", dependencies: ["Real"]),
|
||||
.target(name: "Numerics", dependencies: ["Complex", "Real"]),
|
||||
.target(name: "NumericsShims", dependencies: []),
|
||||
.target(name: "Real", dependencies: ["NumericsShims"]),
|
||||
// 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, .android]))
|
||||
]
|
||||
),
|
||||
|
||||
.testTarget(name: "ComplexTests", dependencies: ["Complex", "NumericsShims"]),
|
||||
.testTarget(name: "RealTests", dependencies: ["Real"]),
|
||||
// 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,63 +1,140 @@
|
||||
# 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 the Complex module without pulling in everything else in the library as well:
|
||||
```swift
|
||||
import Complex
|
||||
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.
|
||||
|
||||
## Process
|
||||
Swift Numerics is a standalone library separate from the core Swift project.
|
||||
In practice, it will act as a staging ground for some APIs that may eventually be incorporated into the Swift Standard Library, and when that happens such changes will be proposed to the Swift Standard Library using the established evolution process of the Swift project.
|
||||
## Using Swift Numerics in your project
|
||||
|
||||
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: "1.0.0"),
|
||||
```
|
||||
|
||||
2. Add `Numerics` as a dependency for your target:
|
||||
|
||||
```swift
|
||||
.target(name: "MyTarget", dependencies: [
|
||||
.product(name: "Numerics", package: "swift-numerics"),
|
||||
"AnotherModule"
|
||||
]),
|
||||
```
|
||||
|
||||
3. Add `import Numerics` in your source code.
|
||||
|
||||
## Source stability
|
||||
|
||||
The Swift Numerics package is source stable; version numbers follow [Semantic Versioning](https://semver.org).
|
||||
The public API of the `swift-numerics` package consists of non-underscored declarations that are marked either `public` or `usableFromInline` in modules re-exported by the top-level `Numerics` module, *excepting any API that involves a conformance to Differentiable (because Differentiable itself is not stable in Swift)*.
|
||||
Interfaces that aren't part of the public API may continue to change in any release, including patch releases.
|
||||
|
||||
Note that contents of the `_NumericsShims` and `_TestSupport` modules, as well as contents of the `Tests` directory, explicitly are not public API.
|
||||
The definitions therein may therefore change at whim, and the entire module may be removed in any new release.
|
||||
If you have a use case that requires underscored operations, please raise an issue to request that they be made public API.
|
||||
|
||||
Future minor versions of the package may introduce changes to these rules as needed.
|
||||
|
||||
We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate.
|
||||
Accordingly, from time to time, we expect that new versions of this package will require clients to upgrade to a more recent Swift toolchain release.
|
||||
Requiring a new Swift release will only require a minor version bump.
|
||||
|
||||
## Contributing to Swift Numerics
|
||||
|
||||
Swift Numerics is a standalone library that is separate from the core Swift project, but it will sometimes act as a staging ground for APIs that will later be incorporated into the Swift Standard Library.
|
||||
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. [Real](Sources/Real/README.md)
|
||||
2. [Complex](Sources/Complex/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)
|
||||
6. [Float16](https://github.com/apple/swift-numerics/issues/8)
|
||||
|
||||
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 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> // 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.
|
||||
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.
|
||||
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.
|
||||
@@ -0,0 +1,16 @@
|
||||
#[[
|
||||
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
|
||||
#]]
|
||||
|
||||
add_subdirectory(_NumericsShims)
|
||||
add_subdirectory(ComplexModule)
|
||||
add_subdirectory(Numerics)
|
||||
add_subdirectory(RealModule)
|
||||
if(BUILD_TESTING)
|
||||
add_subdirectory(_TestSupport)
|
||||
endif()
|
||||
@@ -9,6 +9,8 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import RealModule
|
||||
|
||||
// MARK: - Additive structure
|
||||
extension Complex: AdditiveArithmetic {
|
||||
@_transparent
|
||||
@@ -50,19 +52,37 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Multiplicative structure
|
||||
extension Complex: Numeric {
|
||||
extension Complex: AlgebraicField {
|
||||
@_transparent
|
||||
public static func *(z: Complex, w: Complex) -> Complex {
|
||||
return Complex(z.x*w.x - z.y*w.y, z.x*w.y + z.y*w.x)
|
||||
@@ -124,8 +144,8 @@ extension Complex: Numeric {
|
||||
|
||||
/// 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 {
|
||||
@@ -137,16 +157,18 @@ extension Complex: Numeric {
|
||||
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 }
|
||||
/// }
|
||||
@@ -154,6 +176,12 @@ extension Complex: Numeric {
|
||||
/// 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
|
||||
@@ -163,5 +191,3 @@ extension Complex: Numeric {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
extension Complex: SignedNumeric {}
|
||||
@@ -0,0 +1,22 @@
|
||||
#[[
|
||||
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
|
||||
#]]
|
||||
|
||||
add_library(ComplexModule
|
||||
Arithmetic.swift
|
||||
Complex.swift
|
||||
Differentiable.swift
|
||||
ElementaryFunctions.swift)
|
||||
set_target_properties(ComplexModule PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
target_link_libraries(ComplexModule PUBLIC
|
||||
RealModule)
|
||||
|
||||
|
||||
_install_target(ComplexModule)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_NUMERICS_EXPORTS ComplexModule)
|
||||
@@ -2,14 +2,14 @@
|
||||
//
|
||||
// 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 Real
|
||||
import RealModule
|
||||
|
||||
/// A complex number represented by real and imaginary parts.
|
||||
///
|
||||
@@ -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 }
|
||||
@@ -344,11 +351,23 @@ extension Complex: Hashable {
|
||||
}
|
||||
|
||||
// MARK: - Conformance to Codable
|
||||
// The synthesized conformance works correction for this protocol, unlike
|
||||
// Hashable and Equatable; all we need to do is specify that we conform.
|
||||
// FloatingPoint does not refine Codable, so this is a conditional conformance.
|
||||
extension Complex: Encodable where RealType: Encodable { }
|
||||
extension Complex: Decodable where RealType: Decodable { }
|
||||
extension Complex: Decodable where RealType: Decodable {
|
||||
public init(from decoder: Decoder) throws {
|
||||
var unkeyedContainer = try decoder.unkeyedContainer()
|
||||
let x = try unkeyedContainer.decode(RealType.self)
|
||||
let y = try unkeyedContainer.decode(RealType.self)
|
||||
self.init(x, y)
|
||||
}
|
||||
}
|
||||
|
||||
extension Complex: Encodable where RealType: Encodable {
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var unkeyedContainer = encoder.unkeyedContainer()
|
||||
try unkeyedContainer.encode(x)
|
||||
try unkeyedContainer.encode(y)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Formatting
|
||||
extension Complex: CustomStringConvertible {
|
||||
@@ -369,7 +388,7 @@ extension Complex: CustomDebugStringConvertible {
|
||||
// MARK: - Operations for working with polar form
|
||||
extension Complex {
|
||||
|
||||
/// The euclidean norm (a.k.a. 2-norm, `sqrt(real*real + imaginary*imaginary)`).
|
||||
/// The Euclidean norm (a.k.a. 2-norm, `sqrt(real*real + imaginary*imaginary)`).
|
||||
///
|
||||
/// This property takes care to avoid spurious over- or underflow in
|
||||
/// this computation. For example:
|
||||
@@ -479,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,99 @@
|
||||
//===--- Differentiable.swift ---------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if swift(>=5.3) && canImport(_Differentiation)
|
||||
import _Differentiation
|
||||
|
||||
extension Complex: Differentiable
|
||||
where RealType: Differentiable, RealType.TangentVector == RealType {
|
||||
public typealias TangentVector = Self
|
||||
|
||||
@inlinable
|
||||
public var zeroTangentVectorInitializer: () -> Self {
|
||||
{ Complex.zero }
|
||||
}
|
||||
}
|
||||
|
||||
extension Complex
|
||||
where RealType: Differentiable, RealType.TangentVector == RealType {
|
||||
@derivative(of: init(_:_:))
|
||||
@usableFromInline
|
||||
static func _derivativeInit(
|
||||
_ real: RealType,
|
||||
_ imaginary: RealType
|
||||
) -> (value: Complex, pullback: (Complex) -> (RealType, RealType)) {
|
||||
(value: .init(real, imaginary), pullback: { v in
|
||||
(v.real, v.imaginary)
|
||||
})
|
||||
}
|
||||
|
||||
@derivative(of: real)
|
||||
@usableFromInline
|
||||
func _derivativeReal() -> (value: RealType, pullback: (RealType) -> Complex) {
|
||||
(value: real, pullback: { v in
|
||||
Complex(v, .zero)
|
||||
})
|
||||
}
|
||||
|
||||
@derivative(of: imaginary)
|
||||
@usableFromInline
|
||||
func _derivativeImaginary() -> (
|
||||
value: RealType,
|
||||
pullback: (RealType) -> Complex
|
||||
) {
|
||||
(value: real, pullback: { v in
|
||||
Complex(.zero, v)
|
||||
})
|
||||
}
|
||||
|
||||
@derivative(of: +)
|
||||
@usableFromInline
|
||||
static func _derivativeAdd(lhs: Complex, rhs: Complex)
|
||||
-> (value: Complex, pullback: (Complex) -> (Complex, Complex))
|
||||
{
|
||||
(lhs + rhs, { v in (v, v) })
|
||||
}
|
||||
|
||||
@derivative(of: -)
|
||||
@usableFromInline
|
||||
static func _derivativeSubtract(lhs: Complex, rhs: Complex)
|
||||
-> (value: Complex, pullback: (Complex) -> (Complex, Complex))
|
||||
{
|
||||
(lhs - rhs, { v in (v, -v) })
|
||||
}
|
||||
|
||||
@derivative(of: *)
|
||||
@usableFromInline
|
||||
static func _derivativeMultiply(lhs: Complex, rhs: Complex)
|
||||
-> (value: Complex, pullback: (Complex) -> (Complex, Complex))
|
||||
{
|
||||
(lhs * rhs, { v in (rhs * v, lhs * v) })
|
||||
}
|
||||
|
||||
@derivative(of: /)
|
||||
@usableFromInline
|
||||
static func _derivativeDivide(lhs: Complex, rhs: Complex)
|
||||
-> (value: Complex, pullback: (Complex) -> (Complex, Complex))
|
||||
{
|
||||
(lhs / rhs, { v in (v / rhs, -lhs / (rhs * rhs) * v) })
|
||||
}
|
||||
|
||||
@derivative(of: conjugate)
|
||||
@usableFromInline
|
||||
func _derivativeConjugate() -> (
|
||||
value: Complex,
|
||||
pullback: (Complex) -> Complex
|
||||
) {
|
||||
(conjugate, { v in v.conjugate })
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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)))
|
||||
}
|
||||
}
|
||||
@@ -2,15 +2,15 @@
|
||||
|
||||
This module provides a `Complex` number type generic over an underlying `RealType`:
|
||||
```swift
|
||||
1> import Complex
|
||||
1> import ComplexModule
|
||||
2> let z = Complex(1,1) // z = 1 + i
|
||||
```
|
||||
This module provides approximate feature parity and memory layout compatibility with C, Fortran, and C++ complex types (although the importer cannot map the types for you, buffers may be reinterpreted to shim API defined in other languages).
|
||||
|
||||
The usual arithmetic operators are provided for Complex numbers, as well as conversion to and from polar coordinates and many useful properties, plus conformances to the obvious usual protocols: `Equatable`, `Hashable`, `Codable` (if the underlying `RealType` is), and `Numeric` (hence also `AdditiveArithmetic`).
|
||||
The usual arithmetic operators are provided for Complex numbers, as well as conversion to and from polar coordinates and many useful properties, plus conformances to the obvious usual protocols: `Equatable`, `Hashable`, `Codable` (if the underlying `RealType` is), and `AlgebraicField` (hence also `AdditiveArithmetic` and `SignedNumeric`).
|
||||
|
||||
### Dependencies:
|
||||
- The `Real` module.
|
||||
- `RealModule`.
|
||||
|
||||
## Design notes
|
||||
|
||||
@@ -60,7 +60,7 @@ Because of this, the ∞-norm is the obvious alternative; it gives the nicest AP
|
||||
- The ∞-norm is heavily used in other computational libraries; for example, it is used by the `izamax` and `icamax` functions in BLAS.
|
||||
|
||||
The 2-norm still needs to be available, of course, because sometimes you need it.
|
||||
This functionality is accessed via the `.length` and `.unsafeLengthSquared` properties.
|
||||
This functionality is accessed via the `.length` and `.lengthSquared` properties.
|
||||
|
||||
### Accuracy of division and multiplication
|
||||
This library attempts to provide robust division and multiplication operations, with small relative error in a complex norm. It is a non-goal to deliver small componentwise errors.
|
||||
@@ -0,0 +1,27 @@
|
||||
#[[
|
||||
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
|
||||
#]]
|
||||
|
||||
add_library(Numerics
|
||||
Numerics.swift)
|
||||
set_target_properties(Numerics PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
# NOTE: generate the force load symbol to ensure that the import library is
|
||||
# generated on Windows for autolinking.
|
||||
target_compile_options(Numerics PUBLIC
|
||||
$<$<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)
|
||||
target_link_libraries(Numerics PUBLIC
|
||||
ComplexModule
|
||||
RealModule)
|
||||
|
||||
|
||||
_install_target(Numerics)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_NUMERICS_EXPORTS Numerics)
|
||||
@@ -10,5 +10,5 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// A module that re-exports the complete Swift Numerics public API.
|
||||
@_exported import Real
|
||||
@_exported import Complex
|
||||
@_exported import RealModule
|
||||
@_exported import ComplexModule
|
||||
@@ -1,82 +0,0 @@
|
||||
//===--- Real.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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A type that models the real numbers.
|
||||
///
|
||||
/// Types conforming to this protocol provide the arithmetic and utility operations defined by
|
||||
/// the `FloatingPoint` protocol, and provide all of the math functions defined by the
|
||||
/// `ElementaryFunctions` and `RealFunctions` protocols. This protocol does not
|
||||
/// add any additional conformances itself, but is very useful as a protocol against which to
|
||||
/// write generic code. For example, we can naturally write a generic version of the a sigmoid
|
||||
/// function:
|
||||
/// ```
|
||||
/// func sigmoid<T: Real>(_ x: T) -> T {
|
||||
/// return 1/(1 + .exp(-x))
|
||||
/// }
|
||||
/// ```
|
||||
/// See Also:
|
||||
/// -
|
||||
/// - `ElementaryFunctions`
|
||||
/// - `RealFunctions`
|
||||
public protocol Real: FloatingPoint, RealFunctions {
|
||||
}
|
||||
|
||||
// While `Real` does not provide any additional customization points,
|
||||
// it does allow us to default the implementation of a few operations,
|
||||
// and also provides `signGamma`.
|
||||
extension Real {
|
||||
// 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)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
public static func signGamma(_ x: Self) -> FloatingPointSign {
|
||||
// Gamma is strictly positive for x >= 0.
|
||||
if x >= 0 { return .plus }
|
||||
// For negative x, we arbitrarily choose to assign a sign of .plus to the
|
||||
// poles.
|
||||
let trunc = x.rounded(.towardZero)
|
||||
if x == trunc { return .plus }
|
||||
// Otherwise, signGamma is .minus if the integral part of x is even.
|
||||
return trunc.isEven ? .minus : .plus
|
||||
}
|
||||
|
||||
// Determines if this value is even, assuming that it is an integer.
|
||||
@inline(__always)
|
||||
private var isEven: Bool {
|
||||
if Self.radix == 2 {
|
||||
// For binary types, we can just check if x/2 is an integer. This works
|
||||
// because x/2 is always computed exactly.
|
||||
let half = self/2
|
||||
return half == half.rounded(.towardZero)
|
||||
} else {
|
||||
// For decimal types, it's not quite that simple, because x/2 is not
|
||||
// necessarily computed exactly. As an example, suppose that we had a
|
||||
// decimal type with a one digit significand, and self = 7. Then self/2
|
||||
// would round to 4, and we would (wrongly) conclude that it was an
|
||||
// integer, and hence that self was even.
|
||||
//
|
||||
// Instead, for decimal types, we check if 2*trunc(self/2) == self,
|
||||
// using an FMA; this is always correct; this approach works for any
|
||||
// radix, but the previous method is more efficient for radix == 2.
|
||||
let half = self/2
|
||||
return self.addingProduct(-2, half.rounded(.towardZero)) == 0
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@_transparent
|
||||
public static func sqrt(_ x: Self) -> Self {
|
||||
return x.squareRoot()
|
||||
}
|
||||
}
|
||||
@@ -1,222 +0,0 @@
|
||||
//===--- ScalarConformances.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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// In theory we might be able to get away with using @_silgen_name for these
|
||||
// instead of NumericShims and remove a level of (source-only) indirection.
|
||||
// However, at present if we do that we get a compiler crash when this module
|
||||
// and the Swift platform module are both imported (<rdar://problem/53821031>).
|
||||
import NumericsShims
|
||||
|
||||
// MARK: Float + Real
|
||||
extension Float: Real {
|
||||
@_transparent public static func cos(_ x: Float) -> Float { return libm_cosf(x) }
|
||||
@_transparent public static func sin(_ x: Float) -> Float { return libm_sinf(x) }
|
||||
@_transparent public static func tan(_ x: Float) -> Float { return libm_tanf(x) }
|
||||
@_transparent public static func acos(_ x: Float) -> Float { return libm_acosf(x) }
|
||||
@_transparent public static func asin(_ x: Float) -> Float { return libm_asinf(x) }
|
||||
@_transparent public static func atan(_ x: Float) -> Float { return libm_atanf(x) }
|
||||
@_transparent public static func cosh(_ x: Float) -> Float { return libm_coshf(x) }
|
||||
@_transparent public static func sinh(_ x: Float) -> Float { return libm_sinhf(x) }
|
||||
@_transparent public static func tanh(_ x: Float) -> Float { return libm_tanhf(x) }
|
||||
@_transparent public static func acosh(_ x: Float) -> Float { return libm_acoshf(x) }
|
||||
@_transparent public static func asinh(_ x: Float) -> Float { return libm_asinhf(x) }
|
||||
@_transparent public static func atanh(_ x: Float) -> Float { return libm_atanhf(x) }
|
||||
@_transparent public static func exp(_ x: Float) -> Float { return libm_expf(x) }
|
||||
@_transparent public static func expMinusOne(_ x: Float) -> Float { return libm_expm1f(x) }
|
||||
@_transparent public static func log(_ x: Float) -> Float { return libm_logf(x) }
|
||||
@_transparent public static func log(onePlus x: Float) -> Float { return libm_log1pf(x) }
|
||||
@_transparent public static func erf(_ x: Float) -> Float { return libm_erff(x) }
|
||||
@_transparent public static func erfc(_ x: Float) -> Float { return libm_erfcf(x) }
|
||||
@_transparent public static func exp2(_ x: Float) -> Float { return libm_exp2f(x) }
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
@_transparent public static func exp10(_ x: Float) -> Float { return libm_exp10f(x) }
|
||||
#endif
|
||||
@_transparent public static func hypot(_ x: Float, _ y: Float) -> Float { return libm_hypotf(x, y) }
|
||||
@_transparent public static func gamma(_ x: Float) -> Float { return libm_tgammaf(x) }
|
||||
@_transparent public static func log2(_ x: Float) -> Float { return libm_log2f(x) }
|
||||
@_transparent public static func log10(_ x: Float) -> Float { return libm_log10f(x) }
|
||||
|
||||
@_transparent public static func pow(_ x: Float, _ y: Float) -> Float {
|
||||
guard x >= 0 else { return .nan }
|
||||
return libm_powf(x, y)
|
||||
}
|
||||
|
||||
@_transparent public static func pow(_ x: Float, _ n: Int) -> Float {
|
||||
// TODO: this implementation is not quite correct, because n may be
|
||||
// rounded in conversion to Float. This only effects very extreme cases,
|
||||
// so we'll leave it alone for now; however, it gets the sign wrong if
|
||||
// it rounds an odd number to an even number, so we should fix it soon.
|
||||
return libm_powf(x, Float(n))
|
||||
}
|
||||
|
||||
@_transparent public static func root(_ x: Float, _ n: Int) -> Float {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// Workaround the issue mentioned below for the specific case of n = 3
|
||||
// where we can fallback on cbrt.
|
||||
if n == 3 { return libm_cbrtf(x) }
|
||||
// TODO: this implementation is not quite correct, because either n or
|
||||
// 1/n may be not be representable as Float.
|
||||
return Float(signOf: x, magnitudeOf: libm_powf(x.magnitude, 1/Float(n)))
|
||||
}
|
||||
|
||||
@_transparent public static func atan2(y: Float, x: Float) -> Float {
|
||||
return libm_atan2f(y, x)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_transparent public static func logGamma(_ x: Float) -> Float {
|
||||
var dontCare: Int32 = 0
|
||||
return libm_lgammaf(x, &dontCare)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: Double + Real
|
||||
extension Double: Real {
|
||||
@_transparent public static func cos(_ x: Double) -> Double { return libm_cos(x) }
|
||||
@_transparent public static func sin(_ x: Double) -> Double { return libm_sin(x) }
|
||||
@_transparent public static func tan(_ x: Double) -> Double { return libm_tan(x) }
|
||||
@_transparent public static func acos(_ x: Double) -> Double { return libm_acos(x) }
|
||||
@_transparent public static func asin(_ x: Double) -> Double { return libm_asin(x) }
|
||||
@_transparent public static func atan(_ x: Double) -> Double { return libm_atan(x) }
|
||||
@_transparent public static func cosh(_ x: Double) -> Double { return libm_cosh(x) }
|
||||
@_transparent public static func sinh(_ x: Double) -> Double { return libm_sinh(x) }
|
||||
@_transparent public static func tanh(_ x: Double) -> Double { return libm_tanh(x) }
|
||||
@_transparent public static func acosh(_ x: Double) -> Double { return libm_acosh(x) }
|
||||
@_transparent public static func asinh(_ x: Double) -> Double { return libm_asinh(x) }
|
||||
@_transparent public static func atanh(_ x: Double) -> Double { return libm_atanh(x) }
|
||||
@_transparent public static func exp(_ x: Double) -> Double { return libm_exp(x) }
|
||||
@_transparent public static func expMinusOne(_ x: Double) -> Double { return libm_expm1(x) }
|
||||
@_transparent public static func log(_ x: Double) -> Double { return libm_log(x) }
|
||||
@_transparent public static func log(onePlus x: Double) -> Double { return libm_log1p(x) }
|
||||
@_transparent public static func erf(_ x: Double) -> Double { return libm_erf(x) }
|
||||
@_transparent public static func erfc(_ x: Double) -> Double { return libm_erfc(x) }
|
||||
@_transparent public static func exp2(_ x: Double) -> Double { return libm_exp2(x) }
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
@_transparent public static func exp10(_ x: Double) -> Double { return libm_exp10(x) }
|
||||
#endif
|
||||
#if os(macOS) && arch(x86_64)
|
||||
// Workaround for macOS bug (<rdar://problem/56844150>) where hypot can
|
||||
// overflow for values very close to the overflow boundary of the naive
|
||||
// algorithm. Since this is only for macOS, we can just unconditionally
|
||||
// use Float80, which makes the implementation trivial.
|
||||
public static func hypot(_ x: Double, _ y: Double) -> Double {
|
||||
if x.isInfinite || y.isInfinite { return .infinity }
|
||||
let x80 = Float80(x)
|
||||
let y80 = Float80(y)
|
||||
return Double(Float80.sqrt(x80*x80 + y80*y80))
|
||||
}
|
||||
#else
|
||||
@_transparent public static func hypot(_ x: Double, _ y: Double) -> Double {
|
||||
return libm_hypot(x, y)
|
||||
}
|
||||
#endif
|
||||
@_transparent public static func gamma(_ x: Double) -> Double { return libm_tgamma(x) }
|
||||
@_transparent public static func log2(_ x: Double) -> Double { return libm_log2(x) }
|
||||
@_transparent public static func log10(_ x: Double) -> Double { return libm_log10(x) }
|
||||
|
||||
@_transparent public static func pow(_ x: Double, _ y: Double) -> Double {
|
||||
guard x >= 0 else { return .nan }
|
||||
return libm_pow(x, y)
|
||||
}
|
||||
|
||||
@_transparent public static func pow(_ x: Double, _ n: Int) -> Double {
|
||||
// TODO: this implementation is not quite correct, because n may be
|
||||
// rounded in conversion to Double. This only effects very extreme cases,
|
||||
// so we'll leave it alone for now; however, it gets the sign wrong if
|
||||
// it rounds an odd number to an even number, so we should fix it soon.
|
||||
return libm_pow(x, Double(n))
|
||||
}
|
||||
|
||||
@_transparent public static func root(_ x: Double, _ n: Int) -> Double {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// Workaround the issue mentioned below for the specific case of n = 3
|
||||
// where we can fallback on cbrt.
|
||||
if n == 3 { return libm_cbrt(x) }
|
||||
// TODO: this implementation is not quite correct, because either n or
|
||||
// 1/n may be not be representable as Double.
|
||||
return Double(signOf: x, magnitudeOf: libm_pow(x.magnitude, 1/Double(n)))
|
||||
}
|
||||
|
||||
@_transparent public static func atan2(y: Double, x: Double) -> Double {
|
||||
return libm_atan2(y, x)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_transparent public static func logGamma(_ x: Double) -> Double {
|
||||
var dontCare: Int32 = 0
|
||||
return libm_lgamma(x, &dontCare)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: Float80 + Real
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
extension Float80: Real {
|
||||
@_transparent public static func cos(_ x: Float80) -> Float80 { return libm_cosl(x) }
|
||||
@_transparent public static func sin(_ x: Float80) -> Float80 { return libm_sinl(x) }
|
||||
@_transparent public static func tan(_ x: Float80) -> Float80 { return libm_tanl(x) }
|
||||
@_transparent public static func acos(_ x: Float80) -> Float80 { return libm_acosl(x) }
|
||||
@_transparent public static func asin(_ x: Float80) -> Float80 { return libm_asinl(x) }
|
||||
@_transparent public static func atan(_ x: Float80) -> Float80 { return libm_atanl(x) }
|
||||
@_transparent public static func cosh(_ x: Float80) -> Float80 { return libm_coshl(x) }
|
||||
@_transparent public static func sinh(_ x: Float80) -> Float80 { return libm_sinhl(x) }
|
||||
@_transparent public static func tanh(_ x: Float80) -> Float80 { return libm_tanhl(x) }
|
||||
@_transparent public static func acosh(_ x: Float80) -> Float80 { return libm_acoshl(x) }
|
||||
@_transparent public static func asinh(_ x: Float80) -> Float80 { return libm_asinhl(x) }
|
||||
@_transparent public static func atanh(_ x: Float80) -> Float80 { return libm_atanhl(x) }
|
||||
@_transparent public static func exp(_ x: Float80) -> Float80 { return libm_expl(x) }
|
||||
@_transparent public static func expMinusOne(_ x: Float80) -> Float80 { return libm_expm1l(x) }
|
||||
@_transparent public static func log(_ x: Float80) -> Float80 { return libm_logl(x) }
|
||||
@_transparent public static func log(onePlus x: Float80) -> Float80 { return libm_log1pl(x) }
|
||||
@_transparent public static func erf(_ x: Float80) -> Float80 { return libm_erfl(x) }
|
||||
@_transparent public static func erfc(_ x: Float80) -> Float80 { return libm_erfcl(x) }
|
||||
@_transparent public static func exp2(_ x: Float80) -> Float80 { return libm_exp2l(x) }
|
||||
@_transparent public static func hypot(_ x: Float80, _ y: Float80) -> Float80 { return libm_hypotl(x, y) }
|
||||
@_transparent public static func gamma(_ x: Float80) -> Float80 { return libm_tgammal(x) }
|
||||
@_transparent public static func log2(_ x: Float80) -> Float80 { return libm_log2l(x) }
|
||||
@_transparent public static func log10(_ x: Float80) -> Float80 { return libm_log10l(x) }
|
||||
|
||||
@_transparent public static func pow(_ x: Float80, _ y: Float80) -> Float80 {
|
||||
guard x >= 0 else { return .nan }
|
||||
return libm_powl(x, y)
|
||||
}
|
||||
|
||||
@_transparent public static func pow(_ x: Float80, _ n: Int) -> Float80 {
|
||||
// TODO: this implementation is not quite correct, because n may be
|
||||
// rounded in conversion to Float80. This only effects very extreme cases,
|
||||
// so we'll leave it alone for now; however, it gets the sign wrong if
|
||||
// it rounds an odd number to an even number, so we should fix it soon.
|
||||
return libm_powl(x, Float80(n))
|
||||
}
|
||||
|
||||
@_transparent public static func root(_ x: Float80, _ n: Int) -> Float80 {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// Workaround the issue mentioned below for the specific case of n = 3
|
||||
// where we can fallback on cbrt.
|
||||
if n == 3 { return libm_cbrtl(x) }
|
||||
// TODO: this implementation is not quite correct, because either n or
|
||||
// 1/n may be not be representable as Float80.
|
||||
return Float80(signOf: x, magnitudeOf: libm_powl(x.magnitude, 1/Float80(n)))
|
||||
}
|
||||
|
||||
@_transparent public static func atan2(y: Float80, x: Float80) -> Float80 {
|
||||
return libm_atan2l(y, x)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_transparent public static func logGamma(_ x: Float80) -> Float80 {
|
||||
var dontCare: Int32 = 0
|
||||
return libm_lgammal(x, &dontCare)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,110 @@
|
||||
//===--- AlgebraicField.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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A type modeling an algebraic [field]. Refines the `SignedNumeric` protocol,
|
||||
/// adding division.
|
||||
///
|
||||
/// A field is a set on which addition, subtraction, multiplication, and
|
||||
/// division are defined, and behave basically like those operations on
|
||||
/// the real numbers. More precisely, a field is a commutative group under
|
||||
/// its addition, the non-zero elements of the field form a commutative
|
||||
/// group under its multiplication, and the distributitve law holds.
|
||||
///
|
||||
/// Some common examples of fields include:
|
||||
///
|
||||
/// - the rational numbers
|
||||
/// - the real numbers
|
||||
/// - the complex numbers
|
||||
/// - the integers modulo a prime
|
||||
///
|
||||
/// The most familiar example of a thing that is *not* a field is the integers.
|
||||
/// This may be surprising, since integers seem to have addition, subtraction,
|
||||
/// multiplication and division. Why don't they form a field?
|
||||
///
|
||||
/// Because integer multiplication does not form a group; it's commutative and
|
||||
/// associative, but integers do not have multiplicative inverses.
|
||||
/// I.e. if a is any integer other than 1 or -1, there is no integer b such
|
||||
/// that a*b = 1. The existence of inverses is requried to form a field.
|
||||
///
|
||||
/// If a type `T` conforms to the `Real` protocol, then `T` and `Complex<T>`
|
||||
/// both conform to `AlgebraicField`.
|
||||
///
|
||||
/// See Also:
|
||||
/// -
|
||||
/// - Real
|
||||
/// - SignedNumeric
|
||||
/// - Numeric
|
||||
/// - AdditiveArithmetic
|
||||
///
|
||||
/// [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 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.
|
||||
///
|
||||
/// 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 }
|
||||
}
|
||||
|
||||
extension AlgebraicField {
|
||||
@_transparent
|
||||
public static func /(a: Self, b: Self) -> Self {
|
||||
var result = a
|
||||
result /= b
|
||||
return result
|
||||
}
|
||||
|
||||
/// Implementations should be *conservative* with the reciprocal property;
|
||||
/// it is OK to return `nil` even in cases where a reciprocal could be
|
||||
/// represented. For this reason, a default implementation that simply
|
||||
/// always returns `nil` is correct, but conforming types should provide
|
||||
/// a better implementation if possible.
|
||||
public var reciprocal: Self? {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
//===--- ApproximateEquality.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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Numeric where Magnitude: FloatingPoint {
|
||||
/// Test if `self` and `other` are approximately equal.
|
||||
///
|
||||
/// `true` if `self` and `other` are equal, or if they are finite and
|
||||
/// ```
|
||||
/// norm(self - other) <= relativeTolerance * scale
|
||||
/// ```
|
||||
/// where `scale` is
|
||||
/// ```
|
||||
/// max(norm(self), norm(other), .leastNormalMagnitude)
|
||||
/// ```
|
||||
///
|
||||
/// 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.
|
||||
///
|
||||
/// Mathematical Properties:
|
||||
/// ------------------------
|
||||
///
|
||||
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _reflexive_ for
|
||||
/// non-exceptional values (such as NaN).
|
||||
///
|
||||
/// - `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.
|
||||
///
|
||||
/// 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.
|
||||
///
|
||||
/// See Also:
|
||||
/// -------
|
||||
/// - `isApproximatelyEqual(to:absoluteTolerance:[relativeTolerance:norm:])`
|
||||
///
|
||||
/// - Parameters:
|
||||
///
|
||||
/// - other: The value to which `self` is compared.
|
||||
///
|
||||
/// - relativeTolerance: The tolerance to use for the comparison.
|
||||
/// 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.
|
||||
///
|
||||
/// - norm: The [norm] to use for the comparison.
|
||||
/// Defaults to `\.magnitude`.
|
||||
///
|
||||
/// [norm]: https://en.wikipedia.org/wiki/Norm_(mathematics)
|
||||
@inlinable @inline(__always)
|
||||
public func isApproximatelyEqual(
|
||||
to other: Self,
|
||||
relativeTolerance: Magnitude = Magnitude.ulpOfOne.squareRoot(),
|
||||
norm: (Self) -> Magnitude = \.magnitude
|
||||
) -> Bool {
|
||||
return isApproximatelyEqual(
|
||||
to: other,
|
||||
absoluteTolerance: relativeTolerance * Magnitude.leastNormalMagnitude,
|
||||
relativeTolerance: relativeTolerance,
|
||||
norm: norm
|
||||
)
|
||||
}
|
||||
|
||||
/// Test if `self` and `other` are approximately equal with specified tolerances.
|
||||
///
|
||||
/// `true` if `self` and `other` are equal, or if they are finite and either
|
||||
/// ```
|
||||
/// (self - other).magnitude <= absoluteTolerance
|
||||
/// ```
|
||||
/// or
|
||||
/// ```
|
||||
/// (self - other).magnitude <= relativeTolerance * scale
|
||||
/// ```
|
||||
/// where `scale` is `max(self.magnitude, other.magnitude)`.
|
||||
///
|
||||
/// Mathematical Properties:
|
||||
/// ------------------------
|
||||
///
|
||||
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:)`
|
||||
/// is _reflexive_ for non-exceptional values (such as NaN).
|
||||
///
|
||||
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:)`
|
||||
/// 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.
|
||||
///
|
||||
/// 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:
|
||||
/// -------
|
||||
/// - `isApproximatelyEqual(to:[relativeTolerance:])`
|
||||
///
|
||||
/// - Parameters:
|
||||
///
|
||||
/// - other: The value to which `self` is compared.
|
||||
///
|
||||
/// - 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.
|
||||
///
|
||||
/// - 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.
|
||||
@inlinable @inline(__always)
|
||||
public func isApproximatelyEqual(
|
||||
to other: Self,
|
||||
absoluteTolerance: Magnitude,
|
||||
relativeTolerance: Magnitude = 0
|
||||
) -> Bool {
|
||||
self.isApproximatelyEqual(
|
||||
to: other,
|
||||
absoluteTolerance: absoluteTolerance,
|
||||
relativeTolerance: relativeTolerance,
|
||||
norm: \.magnitude
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension AdditiveArithmetic {
|
||||
/// 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
|
||||
/// ```
|
||||
/// norm(self - other) <= absoluteTolerance
|
||||
/// ```
|
||||
/// or
|
||||
/// ```
|
||||
/// norm(self - other) <= relativeTolerance * scale
|
||||
/// ```
|
||||
/// where `scale` is `max(norm(self), norm(other))`.
|
||||
///
|
||||
/// Mathematical Properties:
|
||||
/// ------------------------
|
||||
///
|
||||
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:norm:)`
|
||||
/// is _reflexive_ for non-exceptional values (such as NaN).
|
||||
///
|
||||
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:norm:)`
|
||||
/// is _symmetric_.
|
||||
///
|
||||
/// - `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.
|
||||
///
|
||||
/// 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:
|
||||
/// -------
|
||||
/// - `isApproximatelyEqual(to:[relativeTolerance:norm:])`
|
||||
/// - `isApproximatelyEqual(to:absoluteTolerance:[relativeTolerance:])`
|
||||
///
|
||||
/// - Parameters:
|
||||
///
|
||||
/// - other: The value to which `self` is compared.
|
||||
///
|
||||
/// - 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.
|
||||
///
|
||||
/// - 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.
|
||||
///
|
||||
/// - 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:
|
||||
/// ```
|
||||
/// z.isApproximatelyEqual(
|
||||
/// to: 1,
|
||||
/// absoluteTolerance: 0.001,
|
||||
/// norm: \.length
|
||||
/// )
|
||||
/// ```
|
||||
/// (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,
|
||||
absoluteTolerance: Magnitude,
|
||||
relativeTolerance: Magnitude = 0,
|
||||
norm: (Self) -> Magnitude
|
||||
) -> Bool
|
||||
// TODO: constraint should really be weaker than FloatingPoint,
|
||||
// but we need to have `isFinite` for it to work correctly with
|
||||
// floating-point magnitudes in generic contexts, which is the
|
||||
// most common case. The fix for this is to lift the isFinite
|
||||
// requirement to Numeric in the standard library, but that's
|
||||
// source-breaking, so requires an ABI rumspringa.
|
||||
where Magnitude: FloatingPoint {
|
||||
assert(
|
||||
absoluteTolerance >= 0 && absoluteTolerance.isFinite,
|
||||
"absoluteTolerance should be non-negative and finite, " +
|
||||
"but is \(absoluteTolerance)."
|
||||
)
|
||||
assert(
|
||||
relativeTolerance >= 0 && relativeTolerance <= 1,
|
||||
"relativeTolerance should be non-negative and <= 1, " +
|
||||
"but is \(relativeTolerance)."
|
||||
)
|
||||
if self == other { return true }
|
||||
let delta = norm(self - other)
|
||||
let scale = max(norm(self), norm(other))
|
||||
let bound = max(absoluteTolerance, scale*relativeTolerance)
|
||||
return delta.isFinite && delta <= bound
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#[[
|
||||
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
|
||||
#]]
|
||||
|
||||
add_library(RealModule
|
||||
AlgebraicField.swift
|
||||
ApproximateEquality.swift
|
||||
AugmentedArithmetic.swift
|
||||
Double+Real.swift
|
||||
ElementaryFunctions.swift
|
||||
Float+Real.swift
|
||||
Float16+Real.swift
|
||||
Float80+Real.swift
|
||||
Real.swift
|
||||
RealFunctions.swift)
|
||||
set_target_properties(RealModule PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
target_link_libraries(RealModule PUBLIC
|
||||
_NumericsShims)
|
||||
|
||||
|
||||
_install_target(RealModule)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_NUMERICS_EXPORTS RealModule)
|
||||
@@ -0,0 +1,227 @@
|
||||
//===--- Double+Real.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 _NumericsShims
|
||||
|
||||
extension Double: Real {
|
||||
@_transparent
|
||||
public static func cos(_ x: Double) -> Double {
|
||||
libm_cos(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sin(_ x: Double) -> Double {
|
||||
libm_sin(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func tan(_ x: Double) -> Double {
|
||||
libm_tan(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func acos(_ x: Double) -> Double {
|
||||
libm_acos(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func asin(_ x: Double) -> Double {
|
||||
libm_asin(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atan(_ x: Double) -> Double {
|
||||
libm_atan(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func cosh(_ x: Double) -> Double {
|
||||
libm_cosh(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sinh(_ x: Double) -> Double {
|
||||
libm_sinh(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func tanh(_ x: Double) -> Double {
|
||||
libm_tanh(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func acosh(_ x: Double) -> Double {
|
||||
libm_acosh(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func asinh(_ x: Double) -> Double {
|
||||
libm_asinh(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atanh(_ x: Double) -> Double {
|
||||
libm_atanh(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func exp(_ x: Double) -> Double {
|
||||
libm_exp(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func expMinusOne(_ x: Double) -> Double {
|
||||
libm_expm1(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log(_ x: Double) -> Double {
|
||||
libm_log(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log(onePlus x: Double) -> Double {
|
||||
libm_log1p(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func erf(_ x: Double) -> Double {
|
||||
libm_erf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func erfc(_ x: Double) -> Double {
|
||||
libm_erfc(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func exp2(_ x: Double) -> Double {
|
||||
libm_exp2(x)
|
||||
}
|
||||
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
@_transparent
|
||||
public static func exp10(_ x: Double) -> Double {
|
||||
libm_exp10(x)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) && arch(x86_64)
|
||||
// Workaround for macOS bug (<rdar://problem/56844150>) where hypot can
|
||||
// overflow for values very close to the overflow boundary of the naive
|
||||
// algorithm. Since this is only for macOS, we can just unconditionally
|
||||
// use Float80, which makes the implementation trivial.
|
||||
public static func hypot(_ x: Double, _ y: Double) -> Double {
|
||||
if x.isInfinite || y.isInfinite { return .infinity }
|
||||
let x80 = Float80(x)
|
||||
let y80 = Float80(y)
|
||||
return Double(Float80.sqrt(x80*x80 + y80*y80))
|
||||
}
|
||||
#else
|
||||
@_transparent
|
||||
public static func hypot(_ x: Double, _ y: Double) -> Double {
|
||||
libm_hypot(x, y)
|
||||
}
|
||||
#endif
|
||||
|
||||
@_transparent
|
||||
public static func gamma(_ x: Double) -> Double {
|
||||
libm_tgamma(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log2(_ x: Double) -> Double {
|
||||
libm_log2(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log10(_ x: Double) -> Double {
|
||||
libm_log10(x)
|
||||
}
|
||||
|
||||
@_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)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func pow(_ x: Double, _ n: Int) -> Double {
|
||||
// If n is exactly representable as Double, we can just call pow:
|
||||
// Note that all calls on a 32b platform go down this path.
|
||||
if let y = Double(exactly: n) { return libm_pow(x, y) }
|
||||
// n is not representable in Double, so we will split it into two parts,
|
||||
// low and high, such that (high + low) = n, and use the identity:
|
||||
//
|
||||
// x**(high + low) = x**high * x**low.
|
||||
//
|
||||
// We put the high-order 32 bits into high, and the remaining 32 bits
|
||||
// in low.
|
||||
//
|
||||
// The exact split isn't important; all we need is that both pieces get
|
||||
// less than 53 bits (so that they are exact) and that they both have
|
||||
// the same sign as n.
|
||||
//
|
||||
// This second point is a little bit subtle--why is
|
||||
// it necessary? Consider what would happen if we took x = 2 and
|
||||
// n = Int.min + Int(UInt32.max), and simply naively split n without
|
||||
// taking care with the sign. We would end up computing:
|
||||
//
|
||||
// 2**n = 2**Int.min * 2**UInt32.max
|
||||
//
|
||||
// The first exponent is negative, the second positive, so the first term
|
||||
// underflows to zero, and the second overflows to infinity, so the final
|
||||
// result is NaN, when it should be zero. In order to avoid this
|
||||
// situation, we make sure that high contains n rounded *towards zero*,
|
||||
// rather than using simple two's-complement truncation (which rounds
|
||||
// down).
|
||||
let mask = Int(truncatingIfNeeded: UInt32.max)
|
||||
let round = n < 0 ? mask : 0
|
||||
// The addition and subtraction below cannot actually overflow (proof:
|
||||
// round is positive if n is negative, and zero otherwise, so n + round
|
||||
// is guaranteed to be representable, and n and high have the same sign,
|
||||
// so n - high is also representable), but it's hard to tell the compiler
|
||||
// that, so I'm using wrapping operations instead.
|
||||
let high = (n &+ round) & ~mask
|
||||
let low = n &- high
|
||||
return libm_pow(x, Double(low)) * libm_pow(x, Double(high))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func root(_ x: Double, _ n: Int) -> Double {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// Workaround the issue mentioned below for the specific case of n = 3
|
||||
// where we can fallback on cbrt.
|
||||
if n == 3 { return libm_cbrt(x) }
|
||||
// TODO: this implementation is not quite correct, because either n or
|
||||
// 1/n may be not be representable as Double.
|
||||
return Double(signOf: x, magnitudeOf: libm_pow(x.magnitude, 1/Double(n)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atan2(y: Double, x: Double) -> Double {
|
||||
libm_atan2(y, x)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_transparent
|
||||
public static func logGamma(_ x: Double) -> Double {
|
||||
var dontCare: Int32 = 0
|
||||
return libm_lgamma(x, &dontCare)
|
||||
}
|
||||
#endif
|
||||
|
||||
@_transparent
|
||||
public static func _mulAdd(_ a: Double, _ b: Double, _ c: Double) -> Double {
|
||||
_numerics_muladd(a, b, c)
|
||||
}
|
||||
}
|
||||
+35
-23
@@ -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`.
|
||||
@@ -0,0 +1,200 @@
|
||||
//===--- Float+Real.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 _NumericsShims
|
||||
|
||||
extension Float: Real {
|
||||
@_transparent
|
||||
public static func cos(_ x: Float) -> Float {
|
||||
libm_cosf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sin(_ x: Float) -> Float {
|
||||
libm_sinf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func tan(_ x: Float) -> Float {
|
||||
libm_tanf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func acos(_ x: Float) -> Float {
|
||||
libm_acosf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func asin(_ x: Float) -> Float {
|
||||
libm_asinf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atan(_ x: Float) -> Float {
|
||||
libm_atanf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func cosh(_ x: Float) -> Float {
|
||||
libm_coshf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sinh(_ x: Float) -> Float {
|
||||
libm_sinhf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func tanh(_ x: Float) -> Float {
|
||||
libm_tanhf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func acosh(_ x: Float) -> Float {
|
||||
libm_acoshf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func asinh(_ x: Float) -> Float {
|
||||
libm_asinhf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atanh(_ x: Float) -> Float {
|
||||
libm_atanhf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func exp(_ x: Float) -> Float {
|
||||
libm_expf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func expMinusOne(_ x: Float) -> Float {
|
||||
libm_expm1f(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log(_ x: Float) -> Float {
|
||||
libm_logf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log(onePlus x: Float) -> Float {
|
||||
libm_log1pf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func erf(_ x: Float) -> Float {
|
||||
libm_erff(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func erfc(_ x: Float) -> Float {
|
||||
libm_erfcf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func exp2(_ x: Float) -> Float {
|
||||
libm_exp2f(x)
|
||||
}
|
||||
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
@_transparent
|
||||
public static func exp10(_ x: Float) -> Float {
|
||||
libm_exp10f(x)
|
||||
}
|
||||
#endif
|
||||
|
||||
@_transparent
|
||||
public static func hypot(_ x: Float, _ y: Float) -> Float {
|
||||
libm_hypotf(x, y)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func gamma(_ x: Float) -> Float {
|
||||
libm_tgammaf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log2(_ x: Float) -> Float {
|
||||
libm_log2f(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log10(_ x: Float) -> Float {
|
||||
libm_log10f(x)
|
||||
}
|
||||
|
||||
@_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)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func pow(_ x: Float, _ n: Int) -> Float {
|
||||
// If n is exactly representable as Float, we can just call powf:
|
||||
if let y = Float(exactly: n) {
|
||||
return libm_powf(x, y)
|
||||
}
|
||||
// Otherwise, n is too large to losslessly represent as Float.
|
||||
// The range of "interesting" n is -1488522191 ... 1744361944; outside
|
||||
// of this range, all x != 1 overflow or underflow, so only the parity
|
||||
// of x matters. We don't really care about the specific range at all,
|
||||
// only that the bounds fit exactly into two Floats.
|
||||
//
|
||||
// We do, however, need to be careful that high and low both have the
|
||||
// same sign as n (consult the Double implementation for details of why
|
||||
// this matters), so we need to be a little bit careful constructing
|
||||
// them.
|
||||
//
|
||||
// Unlike the Double implementation, when n is very large, high will
|
||||
// get rounded here; that's OK because it does not change the sign or
|
||||
// parity, which are the only two bits that matter for such large
|
||||
// exponents in Float.
|
||||
let mask = Int(truncatingIfNeeded: 0xffffff)
|
||||
let round = n < 0 ? mask : 0
|
||||
let high = (n &+ round) & ~mask
|
||||
let low = n &- high
|
||||
return libm_powf(x, Float(low)) * libm_powf(x, Float(high))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func root(_ x: Float, _ n: Int) -> Float {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// Workaround the issue mentioned below for the specific case of n = 3
|
||||
// where we can fallback on cbrt.
|
||||
if n == 3 { return libm_cbrtf(x) }
|
||||
// TODO: this implementation is not quite correct, because either n or
|
||||
// 1/n may be not be representable as Float.
|
||||
return Float(signOf: x, magnitudeOf: libm_powf(x.magnitude, 1/Float(n)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atan2(y: Float, x: Float) -> Float {
|
||||
libm_atan2f(y, x)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_transparent
|
||||
public static func logGamma(_ x: Float) -> Float {
|
||||
var dontCare: Int32 = 0
|
||||
return libm_lgammaf(x, &dontCare)
|
||||
}
|
||||
#endif
|
||||
|
||||
@_transparent
|
||||
public static func _mulAdd(_ a: Float, _ b: Float, _ c: Float) -> Float {
|
||||
_numerics_muladdf(a, b, c)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
//===--- Float16+Real.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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import _NumericsShims
|
||||
|
||||
// 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 {
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -0,0 +1,169 @@
|
||||
//===--- Float80+Real.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 _NumericsShims
|
||||
|
||||
// Restrict extension to platforms for which Float80 exists.
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
extension Float80: Real {
|
||||
@_transparent
|
||||
public static func cos(_ x: Float80) -> Float80 {
|
||||
libm_cosl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sin(_ x: Float80) -> Float80 {
|
||||
libm_sinl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func tan(_ x: Float80) -> Float80 {
|
||||
libm_tanl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func acos(_ x: Float80) -> Float80 {
|
||||
libm_acosl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func asin(_ x: Float80) -> Float80 {
|
||||
libm_asinl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atan(_ x: Float80) -> Float80 {
|
||||
libm_atanl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func cosh(_ x: Float80) -> Float80 {
|
||||
libm_coshl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sinh(_ x: Float80) -> Float80 {
|
||||
libm_sinhl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func tanh(_ x: Float80) -> Float80 {
|
||||
libm_tanhl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func acosh(_ x: Float80) -> Float80 {
|
||||
libm_acoshl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func asinh(_ x: Float80) -> Float80 {
|
||||
libm_asinhl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atanh(_ x: Float80) -> Float80 {
|
||||
libm_atanhl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func exp(_ x: Float80) -> Float80 {
|
||||
libm_expl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func expMinusOne(_ x: Float80) -> Float80 {
|
||||
libm_expm1l(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log(_ x: Float80) -> Float80 {
|
||||
libm_logl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log(onePlus x: Float80) -> Float80 {
|
||||
libm_log1pl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func erf(_ x: Float80) -> Float80 {
|
||||
libm_erfl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func erfc(_ x: Float80) -> Float80 {
|
||||
libm_erfcl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func exp2(_ x: Float80) -> Float80 {
|
||||
libm_exp2l(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func hypot(_ x: Float80, _ y: Float80) -> Float80 {
|
||||
libm_hypotl(x, y)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func gamma(_ x: Float80) -> Float80 {
|
||||
libm_tgammal(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log2(_ x: Float80) -> Float80 {
|
||||
libm_log2l(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log10(_ x: Float80) -> Float80 {
|
||||
libm_log10l(x)
|
||||
}
|
||||
|
||||
@_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)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func pow(_ x: Float80, _ n: Int) -> Float80 {
|
||||
// Every Int value is exactly representable as Float80, so we don't need
|
||||
// to do anything fancy--unlike Float and Double, we can just call the
|
||||
// libm pow function.
|
||||
libm_powl(x, Float80(n))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func root(_ x: Float80, _ n: Int) -> Float80 {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// Workaround the issue mentioned below for the specific case of n = 3
|
||||
// where we can fallback on cbrt.
|
||||
if n == 3 { return libm_cbrtl(x) }
|
||||
// TODO: this implementation is not quite correct, because either n or
|
||||
// 1/n may be not be representable as Float80.
|
||||
return Float80(signOf: x, magnitudeOf: libm_powl(x.magnitude, 1/Float80(n)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atan2(y: Float80, x: Float80) -> Float80 {
|
||||
libm_atan2l(y, x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func logGamma(_ x: Float80) -> Float80 {
|
||||
var dontCare: Int32 = 0
|
||||
return libm_lgammal(x, &dontCare)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,12 +1,12 @@
|
||||
# Real
|
||||
# Real Module
|
||||
|
||||
[SE-0246] proposed an API for "basic math functions" that would make operations like sine and logarithm available in generic contexts.
|
||||
It was accepted, but because of limitations in the compiler, the API could not be added to the standard library in a source-stable manner.
|
||||
The `Real` module provides that API as a separate module so that you can use it right away to get access to the improved API for these operations in your projects.
|
||||
`RealModule` provides that API as a separate module so that you can use it right away to get access to the improved API for these operations in your projects.
|
||||
|
||||
## Protocols and Methods
|
||||
|
||||
The module defines three protocols. The most general is `ElementaryFunctions`, which makes the following functions available:
|
||||
The module defines four protocols. The most general is `ElementaryFunctions`, which makes the following functions available:
|
||||
- Exponential functions: `exp`, `expMinusOne`
|
||||
- Logarithmic functions: `log`, `log(onePlus:)`
|
||||
- Trigonometric functions: `cos`, `sin`, `tan`
|
||||
@@ -28,9 +28,13 @@ The `RealFunctions` protocol refines `ElementaryFunctions`, and adds operations
|
||||
The protocol that you will use most often is `Real`, which describes a floating-point type equipped with the full set of basic math functions.
|
||||
This is a great protocol to use in writing generic code, because it has all the basics that you need to implement most numeric functions.
|
||||
|
||||
The fourth protocol is `AlgebraicField`, which `Real` also refines.
|
||||
This protocol is a very small refinement of `SignedNumeric`, adding the `/` and `/=` operators and a `reciprocal` property.
|
||||
The primary use of this protocol is for writing code that is generic over real and complex types.
|
||||
|
||||
## Using Real
|
||||
|
||||
First, either import `Real` directly or import the `Numerics` umbrella module.
|
||||
First, either import `RealModule` directly or import the `Numerics` umbrella module.
|
||||
|
||||
Suppose we were experimenting with some basic machine learning, and needed a generic [sigmoid function][Sigmoid] activation function:
|
||||
|
||||
@@ -65,8 +69,9 @@ When new basic floating-point types are added to Swift, like `Float16` or `Float
|
||||
Not having this protocol is a significant missing feature for numerical computing in Swift, and I'm really looking forward to seeing what people do with it.
|
||||
|
||||
### Dependencies:
|
||||
- The C standard math library (`libm`) via the `NumericShims` target.
|
||||
- The C standard math library (`libm`) via the `_NumericsShims` target.
|
||||
|
||||
[ErrorFunction]: https://en.wikipedia.org/wiki/Error_function
|
||||
[GammaFunction]: https://en.wikipedia.org/wiki/Gamma_function
|
||||
[SE-0246]: https://github.com/apple/swift-evolution/blob/master/proposals/0246-mathable.md
|
||||
[SE-0246]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0246-mathable.md
|
||||
[Sigmoid]: https://en.wikipedia.org/wiki/Sigmoid_function
|
||||
@@ -0,0 +1,157 @@
|
||||
//===--- Real.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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// 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 implementation of a sigmoid
|
||||
/// function:
|
||||
/// ```
|
||||
/// func sigmoid<T: Real>(_ x: T) -> T {
|
||||
/// return 1/(1 + .exp(-x))
|
||||
/// }
|
||||
/// ```
|
||||
/// See Also:
|
||||
/// -
|
||||
/// - `ElementaryFunctions`
|
||||
/// - `RealFunctions`
|
||||
/// - `AlgebraicField`
|
||||
public protocol Real: FloatingPoint, RealFunctions, AlgebraicField {
|
||||
}
|
||||
|
||||
// While `Real` does not provide any additional customization points,
|
||||
// it does allow us to default the implementation of a few operations,
|
||||
// and also provides `signGamma`.
|
||||
extension Real {
|
||||
// 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)
|
||||
}
|
||||
|
||||
/// cos(x) - 1, computed in such a way as to maintain accuracy for small x.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `ElementaryFunctions.expMinusOne()`
|
||||
@_transparent
|
||||
public static func cosMinusOne(_ x: Self) -> Self {
|
||||
let sinxOver2 = sin(x/2)
|
||||
return -2*sinxOver2*sinxOver2
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
public static func signGamma(_ x: Self) -> FloatingPointSign {
|
||||
// Gamma is strictly positive for x >= 0.
|
||||
if x >= 0 { return .plus }
|
||||
// For negative x, we arbitrarily choose to assign a sign of .plus to the
|
||||
// poles.
|
||||
let trunc = x.rounded(.towardZero)
|
||||
if x == trunc { return .plus }
|
||||
// Otherwise, signGamma is .minus if the integral part of x is even.
|
||||
return trunc.isEven ? .minus : .plus
|
||||
}
|
||||
|
||||
// Determines if this value is even, assuming that it is an integer.
|
||||
@inline(__always)
|
||||
private var isEven: Bool {
|
||||
if Self.radix == 2 {
|
||||
// For binary types, we can just check if x/2 is an integer. This works
|
||||
// because x/2 is always computed exactly.
|
||||
let half = self/2
|
||||
return half == half.rounded(.towardZero)
|
||||
} else {
|
||||
// For decimal types, it's not quite that simple, because x/2 is not
|
||||
// necessarily computed exactly. As an example, suppose that we had a
|
||||
// decimal type with a one digit significand, and self = 7. Then self/2
|
||||
// would round to 4, and we would (wrongly) conclude that it was an
|
||||
// integer, and hence that self was even.
|
||||
//
|
||||
// Instead, for decimal types, we check if 2*trunc(self/2) == self,
|
||||
// using an FMA; this is always correct; this approach works for any
|
||||
// radix, but the previous method is more efficient for radix == 2.
|
||||
let half = self/2
|
||||
return self.addingProduct(-2, half.rounded(.towardZero)) == 0
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@_transparent
|
||||
public static func _mulAdd(_ a: Self, _ b: Self, _ c: Self) -> Self {
|
||||
a*b + c
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sqrt(_ x: Self) -> Self {
|
||||
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
|
||||
if recip.isNormal || isZero || !isFinite {
|
||||
return recip
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
///
|
||||
@@ -112,4 +113,9 @@ public protocol RealFunctions: ElementaryFunctions {
|
||||
/// - `logGamma()`
|
||||
static func signGamma(_ x: Self) -> FloatingPointSign
|
||||
#endif
|
||||
|
||||
/// a*b + c, computed _either_ with an FMA or with separate multiply and add.
|
||||
///
|
||||
/// Whichever is faster should be chosen by the compiler statically.
|
||||
static func _mulAdd(_ a: Self, _ b: Self, _ c: Self) -> Self
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#[[
|
||||
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
|
||||
#]]
|
||||
|
||||
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)
|
||||
File renamed without changes.
@@ -16,4 +16,4 @@
|
||||
// If any shims are added that are not pure header inlines, whatever runtime
|
||||
// support they require can be added to this file.
|
||||
|
||||
#include "NumericsShims.h"
|
||||
#include "_NumericsShims.h"
|
||||
+36
-20
@@ -2,17 +2,35 @@
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define HEADER_SHIM static inline __attribute__((__always_inline__))
|
||||
|
||||
// MARK: - math functions for float
|
||||
// This header uses most of the libm functions, but we don't want to end up
|
||||
// exporting the libm declarations to modules that include NumericsShims, so
|
||||
// we don't want to actually #include <math.h>.
|
||||
//
|
||||
// For most of the functions, we can get around this by using __builtin_func
|
||||
// instead of func, since the compiler knows about these operations, but for
|
||||
// the non-standard extensions, we need to include our own declarations. This
|
||||
// is a little bit risky, in that we might end up missing an attribute that
|
||||
// gets added and effects calling conventions, etc, but that's expected to be
|
||||
// exceedingly rare.
|
||||
//
|
||||
// Still, we'll eventually want to find a better solution to this problem,
|
||||
// especially if people start using this package on systems that are not
|
||||
// Darwin or Ubuntu.
|
||||
|
||||
// MARK: - math functions for float
|
||||
HEADER_SHIM float libm_cosf(float x) {
|
||||
return __builtin_cosf(x);
|
||||
}
|
||||
@@ -131,9 +149,7 @@ HEADER_SHIM float libm_log10f(float x) {
|
||||
|
||||
#if !defined _WIN32
|
||||
HEADER_SHIM float libm_lgammaf(float x, int *signp) {
|
||||
#if __APPLE__
|
||||
extern float lgammaf_r(float, int *);
|
||||
#endif
|
||||
return lgammaf_r(x, signp);
|
||||
}
|
||||
#endif
|
||||
@@ -253,9 +269,7 @@ HEADER_SHIM double libm_log10(double x) {
|
||||
|
||||
#if !defined _WIN32
|
||||
HEADER_SHIM double libm_lgamma(double x, int *signp) {
|
||||
#if __APPLE__
|
||||
extern double lgamma_r(double, int *);
|
||||
#endif
|
||||
return lgamma_r(x, signp);
|
||||
}
|
||||
#endif
|
||||
@@ -372,20 +386,22 @@ HEADER_SHIM long double libm_lgammal(long double x, int *signp) {
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - shims to import C complex operations for timing purposes
|
||||
|
||||
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 };
|
||||
// MARK: - fast mul-add inlines
|
||||
/// a*b + c evaluated _either_ as two operations or fma, whichever is faster.
|
||||
HEADER_SHIM float _numerics_muladdf(float a, float b, float c) {
|
||||
#pragma STDC FP_CONTRACT ON
|
||||
return a*b + c;
|
||||
}
|
||||
|
||||
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 };
|
||||
/// a*b + c evaluated _either_ as two operations or fma, whichever is faster.
|
||||
HEADER_SHIM double _numerics_muladd(double a, double b, double c) {
|
||||
#pragma STDC FP_CONTRACT ON
|
||||
return a*b + c;
|
||||
}
|
||||
|
||||
// No long-double muladd operation, because no one has built an FMA for it
|
||||
// (except for Itanium, which Swift doesn't support).
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,3 @@
|
||||
module _NumericsShims {
|
||||
header "_NumericsShims.h"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#[[
|
||||
This source file is part of the Swift Numerics open source project
|
||||
|
||||
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
|
||||
#]]
|
||||
|
||||
add_library(_TestSupport
|
||||
Error.swift
|
||||
Interval.swift
|
||||
RealTestSupport.swift)
|
||||
set_target_properties(_TestSupport PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
target_link_libraries(_TestSupport PUBLIC
|
||||
Numerics)
|
||||
|
||||
|
||||
_install_target(_TestSupport)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_NUMERICS_EXPORTS _TestSupport)
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
//===--- RealTestSupport.swift --------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// 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 RealModule
|
||||
|
||||
public protocol FixedWidthFloatingPoint: BinaryFloatingPoint
|
||||
where Exponent: FixedWidthInteger,
|
||||
RawSignificand: FixedWidthInteger { }
|
||||
|
||||
#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
|
||||
|
||||
extension Float: FixedWidthFloatingPoint { }
|
||||
extension Double: FixedWidthFloatingPoint { }
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
extension Float80: FixedWidthFloatingPoint { }
|
||||
#endif
|
||||
|
||||
extension FloatingPointSign {
|
||||
static func random<G: RandomNumberGenerator>(using g: inout G) -> FloatingPointSign {
|
||||
[.plus,.minus].randomElement(using: &g)!
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
//===--- ApproximateEqualityTests.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 XCTest
|
||||
|
||||
final class ApproximateEqualityTests: XCTestCase {
|
||||
|
||||
func testSpecials<T: Real>(absolute tol: T) {
|
||||
let zero = Complex<T>.zero
|
||||
let inf = Complex<T>.infinity
|
||||
XCTAssertTrue(zero.isApproximatelyEqual(to: zero, absoluteTolerance: tol))
|
||||
XCTAssertTrue(zero.isApproximatelyEqual(to:-zero, absoluteTolerance: tol))
|
||||
XCTAssertTrue((-zero).isApproximatelyEqual(to: zero, absoluteTolerance: tol))
|
||||
XCTAssertTrue((-zero).isApproximatelyEqual(to:-zero, absoluteTolerance: tol))
|
||||
// Complex has a single point at infinity.
|
||||
XCTAssertTrue(inf.isApproximatelyEqual(to: inf, absoluteTolerance: tol))
|
||||
XCTAssertTrue(inf.isApproximatelyEqual(to:-inf, absoluteTolerance: tol))
|
||||
XCTAssertTrue((-inf).isApproximatelyEqual(to: inf, absoluteTolerance: tol))
|
||||
XCTAssertTrue((-inf).isApproximatelyEqual(to:-inf, absoluteTolerance: tol))
|
||||
}
|
||||
|
||||
func testSpecials<T: Real>(relative tol: T) {
|
||||
let zero = Complex<T>.zero
|
||||
let inf = Complex<T>.infinity
|
||||
XCTAssertTrue(zero.isApproximatelyEqual(to: zero, relativeTolerance: tol))
|
||||
XCTAssertTrue(zero.isApproximatelyEqual(to:-zero, relativeTolerance: tol))
|
||||
XCTAssertTrue((-zero).isApproximatelyEqual(to: zero, relativeTolerance: tol))
|
||||
XCTAssertTrue((-zero).isApproximatelyEqual(to:-zero, relativeTolerance: tol))
|
||||
// Complex has a single point at infinity.
|
||||
XCTAssertTrue(inf.isApproximatelyEqual(to: inf, relativeTolerance: tol))
|
||||
XCTAssertTrue(inf.isApproximatelyEqual(to:-inf, relativeTolerance: tol))
|
||||
XCTAssertTrue((-inf).isApproximatelyEqual(to: inf, relativeTolerance: tol))
|
||||
XCTAssertTrue((-inf).isApproximatelyEqual(to:-inf, relativeTolerance: tol))
|
||||
}
|
||||
|
||||
func testSpecials<T: Real>(_ type: T.Type) {
|
||||
XCTAssertTrue(Complex<T>.zero.isApproximatelyEqual(to: .zero))
|
||||
XCTAssertTrue(Complex<T>.zero.isApproximatelyEqual(to:-.zero))
|
||||
testSpecials(absolute: T.zero)
|
||||
testSpecials(absolute: T.greatestFiniteMagnitude)
|
||||
testSpecials(relative: T.ulpOfOne)
|
||||
testSpecials(relative: T(1))
|
||||
}
|
||||
|
||||
func testFloat() {
|
||||
testSpecials(Float.self)
|
||||
}
|
||||
|
||||
func testDouble() {
|
||||
testSpecials(Double.self)
|
||||
}
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
func testFloat80() {
|
||||
testSpecials(Float80.self)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
//===--- ArithmeticBenchmarkTests.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 XCTest
|
||||
import Complex
|
||||
|
||||
// For CComplex and shims
|
||||
import NumericsShims
|
||||
|
||||
extension Complex where RealType == Double {
|
||||
@_transparent
|
||||
init(_ other: CComplex) {
|
||||
self = unsafeBitCast(other, to: Complex<Double>.self)
|
||||
}
|
||||
@_transparent
|
||||
var ctype: CComplex {
|
||||
unsafeBitCast(self, to: CComplex.self)
|
||||
}
|
||||
}
|
||||
|
||||
let wellScaledDoubles: [Complex<Double>] = (0 ..< 1024).map { _ in
|
||||
Complex(length: Double.random(in: 0.5 ..< 2.0),
|
||||
phase: Double.random(in: -.pi ..< .pi))
|
||||
}
|
||||
|
||||
let poorlyScaledDoubles: [Complex<Double>] = (0 ..< 1024).map { _ in
|
||||
Complex(
|
||||
length: Double(sign: .plus,
|
||||
exponent: .random(in: -970 ... 1023),
|
||||
significand: .random(in: 1 ..< 2)),
|
||||
phase: Double.random(in: -.pi ..< .pi)
|
||||
)
|
||||
}
|
||||
|
||||
final class ArithmeticBenchmarkTests: XCTestCase {
|
||||
|
||||
let iters = 1000
|
||||
|
||||
func testDivisionByConstant() {
|
||||
let divisor = wellScaledDoubles[0]
|
||||
var sum = Complex<Double>.zero
|
||||
measure {
|
||||
for _ in 0 ..< iters {
|
||||
sum = wellScaledDoubles.reduce(into: sum) { $0 += $1 / divisor }
|
||||
}
|
||||
}
|
||||
print(sum)
|
||||
}
|
||||
|
||||
func testReciprocal() {
|
||||
let recip = wellScaledDoubles[0].reciprocal!
|
||||
var sum = Complex<Double>.zero
|
||||
measure {
|
||||
for _ in 0 ..< iters {
|
||||
sum = wellScaledDoubles.reduce(into: sum) { $0 += $1 * recip }
|
||||
}
|
||||
}
|
||||
print(sum)
|
||||
}
|
||||
|
||||
func testDivisionByConstantC() {
|
||||
let divisor = wellScaledDoubles[0].ctype
|
||||
var sum = Complex<Double>.zero
|
||||
measure {
|
||||
for _ in 0 ..< iters {
|
||||
sum = wellScaledDoubles.reduce(into: sum) {
|
||||
$0 += Complex(libm_cdiv($1.ctype, divisor))
|
||||
}
|
||||
}
|
||||
}
|
||||
print(sum)
|
||||
}
|
||||
|
||||
func testMultiplication() {
|
||||
let multiplicand = wellScaledDoubles[0]
|
||||
var sum = Complex<Double>.zero
|
||||
measure {
|
||||
for _ in 0 ..< iters {
|
||||
sum = wellScaledDoubles.reduce(into: sum) { $0 += $1 * multiplicand }
|
||||
}
|
||||
}
|
||||
print(sum)
|
||||
}
|
||||
|
||||
func testMultiplicationC() {
|
||||
let multiplicand = wellScaledDoubles[0].ctype
|
||||
var sum = Complex<Double>.zero
|
||||
measure {
|
||||
for _ in 0 ..< iters {
|
||||
sum = wellScaledDoubles.reduce(into: sum) {
|
||||
$0 += Complex(libm_cmul($1.ctype, multiplicand))
|
||||
}
|
||||
}
|
||||
}
|
||||
print(sum)
|
||||
}
|
||||
|
||||
func testDivision() {
|
||||
var sum = Complex<Double>.zero
|
||||
measure {
|
||||
for o in 0 ..< iters {
|
||||
for i in 0 ..< 1024 {
|
||||
sum += wellScaledDoubles[i] / wellScaledDoubles[(i &- o) & 1023]
|
||||
}
|
||||
}
|
||||
}
|
||||
print(sum)
|
||||
}
|
||||
|
||||
func testDivisionC() {
|
||||
var sum = Complex<Double>.zero
|
||||
measure {
|
||||
for o in 0 ..< iters {
|
||||
for i in 0 ..< 1024 {
|
||||
sum += Complex(libm_cdiv(wellScaledDoubles[i].ctype,
|
||||
wellScaledDoubles[(i &- o) & 1023].ctype))
|
||||
}
|
||||
}
|
||||
}
|
||||
print(sum)
|
||||
}
|
||||
|
||||
func testDivisionPoorScaling() {
|
||||
var sum = Complex<Double>.zero
|
||||
measure {
|
||||
for o in 0 ..< iters {
|
||||
for i in 0 ..< 1024 {
|
||||
sum += poorlyScaledDoubles[i] / poorlyScaledDoubles[(i &- o) & 1023]
|
||||
}
|
||||
}
|
||||
}
|
||||
print(sum)
|
||||
}
|
||||
|
||||
func testDivisionPoorScalingC() {
|
||||
var sum = Complex<Double>.zero
|
||||
measure {
|
||||
for o in 0 ..< iters {
|
||||
for i in 0 ..< 1024 {
|
||||
sum += Complex(libm_cdiv(poorlyScaledDoubles[i].ctype,
|
||||
poorlyScaledDoubles[(i &- o) & 1023].ctype))
|
||||
}
|
||||
}
|
||||
}
|
||||
print(sum)
|
||||
}
|
||||
|
||||
func testMultiplicationPoorScaling() {
|
||||
var sum = Complex<Double>.zero
|
||||
measure {
|
||||
for o in 0 ..< iters {
|
||||
for i in 0 ..< 1024 {
|
||||
sum += poorlyScaledDoubles[i] * poorlyScaledDoubles[(i &- o) & 1023]
|
||||
}
|
||||
}
|
||||
}
|
||||
print(sum)
|
||||
}
|
||||
|
||||
func testMultiplicationPoorScalingC() {
|
||||
var sum = Complex<Double>.zero
|
||||
measure {
|
||||
for o in 0 ..< iters {
|
||||
for i in 0 ..< 1024 {
|
||||
sum += Complex(libm_cmul(poorlyScaledDoubles[i].ctype,
|
||||
poorlyScaledDoubles[(i &- o) & 1023].ctype))
|
||||
}
|
||||
}
|
||||
}
|
||||
print(sum)
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,8 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Complex
|
||||
import Real
|
||||
import ComplexModule
|
||||
import RealModule
|
||||
|
||||
// TODO: improve this to be a general-purpose complex comparison with tolerance
|
||||
func relativeError<T>(_ a: Complex<T>, _ b: Complex<T>) -> T {
|
||||
@@ -165,12 +165,10 @@ final class ArithmeticTests: XCTestCase {
|
||||
let a: Complex<Double>
|
||||
let b: Complex<Double>
|
||||
let c: Complex<Double>
|
||||
let allowSmallError: Bool
|
||||
init(_ a: Complex<Double>, _ b: Complex<Double>, _ c: Complex<Double>, allowSmallError: Bool = false) {
|
||||
init(_ a: Complex<Double>, _ b: Complex<Double>, _ c: Complex<Double>) {
|
||||
self.a = a
|
||||
self.b = b
|
||||
self.c = c
|
||||
self.allowSmallError = allowSmallError
|
||||
}
|
||||
}
|
||||
// The ten test cases from Baudin & Smith's paper. These only apply to
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
#[[
|
||||
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
|
||||
#]]
|
||||
|
||||
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})
|
||||
target_compile_options(ComplexTests PRIVATE
|
||||
-enable-testing)
|
||||
target_link_libraries(ComplexTests PUBLIC
|
||||
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
|
||||
ComplexModule
|
||||
Numerics
|
||||
_TestSupport
|
||||
XCTest)
|
||||
@@ -0,0 +1,74 @@
|
||||
//===--- DifferentiableTests.swift ----------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if swift(>=5.3) && canImport(_Differentiation)
|
||||
|
||||
import XCTest
|
||||
import ComplexModule
|
||||
import _Differentiation
|
||||
|
||||
final class DifferentiableTests: XCTestCase {
|
||||
func testComponentGetter() {
|
||||
XCTAssertEqual(
|
||||
gradient(at: Complex<Float>(5, 5)) { $0.real * 2 },
|
||||
Complex(2, 0))
|
||||
XCTAssertEqual(
|
||||
gradient(at: Complex<Float>(5, 5)) { $0.imaginary * 2 },
|
||||
Complex(0, 2))
|
||||
XCTAssertEqual(
|
||||
gradient(at: Complex<Float>(5, 5)) { $0.real * 5 + $0.imaginary * 2 },
|
||||
Complex(5, 2))
|
||||
}
|
||||
|
||||
func testInitializer() {
|
||||
let φ1 = pullback(at: 4, -3) { r, i in Complex<Float>(r, i) }
|
||||
let tan1 = φ1(Complex(-1, 2))
|
||||
XCTAssertEqual(tan1.0, -1)
|
||||
XCTAssertEqual(tan1.1, 2)
|
||||
|
||||
let φ2 = pullback(at: 4, -3) { r, i in Complex<Float>(r * r, i + i) }
|
||||
let tan2 = φ2(Complex(-1, 1))
|
||||
XCTAssertEqual(tan2.0, -8)
|
||||
XCTAssertEqual(tan2.1, 2)
|
||||
}
|
||||
|
||||
func testConjugate() {
|
||||
let φ = pullback(at: Complex<Float>(20, -4)) { x in x.conjugate }
|
||||
XCTAssertEqual(φ(Complex(1, 0)), Complex(1, 0))
|
||||
XCTAssertEqual(φ(Complex(0, 1)), Complex(0, -1))
|
||||
XCTAssertEqual(φ(Complex(-1, 1)), Complex(-1, -1))
|
||||
}
|
||||
|
||||
func testArithmetics() {
|
||||
let φAdd = pullback(at: Complex<Float>(2, 3)) { x in
|
||||
x + Complex(5, 6)
|
||||
}
|
||||
XCTAssertEqual(φAdd(Complex(1, 1)), Complex(1, 1))
|
||||
|
||||
let φSubtract = pullback(at: Complex<Float>(2, 3)) { x in
|
||||
Complex(5, 6) - x
|
||||
}
|
||||
XCTAssertEqual(φSubtract(Complex(1, 1)), Complex(-1, -1))
|
||||
|
||||
let φMultiply = pullback(at: Complex<Float>(2, 3)) { x in x * x }
|
||||
XCTAssertEqual(φMultiply(Complex(1, 0)), Complex(4, 6))
|
||||
XCTAssertEqual(φMultiply(Complex(0, 1)), Complex(-6, 4))
|
||||
XCTAssertEqual(φMultiply(Complex(1, 1)), Complex(-2, 10))
|
||||
|
||||
let φDivide = pullback(at: Complex<Float>(20, -4)) { x in
|
||||
x / Complex(2, 2)
|
||||
}
|
||||
XCTAssertEqual(φDivide(Complex(1, 0)), Complex(0.25, -0.25))
|
||||
XCTAssertEqual(φDivide(Complex(0, 1)), Complex(0.25, 0.25))
|
||||
}
|
||||
}
|
||||
|
||||
#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
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// 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
|
||||
@@ -10,8 +10,8 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Complex
|
||||
import Real
|
||||
import ComplexModule
|
||||
import RealModule
|
||||
|
||||
final class PropertyTests: XCTestCase {
|
||||
|
||||
@@ -102,4 +102,31 @@ final class PropertyTests: XCTestCase {
|
||||
testEquatableHashable(Float80.self)
|
||||
#endif
|
||||
}
|
||||
|
||||
func testCodable<T: Codable & Real>(_ type: T.Type) throws {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.nonConformingFloatEncodingStrategy = .convertToString(
|
||||
positiveInfinity: "inf",
|
||||
negativeInfinity: "-inf",
|
||||
nan: "nan")
|
||||
|
||||
let decoder = JSONDecoder()
|
||||
decoder.nonConformingFloatDecodingStrategy = .convertFromString(
|
||||
positiveInfinity: "inf",
|
||||
negativeInfinity: "-inf",
|
||||
nan: "nan")
|
||||
|
||||
for expected: Complex<T> in [.zero, .one, .i, .infinity] {
|
||||
let data = try encoder.encode(expected)
|
||||
// print("*** \(String(decoding: data, as: Unicode.UTF8.self)) ***")
|
||||
let actual = try decoder.decode(Complex<T>.self, from: data)
|
||||
XCTAssertEqual(actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func testCodable() throws {
|
||||
try testCodable(Float32.self)
|
||||
try testCodable(Float64.self)
|
||||
// Float80 doesn't conform to Codable.
|
||||
}
|
||||
}
|
||||
@@ -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.")
|
||||
@@ -0,0 +1,145 @@
|
||||
//===--- ApproximateEqualityTests.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 XCTest
|
||||
import _TestSupport
|
||||
|
||||
final class ApproximateEqualityTests: XCTestCase {
|
||||
|
||||
func testSpecials<T: Real>(absolute tol: T) {
|
||||
let zero = T.zero
|
||||
let gfm = T.greatestFiniteMagnitude
|
||||
let inf = T.infinity
|
||||
let nan = T.nan
|
||||
XCTAssertTrue(zero.isApproximatelyEqual(to: zero, absoluteTolerance: tol))
|
||||
XCTAssertTrue(zero.isApproximatelyEqual(to:-zero, absoluteTolerance: tol))
|
||||
XCTAssertFalse(inf.isApproximatelyEqual(to: gfm, absoluteTolerance: tol))
|
||||
XCTAssertFalse(gfm.isApproximatelyEqual(to: inf, absoluteTolerance: tol))
|
||||
XCTAssertTrue(inf.isApproximatelyEqual(to: inf, absoluteTolerance: tol))
|
||||
XCTAssertTrue(inf.isApproximatelyEqual(to: inf, absoluteTolerance: tol))
|
||||
XCTAssertFalse(nan.isApproximatelyEqual(to: nan, absoluteTolerance: tol))
|
||||
}
|
||||
|
||||
func testSpecials<T: Real>(relative tol: T) {
|
||||
let zero = T.zero
|
||||
let gfm = T.greatestFiniteMagnitude
|
||||
let inf = T.infinity
|
||||
let nan = T.nan
|
||||
XCTAssertTrue(zero.isApproximatelyEqual(to: zero, relativeTolerance: tol))
|
||||
XCTAssertTrue(zero.isApproximatelyEqual(to:-zero, relativeTolerance: tol))
|
||||
XCTAssertFalse(inf.isApproximatelyEqual(to: gfm, relativeTolerance: tol))
|
||||
XCTAssertFalse(gfm.isApproximatelyEqual(to: inf, relativeTolerance: tol))
|
||||
XCTAssertTrue(inf.isApproximatelyEqual(to: inf, relativeTolerance: tol))
|
||||
XCTAssertTrue(inf.isApproximatelyEqual(to: inf, relativeTolerance: tol))
|
||||
XCTAssertFalse(nan.isApproximatelyEqual(to: nan, relativeTolerance: tol))
|
||||
}
|
||||
|
||||
func testSpecials<T: Real>(_ type: T.Type) {
|
||||
XCTAssertTrue(T.zero.isApproximatelyEqual(to: .zero))
|
||||
XCTAssertTrue(T.zero.isApproximatelyEqual(to:-.zero))
|
||||
testSpecials(absolute: T.zero)
|
||||
testSpecials(absolute: T.leastNormalMagnitude)
|
||||
testSpecials(absolute: T.greatestFiniteMagnitude)
|
||||
testSpecials(relative: T.zero)
|
||||
testSpecials(relative: T.ulpOfOne)
|
||||
testSpecials(relative: T(1).nextDown)
|
||||
testSpecials(relative: T(1))
|
||||
}
|
||||
|
||||
func testDefaults<T: Real>(_ type: T.Type) {
|
||||
let e = T.ulpOfOne.squareRoot()
|
||||
XCTAssertTrue(T(1).isApproximatelyEqual(to: 1 + e))
|
||||
XCTAssertTrue(T(1).isApproximatelyEqual(to: 1 - e/2))
|
||||
XCTAssertFalse(T(1).isApproximatelyEqual(to: 1 + 2*e))
|
||||
XCTAssertFalse(T(1).isApproximatelyEqual(to: 1 - 3*e/2))
|
||||
}
|
||||
|
||||
func testRandom<T>(_ type: T.Type) where T: FixedWidthFloatingPoint & Real {
|
||||
var g = SystemRandomNumberGenerator()
|
||||
// Generate a bunch of random values in a small interval and a tolerance
|
||||
// and use them to check that various properties that we would like to
|
||||
// hold actually do.
|
||||
var x = [1] + (0 ..< 64).map {
|
||||
_ in T.random(in: 1 ..< 2, using: &g)
|
||||
} + [2]
|
||||
x.sort()
|
||||
// We have 66 values in 1 ... 2, so if we use a tolerance of around 1/64,
|
||||
// at least some of the pairs will compare equal with tolerance.
|
||||
let tol = T.random(in: 1/64 ... 1/32, using: &g)
|
||||
// We're going to walk the values in order, validating that some common-
|
||||
// sense properties hold.
|
||||
for i in x.indices {
|
||||
// reflexivity
|
||||
XCTAssertTrue(x[i].isApproximatelyEqual(to: x[i]))
|
||||
XCTAssertTrue(x[i].isApproximatelyEqual(to: x[i], relativeTolerance: tol))
|
||||
XCTAssertTrue(x[i].isApproximatelyEqual(to: x[i], absoluteTolerance: tol))
|
||||
for j in i ..< x.endIndex {
|
||||
// commutativity
|
||||
XCTAssertTrue(
|
||||
x[i].isApproximatelyEqual(to: x[j], relativeTolerance: tol) ==
|
||||
x[j].isApproximatelyEqual(to: x[i], relativeTolerance: tol)
|
||||
)
|
||||
XCTAssertTrue(
|
||||
x[i].isApproximatelyEqual(to: x[j], absoluteTolerance: tol) ==
|
||||
x[j].isApproximatelyEqual(to: x[i], absoluteTolerance: tol)
|
||||
)
|
||||
// scale invariance for relative comparisons
|
||||
let scale = T(
|
||||
sign:.plus,
|
||||
exponent: T.Exponent.random(in: T.leastNormalMagnitude.exponent ..< T.greatestFiniteMagnitude.exponent),
|
||||
significand: 1
|
||||
)
|
||||
XCTAssertTrue(
|
||||
x[i].isApproximatelyEqual(to: x[j], relativeTolerance: tol) ==
|
||||
(scale*x[i]).isApproximatelyEqual(to: scale*x[j], relativeTolerance: tol)
|
||||
)
|
||||
}
|
||||
// if a ≤ b ≤ c, and a ≈ c, then a ≈ b and b ≈ c (relative tolerance)
|
||||
var left = x.firstIndex { x[i].isApproximatelyEqual(to: $0, relativeTolerance: tol) }
|
||||
var right = x.lastIndex { x[i].isApproximatelyEqual(to: $0, relativeTolerance: tol) }
|
||||
if let l = left, let r = right {
|
||||
for j in l ..< r {
|
||||
XCTAssertTrue(x[i].isApproximatelyEqual(to: x[j], relativeTolerance: tol))
|
||||
}
|
||||
}
|
||||
// if a ≤ b ≤ c, and a ≈ c, then a ≈ b and b ≈ c (absolute tolerance)
|
||||
left = x.firstIndex { x[i].isApproximatelyEqual(to: $0, absoluteTolerance: tol) }
|
||||
right = x.lastIndex { x[i].isApproximatelyEqual(to: $0, absoluteTolerance: tol) }
|
||||
if let l = left, let r = right {
|
||||
for j in l ..< r {
|
||||
XCTAssertTrue(x[i].isApproximatelyEqual(to: x[j], absoluteTolerance: tol))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFloat() {
|
||||
testSpecials(Float.self)
|
||||
testDefaults(Float.self)
|
||||
testRandom(Float.self)
|
||||
}
|
||||
|
||||
func testDouble() {
|
||||
testSpecials(Double.self)
|
||||
testDefaults(Double.self)
|
||||
testRandom(Double.self)
|
||||
}
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
func testFloat80() {
|
||||
testSpecials(Float80.self)
|
||||
testDefaults(Float80.self)
|
||||
testRandom(Float80.self)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#[[
|
||||
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
|
||||
#]]
|
||||
|
||||
add_library(RealTests
|
||||
ApproximateEqualityTests.swift
|
||||
ElementaryFunctionChecks.swift
|
||||
IntegerExponentTests.swift)
|
||||
target_compile_options(RealTests PRIVATE
|
||||
-enable-testing)
|
||||
target_link_libraries(RealTests PUBLIC
|
||||
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
|
||||
RealModule
|
||||
_TestSupport
|
||||
XCTest)
|
||||
@@ -0,0 +1,178 @@
|
||||
//===--- ElementaryFunctionChecks.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 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))
|
||||
assertClose(0.3843967744956390830381948729670469737, Self.asin(0.375))
|
||||
assertClose(0.3587706702705722203959200639264604997, Self.atan(0.375))
|
||||
assertClose(0.9305076219123142911494767922295555080, Self.cos(0.375))
|
||||
assertClose(0.3662725290860475613729093517162641571, Self.sin(0.375))
|
||||
assertClose(0.3936265759256327582294137871012180981, Self.tan(0.375))
|
||||
assertClose(0.4949329230945269058895630995767185785, Self.acosh(1.125))
|
||||
assertClose(0.9670596312833237113713762009167286709, Self.asinh(1.125))
|
||||
assertClose(0.7331685343967135223291211023213964500, Self.atanh(0.625))
|
||||
assertClose(1.0711403467045867672994980155670160493, Self.cosh(0.375))
|
||||
assertClose(0.3838510679136145687542956764205024589, Self.sinh(0.375))
|
||||
assertClose(0.3583573983507859463193602315531580424, Self.tanh(0.375))
|
||||
assertClose(1.4549914146182013360537936919875185083, Self.exp(0.375))
|
||||
assertClose(0.4549914146182013360537936919875185083, Self.expMinusOne(0.375))
|
||||
assertClose(-0.980829253011726236856451127452003999, Self.log(0.375))
|
||||
assertClose(0.3184537311185346158102472135905995955, Self.log(onePlus: 0.375))
|
||||
assertClose(-0.7211247851537041911608191553900547941, Self.root(-0.375, 3))
|
||||
XCTAssertEqual(-10, Self.root(-1000, 3))
|
||||
assertClose(0.6123724356957945245493210186764728479, Self.sqrt(0.375))
|
||||
assertClose(0.54171335479545025876069682133938570, Self.pow(0.375, 0.625))
|
||||
assertClose(-0.052734375, Self.pow(-0.375, 3))
|
||||
}
|
||||
}
|
||||
|
||||
internal extension Real where Self: BinaryFloatingPoint {
|
||||
static func realFunctionChecks() {
|
||||
assertClose(1.2968395546510096659337541177924511598, Self.exp2(0.375))
|
||||
assertClose(2.3713737056616552616517527574788898386, Self.exp10(0.375))
|
||||
assertClose(-1.415037499278843818546261056052183491, Self.log2(0.375))
|
||||
assertClose(-0.425968732272281148346188780918363771, Self.log10(0.375))
|
||||
assertClose(0.54041950027058415544357836460859991, Self.atan2(y: 0.375, x: 0.625))
|
||||
assertClose(0.72886898685566255885926910969319788, Self.hypot(0.375, 0.625))
|
||||
assertClose(0.4041169094348222983238250859191217675, Self.erf(0.375))
|
||||
assertClose(0.5958830905651777016761749140808782324, Self.erfc(0.375))
|
||||
assertClose(2.3704361844166009086464735041766525098, Self.gamma(0.375))
|
||||
#if !os(Windows)
|
||||
assertClose( -0.11775527074107877445136203331798850, Self.logGamma(1.375))
|
||||
XCTAssertEqual(.plus, Self.signGamma(1.375))
|
||||
XCTAssertEqual(.minus, Self.signGamma(-2.375))
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
extension Real {
|
||||
static func powZeroChecks() {
|
||||
// pow(_:Self,_:Self) is defined by exp(y log(x)) and has edge-cases to
|
||||
// match. In particular, if x is zero, log(x) is -infinity, so pow(0,0)
|
||||
// is exp(0 * -infinity) = exp(nan) = nan.
|
||||
XCTAssertEqual(pow(0, -1 as Self), infinity)
|
||||
XCTAssert(pow(0, 0 as Self).isNaN)
|
||||
XCTAssertEqual(pow(0, 1 as Self), zero)
|
||||
// pow(_:Self,_:Int) is defined by repeated multiplication or division,
|
||||
// and hence pow(0, 0) is 1.
|
||||
XCTAssertEqual(pow(0, -1), infinity)
|
||||
XCTAssertEqual(pow(0, 0), 1)
|
||||
XCTAssertEqual(pow(0, 1), zero)
|
||||
}
|
||||
}
|
||||
|
||||
final class ElementaryFunctionChecks: XCTestCase {
|
||||
|
||||
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
|
||||
func testFloat16() {
|
||||
if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
|
||||
Float16.elementaryFunctionChecks()
|
||||
Float16.realFunctionChecks()
|
||||
Float16.powZeroChecks()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
//===--- IntegerExponentTests.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 XCTest
|
||||
import RealModule
|
||||
import _TestSupport
|
||||
|
||||
internal extension Real where Self: FixedWidthFloatingPoint {
|
||||
|
||||
static func testIntegerExponentCommon() {
|
||||
// TODO: replace with seedable generator, print seed.
|
||||
var g = SystemRandomNumberGenerator()
|
||||
// If x is -1, then the result is ±1 with sign chosen by parity of n.
|
||||
// Simply converting n to Real will flip parity when n is large, so
|
||||
// first check that we get those cases right.
|
||||
XCTAssertEqual(Self.pow(-1, 0), 1)
|
||||
XCTAssertEqual(Self.pow(-1, 1), -1)
|
||||
XCTAssertEqual(Self.pow(-1, -1), -1)
|
||||
XCTAssertEqual(Self.pow(-1, 2), 1)
|
||||
XCTAssertEqual(Self.pow(-1, -2), 1)
|
||||
XCTAssertEqual(Self.pow(-1, Int.max - 1), 1)
|
||||
XCTAssertEqual(Self.pow(-1, -Int.max + 1), 1)
|
||||
XCTAssertEqual(Self.pow(-1, Int.max), -1)
|
||||
XCTAssertEqual(Self.pow(-1, -Int.max), -1)
|
||||
XCTAssertEqual(Self.pow(-1, Int.min), 1)
|
||||
// Generate some random test values that definitely overflow or
|
||||
// underflow; we want to be sure that we get the right ±0 or ±∞
|
||||
// result.
|
||||
for _ in 0 ..< 10 {
|
||||
let x = Self.random(in: 2 ..< 4, using: &g)
|
||||
let nLowerBound = 1 - Int(Self.leastNonzeroMagnitude.exponent)
|
||||
let n = Int.random(in: nLowerBound ..< .max, using: &g)
|
||||
let even = n & -2
|
||||
let odd = even | 1
|
||||
assertClose( .infinity, Self.pow(x, even))
|
||||
assertClose( .infinity, Self.pow(x, odd))
|
||||
assertClose( 0.0, Self.pow(1/x, even))
|
||||
assertClose( 0.0, Self.pow(1/x, odd))
|
||||
assertClose( .infinity, Self.pow(-x, even))
|
||||
assertClose(-.infinity, Self.pow(-x, odd))
|
||||
assertClose( 0.0, Self.pow(-1/x, even))
|
||||
assertClose(-0.0, Self.pow(-1/x, odd))
|
||||
assertClose( 0.0, Self.pow(x, -even))
|
||||
assertClose( 0.0, Self.pow(x, -odd))
|
||||
assertClose( .infinity, Self.pow(1/x, -even))
|
||||
assertClose( .infinity, Self.pow(1/x, -odd))
|
||||
assertClose( 0.0, Self.pow(-x, -even))
|
||||
assertClose(-0.0, Self.pow(-x, -odd))
|
||||
assertClose( .infinity, Self.pow(-1/x, -even))
|
||||
assertClose(-.infinity, Self.pow(-1/x, -odd))
|
||||
}
|
||||
}
|
||||
|
||||
static func testIntegerExponentDoubleAndSmaller() {
|
||||
// max/min exponents, these always saturate, but this will reveal
|
||||
// errors in some implementations that one could try.
|
||||
let u = Self(1).nextUp
|
||||
let d = Self(1).nextDown
|
||||
assertClose( .infinity, Self.pow(-u, Int.max - 1))
|
||||
assertClose( 0.0, Self.pow(-d, Int.max - 1))
|
||||
assertClose( 0.0, Self.pow(-u, -Int.max + 1))
|
||||
assertClose( .infinity, Self.pow(-d, -Int.max + 1))
|
||||
assertClose(-.infinity, Self.pow(-u, Int.max))
|
||||
assertClose(-0.0, Self.pow(-d, Int.max))
|
||||
assertClose(-0.0, Self.pow(-u, -Int.max))
|
||||
assertClose(-.infinity, Self.pow(-d, -Int.max))
|
||||
assertClose( 0.0, Self.pow(-u, Int.min))
|
||||
assertClose( .infinity, Self.pow(-d, Int.min))
|
||||
}
|
||||
}
|
||||
|
||||
#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()
|
||||
testIntegerExponentDoubleAndSmaller()
|
||||
let u = Float16(1).nextUp
|
||||
let d = Float16(1).nextDown
|
||||
// Smallest exponents not exactly representable as Float16.
|
||||
assertClose(-7.3890572722436554354625993393835304, Float16.pow(-u, 0x801))
|
||||
assertClose(-0.3676100238077049750885141244927184, Float16.pow(-d, 0x801))
|
||||
// Exponents close to overflow boundary.
|
||||
assertClose( 65403.86633107, Float16.pow(-u, 11360))
|
||||
assertClose(-65467.73729429, Float16.pow(-u, 11361))
|
||||
assertClose( 65531.67063149, Float16.pow(-u, 11362))
|
||||
assertClose( 65487.96799785, Float16.pow(-d, -22706))
|
||||
assertClose(-65519.96016590, Float16.pow(-d, -22707))
|
||||
assertClose( 65551.96796276, Float16.pow(-d, -22708))
|
||||
// Exponents close to underflow boundary.
|
||||
assertClose( 5.966876499900e-8, Float16.pow(-u, -17042))
|
||||
assertClose(-5.961055156973e-8, Float16.pow(-u, -17043))
|
||||
assertClose( 5.955239493405e-8, Float16.pow(-u, -17044))
|
||||
assertClose( 5.964109628044e-8, Float16.pow(-d, 34060))
|
||||
assertClose(-5.961197465140e-8, Float16.pow(-d, 34061))
|
||||
assertClose( 5.958286724190e-8, Float16.pow(-d, 34062))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension Float {
|
||||
static func testIntegerExponent() {
|
||||
testIntegerExponentCommon()
|
||||
testIntegerExponentDoubleAndSmaller()
|
||||
let u = Float(1).nextUp
|
||||
let d = Float(1).nextDown
|
||||
// Smallest exponents not exactly representable as Float.
|
||||
assertClose(-7.3890560989306677280287919329569359, Float.pow(-u, 0x1000001))
|
||||
assertClose(-0.3678794082804575860056608283059288, Float.pow(-d, 0x1000001))
|
||||
// Exponents close to overflow boundary.
|
||||
assertClose(-3.4028231352500001570898203463449749e38, Float.pow(-u, 744261161))
|
||||
assertClose( 3.4028235408981285772043562848249166e38, Float.pow(-u, 744261162))
|
||||
assertClose(-3.4028239465463053543440887892352174e38, Float.pow(-u, 744261163))
|
||||
assertClose( 3.4028233551634475284795244782720072e38, Float.pow(-d, -1488522190))
|
||||
assertClose(-3.4028235579875369356575053576685267e38, Float.pow(-d, -1488522191))
|
||||
assertClose( 3.4028237608116384320940078199368685e38, Float.pow(-d, -1488522192))
|
||||
// Exponents close to underflow boundary.
|
||||
assertClose( 7.0064936491761438872280296737844625e-46, Float.pow(-u, -872181048))
|
||||
assertClose(-7.0064928139371132951305928725186420e-46, Float.pow(-u, -872181049))
|
||||
assertClose( 7.0064919786981822712727285793333389e-46, Float.pow(-u, -872181050))
|
||||
assertClose(-7.0064924138100205091278464932003585e-46, Float.pow(-d, 1744361943))
|
||||
assertClose( 7.0064919961905290625123586120258840e-46, Float.pow(-d, 1744361944))
|
||||
assertClose(-7.0064915785710625079583096856510544e-46, Float.pow(-d, 1744361945))
|
||||
}
|
||||
}
|
||||
|
||||
extension Double {
|
||||
static func testIntegerExponent() {
|
||||
testIntegerExponentCommon()
|
||||
// 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.
|
||||
assertClose(-7.3890560989306502272304274605750685, Double.pow(-u, 0x20000000000001))
|
||||
assertClose(-0.1353352832366126918939994949724833, Double.pow(-u, -0x20000000000001))
|
||||
assertClose(-0.3678794411714422603312898889458068, Double.pow(-d, 0x20000000000001))
|
||||
assertClose(-2.7182818284590456880451484776630468, Double.pow(-d, -0x20000000000001))
|
||||
// Exponents close to overflow boundary.
|
||||
#if os(Windows)
|
||||
// TODO: It appears that the Windows pow doesn't carry enough precision
|
||||
// through the computation of log(1.nextDown) to produce a good result
|
||||
// for these cases; we'll want to provide a better implementation at some
|
||||
// point in the future. It's acceptable in the short term, however.
|
||||
let tol: Double = 360
|
||||
#else
|
||||
let tol: Double = 16
|
||||
#endif
|
||||
assertClose( 1.7976931348623151738531864721534215e308, Double.pow(-u, 3196577161300664268), allowedError: tol)
|
||||
assertClose(-1.7976931348623155730212483790972209e308, Double.pow(-u, 3196577161300664269), allowedError: tol)
|
||||
assertClose( 1.7976931348623159721893102860411089e308, Double.pow(-u, 3196577161300664270), allowedError: tol)
|
||||
assertClose( 1.7976931348623157075547244136070910e308, Double.pow(-d, -6393154322601327474), allowedError: tol)
|
||||
assertClose(-1.7976931348623159071387553670790721e308, Double.pow(-d, -6393154322601327475), allowedError: tol)
|
||||
assertClose( 1.7976931348623161067227863205510754e308, Double.pow(-d, -6393154322601327476), allowedError: tol)
|
||||
// Exponents close to underflow boundary.
|
||||
assertClose( 2.4703282292062334560337346683707907e-324, Double.pow(-u, -3355781687888880946))
|
||||
assertClose(-2.4703282292062329075106789791206172e-324, Double.pow(-u, -3355781687888880947))
|
||||
assertClose( 2.4703282292062323589876232898705654e-324, Double.pow(-u, -3355781687888880948))
|
||||
assertClose(-2.4703282292062332640976590913373022e-324, Double.pow(-d, 6711563375777760775))
|
||||
assertClose( 2.4703282292062329898361312467121758e-324, Double.pow(-d, 6711563375777760776))
|
||||
assertClose(-2.4703282292062327155746034020870799e-324, Double.pow(-d, 6711563375777760777))
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
final class IntegerExponentTests: XCTestCase {
|
||||
|
||||
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
|
||||
func testFloat16() {
|
||||
if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
|
||||
Float16.testIntegerExponent()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
func testFloat() {
|
||||
Float.testIntegerExponent()
|
||||
}
|
||||
|
||||
func testDouble() {
|
||||
Double.testIntegerExponent()
|
||||
}
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
func testFloat80() {
|
||||
Float80.testIntegerExponentCommon()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
//===--- ElementaryFunctionTests.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 XCTest
|
||||
import Real
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
typealias TestLiteralType = Float80
|
||||
#else
|
||||
typealias TestLiteralType = Double
|
||||
#endif
|
||||
|
||||
func sanityCheck<T>(_ expected: TestLiteralType, _ actual: T,
|
||||
ulps allowed: T = 16,
|
||||
file: StaticString = #file, line: UInt = #line)
|
||||
where T: BinaryFloatingPoint {
|
||||
// Default tolerance is 16 ulps; It's OK to relax this as needed for new
|
||||
// platforms, as these tests are *not* intended to validate the math
|
||||
// library--they are only intended to check that the Swift bindings are
|
||||
// calling the right functions in the math library. It's important, however
|
||||
// not to relax the tolerance beyond a few hundred ulps, because these tests
|
||||
// need to detect errors where the *wrong function* is being called; e.g.
|
||||
// we need to flag an implentation that inadvertently called the C hypotf
|
||||
// function instead of hypot. This is especially important because the C
|
||||
// shims that we're calling through will allow silent type conversions.
|
||||
if actual == T(expected) || actual.isNaN && expected.isNaN {
|
||||
return
|
||||
}
|
||||
// Compute error in ulp, compare to tolerance.
|
||||
let absoluteError = T(abs(TestLiteralType(actual) - expected))
|
||||
let ulpError = absoluteError / T(expected).ulp
|
||||
XCTAssert(ulpError <= allowed, "\(actual) != \(expected) as \(T.self)" +
|
||||
"\n \(ulpError)-ulp error exceeds \(allowed)-ulp tolerance.",
|
||||
file: file, line: line)
|
||||
}
|
||||
|
||||
internal extension ElementaryFunctions where Self: BinaryFloatingPoint {
|
||||
static func elementaryFunctionTests() {
|
||||
sanityCheck(1.1863995522992575361931268186727044683, Self.acos(0.375))
|
||||
sanityCheck(0.3843967744956390830381948729670469737, Self.asin(0.375))
|
||||
sanityCheck(0.3587706702705722203959200639264604997, Self.atan(0.375))
|
||||
sanityCheck(0.9305076219123142911494767922295555080, Self.cos(0.375))
|
||||
sanityCheck(0.3662725290860475613729093517162641571, Self.sin(0.375))
|
||||
sanityCheck(0.3936265759256327582294137871012180981, Self.tan(0.375))
|
||||
sanityCheck(0.4949329230945269058895630995767185785, Self.acosh(1.125))
|
||||
sanityCheck(0.9670596312833237113713762009167286709, Self.asinh(1.125))
|
||||
sanityCheck(0.7331685343967135223291211023213964500, Self.atanh(0.625))
|
||||
sanityCheck(1.0711403467045867672994980155670160493, Self.cosh(0.375))
|
||||
sanityCheck(0.3838510679136145687542956764205024589, Self.sinh(0.375))
|
||||
sanityCheck(0.3583573983507859463193602315531580424, Self.tanh(0.375))
|
||||
sanityCheck(1.4549914146182013360537936919875185083, Self.exp(0.375))
|
||||
sanityCheck(0.4549914146182013360537936919875185083, Self.expMinusOne(0.375))
|
||||
sanityCheck(-0.980829253011726236856451127452003999, Self.log(0.375))
|
||||
sanityCheck(0.3184537311185346158102472135905995955, Self.log(onePlus: 0.375))
|
||||
sanityCheck(-0.7211247851537041911608191553900547941, Self.root(-0.375, 3))
|
||||
XCTAssertEqual(-10, Self.root(-1000, 3))
|
||||
sanityCheck(0.6123724356957945245493210186764728479, Self.sqrt(0.375))
|
||||
sanityCheck(0.54171335479545025876069682133938570, Self.pow(0.375, 0.625))
|
||||
sanityCheck(-0.052734375, Self.pow(-0.375, 3))
|
||||
}
|
||||
}
|
||||
|
||||
internal extension Real where Self: BinaryFloatingPoint {
|
||||
static func realFunctionTests() {
|
||||
sanityCheck(1.2968395546510096659337541177924511598, Self.exp2(0.375))
|
||||
sanityCheck(2.3713737056616552616517527574788898386, Self.exp10(0.375))
|
||||
sanityCheck(-1.415037499278843818546261056052183491, Self.log2(0.375))
|
||||
sanityCheck(-0.425968732272281148346188780918363771, Self.log10(0.375))
|
||||
sanityCheck(0.54041950027058415544357836460859991, Self.atan2(y: 0.375, x: 0.625))
|
||||
sanityCheck(0.72886898685566255885926910969319788, Self.hypot(0.375, 0.625))
|
||||
sanityCheck(0.4041169094348222983238250859191217675, Self.erf(0.375))
|
||||
sanityCheck(0.5958830905651777016761749140808782324, Self.erfc(0.375))
|
||||
sanityCheck(2.3704361844166009086464735041766525098, Self.gamma(0.375))
|
||||
#if !os(Windows)
|
||||
sanityCheck( -0.11775527074107877445136203331798850, Self.logGamma(1.375))
|
||||
XCTAssertEqual(.plus, Self.signGamma(1.375))
|
||||
XCTAssertEqual(.minus, Self.signGamma(-2.375))
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
final class ElementaryFunctionTests: XCTestCase {
|
||||
|
||||
func testFloat() {
|
||||
Float.elementaryFunctionTests()
|
||||
Float.realFunctionTests()
|
||||
}
|
||||
|
||||
func testDouble() {
|
||||
Double.elementaryFunctionTests()
|
||||
Double.realFunctionTests()
|
||||
}
|
||||
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
func testFloat80() {
|
||||
Float80.elementaryFunctionTests()
|
||||
Float80.realFunctionTests()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
#[[
|
||||
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
|
||||
#]]
|
||||
|
||||
# Returns the architecture name in a variable
|
||||
#
|
||||
# Usage:
|
||||
# get_swift_host_arch(result_var_name)
|
||||
#
|
||||
# Sets ${result_var_name} with the converted architecture name derived from
|
||||
# CMAKE_SYSTEM_PROCESSOR.
|
||||
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}" 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")
|
||||
set("${result_var_name}" "powerpc64le" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "s390x")
|
||||
set("${result_var_name}" "s390x" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv6l")
|
||||
set("${result_var_name}" "armv6" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7l")
|
||||
set("${result_var_name}" "armv7" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7-a")
|
||||
set("${result_var_name}" "armv7" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "AMD64")
|
||||
set("${result_var_name}" "x86_64" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "IA64")
|
||||
set("${result_var_name}" "itanium" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86")
|
||||
set("${result_var_name}" "i686" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "i686")
|
||||
set("${result_var_name}" "i686" PARENT_SCOPE)
|
||||
else()
|
||||
message(FATAL_ERROR "Unrecognized architecture on host system: ${CMAKE_SYSTEM_PROCESSOR}")
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# Returns the os name in a variable
|
||||
#
|
||||
# Usage:
|
||||
# get_swift_host_os(result_var_name)
|
||||
#
|
||||
#
|
||||
# Sets ${result_var_name} with the converted OS name derived from
|
||||
# CMAKE_SYSTEM_NAME.
|
||||
function(get_swift_host_os result_var_name)
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL Darwin)
|
||||
set(${result_var_name} macosx PARENT_SCOPE)
|
||||
else()
|
||||
string(TOLOWER ${CMAKE_SYSTEM_NAME} cmake_system_name_lc)
|
||||
set(${result_var_name} ${cmake_system_name_lc} PARENT_SCOPE)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
function(_install_target module)
|
||||
get_swift_host_arch(swift_arch)
|
||||
get_swift_host_os(swift_os)
|
||||
install(TARGETS ${module}
|
||||
ARCHIVE DESTINATION lib/swift$<$<NOT:$<BOOL:${BUILD_SHARED_LIBS}>>:_static>/${swift_os}
|
||||
LIBRARY DESTINATION lib/swift$<$<NOT:$<BOOL:${BUILD_SHARED_LIBS}>>:_static>/${swift_os}
|
||||
RUNTIME DESTINATION bin)
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL Darwin)
|
||||
install(FILES $<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module}.swiftdoc
|
||||
DESTINATION lib/swift$<$<NOT:$<BOOL:${BUILD_SHARED_LIBS}>>:_static>/${swift_os}/${mmodule}.swiftmodule
|
||||
RENAME ${swift_arch}.swiftdoc)
|
||||
install(FILES $<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module}.swiftmodule
|
||||
DESTINATION lib/swift$<$<NOT:$<BOOL:${BUILD_SHARED_LIBS}>>:_static>/${swift_os}/${mmodule}.swiftmodule
|
||||
RENAME ${swift_arch}.swiftmodule)
|
||||
else()
|
||||
install(FILES
|
||||
$<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module}.swiftdoc
|
||||
$<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module}.swiftmodule
|
||||
DESTINATION lib/swift$<$<NOT:$<BOOL:${BUILD_SHARED_LIBS}>>:_static>/${swift_os}/${swift_arch})
|
||||
endif()
|
||||
endfunction()
|
||||
Reference in new issue
Block a user