177 Commits
Author SHA1 Message Date
Stephen Canon 0a5bc04095 Merge pull request #215 from stephentyrone/arm64-mac-cmake-1.0
add arm64 support for M1 Mac
2021-11-18 09:21:09 -05:00
bob a6bea6639c add arm64 support for M1 Mac 2021-11-18 09:18:40 -05:00
Stephen Canon 0a23770641 Merge pull request #198 from stephentyrone/clarify-stability-differentiable
Clarify that differentaible API is not stable.
2021-08-31 16:29:00 -04:00
Stephen Canon d560765047 Clarify that differentaible API is not stable. 2021-08-31 16:26:17 -04:00
Stephen Canon 1e5cbc4e21 Merge pull request #195 from stephentyrone/readme-semver-1.0
Update README for 1.0.0.
2021-08-31 11:34:42 -04:00
Stephen Canon b4ec7556e9 Update README for 1.0.0. 2021-08-31 11:31:30 -04:00
Stephen Canon 79f6025798 Merge pull request #193 from stephentyrone/cherry-pick-doc-changes-from-main
Cherry pick doc changes from main
2021-08-27 09:38:44 -04:00
Stephen Canon 03c5840722 Merge pull request #194 from stephentyrone/source-stability-api
Add notes about what the public API is.
2021-08-27 09:38:19 -04:00
Stephen Canon ed66862a2c Add notes about what the public API is. 2021-08-27 09:36:56 -04:00
Stephen Canon bcde4bc513 Comment cleanups. 2021-08-27 09:25:57 -04:00
Stephen Canon 58f95289a0 Merge pull request #185 from stephentyrone/reciprocal-documentation
Further expand documentation of `reciprocal` with some example use.
2021-08-27 09:09:21 -04:00
Stephen Canon 832dac1ef8 Merge pull request #184 from stephentyrone/document-real-reciprocal-1.0
Merge pull request #182 from stephentyrone/more-documentation-for-1.0
2021-08-19 19:41:47 -04:00
Stephen Canon 419caa222f Merge pull request #182 from stephentyrone/more-documentation-for-1.0
Add some documentation for AlgebraicField ops, minor fix for Augmented.
2021-08-19 19:38:54 -04:00
Stephen Canon 5a0aedbccd Merge pull request #183 from stephentyrone/deprecations-for-1.0
Add deprecation warnings for old Augmented names in release/1.0
2021-08-19 19:38:17 -04:00
Stephen Canon 8e3d889b5f Add deprecation warnings for old Augmented names in release/1.0 2021-08-19 19:35:06 -04:00
Stephen Canon 92f0095962 Document the Augmented enum in RealModule in advance of 1.0 2021-08-19 14:08:22 -04:00
Stephen Canon f50a1acf2d Merge pull request #178 from kylemacomber/remove-xcodesamplecode-plist
Remove .xcodesamplecode.plist, which prevents editing markdown from Xcode
2021-03-23 09:03:31 -04:00
Stephen Canon 2aa93ccf24 Merge pull request #179 from stephentyrone/remove-workflows
remove workflows, no longer needed.
2021-03-21 16:01:56 -04:00
Steve (Numerics) Canon 50161d39df remove workflows, no longer needed. 2021-03-21 16:01:23 -04:00
Kyle Macomber d34cff5a13 Remove .xcodesamplecode.plist, which prevents editing markdown from Xcode 2021-03-19 12:40:59 -07:00
Stephen Canon 9f55a78685 Merge pull request #175 from stephentyrone/eighty-columns-wide-my-father-lies
80-column formatting for source doc comments
2021-03-03 20:01:35 -05:00
Steve (Numerics) Canon 5827f9a943 80-column formatting for source doc comments
Tidying, plus a few small edits. This commit should not include any code changes.
2021-03-03 14:01:09 -05:00
Stephen Canon 3cad9b69a0 Update README.md
Update version number in sample code.
2021-02-21 21:22:01 -05:00
Stephen Canon 6583ac70c3 Merge pull request #172 from stephentyrone/float16-availability
Adjust Float16 availability for Swift 5.4 toolchains.
2021-02-19 17:38:49 -05:00
Steve (Numerics) Canon 97852afaf5 Adjust Float16 availability for Swift 5.4 toolchains.
In older toolchains, Float16 is marked unavailable on all mac targets; starting with the 5.4 toolchain, it is available starting in macOS 11.0 when targeting Apple Silicon.
2021-02-19 15:53:15 -05:00
Steve (Numerics) Canon 105b59b8a4 Remove vestigal C complex shims.
These used to be used by some test appratus, but they are no longer
used and can be removed.
2021-02-19 15:16:30 -05:00
Steve (Numerics) Canon 0cf166da79 Remove zeroTangentVectorInitializer test, as the requirement has been removed from Swift main. 2021-02-19 15:11:21 -05:00
Stephen Canon 4a2cbc186b Merge pull request #166 from NevinBR/patch-5
Cleaning up some comments
2020-11-15 12:22:56 -05:00
NevinBR 5a7eb37c19 Cleaned up some comments 2020-11-11 14:05:55 -05:00
Stephen Canon 198da2adf9 Merge pull request #165 from stephentyrone/complex-elfns-inlinable
Mark all complex elementary functions inlinable
2020-11-09 16:43:31 -05:00
Stephen Canon 26c51aca1b Mark all complex elementary functions inlinable
This is kind of dubious, but necessary for performance reasons until we get dependable cross-module specialization. Also has a minor test fix for 32b platforms.
2020-11-09 16:41:45 -05:00
Stephen Canon c5a3504143 Merge pull request #164 from compnerd/update
build: update file lists for `RealModule` and `_TestSupport`
2020-11-09 14:45:44 -05:00
Saleem Abdulrasool 00c6183670 build: update file lists for RealModule and _TestSupport
Add new files to the list that were missed in the CMakeLists.txt
updates.
2020-11-09 11:23:48 -08:00
Stephen Canon ae364a28f0 Merge pull request #162 from apple/complex-elfns
Conform Complex to Elementary Functions
2020-11-09 11:39:18 -05:00
Stephen Canon e042c13415 Merge pull request #150 from markuswntr/master
Refactor README.md and include Approximate Equality as part of the RealModule.
2020-11-09 11:28:25 -05:00
Stephen Canon 16837299c1 Added inverse trig and hyperbolics, some rough test coverage. 2020-11-09 11:25:08 -05:00
Stephen Canon 0c066bd268 Merge pull request #155 from stephentyrone/complex-log1p
Augmented arithmetic implementations of log and log(onePlus:) for enhanced accuracy close to the circle where the real part of the result vanishes.
2020-11-05 15:15:35 -05:00
Stephen Canon 2b4c6701f2 log and log(onePlus:) implementations for Complex
These significantly improve on the state of the art for arguments close to the circle where the result vanishes, producing good componentwise relative accuracy as well as relative accuracy in the complex norm.

Also drops the argument parser dependency, which is desirable to avoid possible circular dependencies in the future with algorithms.
2020-11-05 15:14:25 -05:00
Stephen Canon 874c767424 Merge pull request #159 from compnerd/autolink
build: enable building `Numerics` on Darwin with CMake
2020-10-14 12:05:59 -04:00
Saleem Abdulrasool 0ee972ff92 build: enable building Numerics on Darwin with CMake
The `-enable-force-autolink` flag is not supported on Darwin.
Fortunately, it is also unnecessary to work around the SR on Darwin.
Simply exclude the flag when targeting Darwin.
2020-10-12 14:01:56 -07:00
Stephen Canon 754cbd9e2e Merge branch 'complex-elfns' of github.com:stephentyrone/swift-numerics into complex-elfns 2020-10-01 17:12:48 -04:00
Stephen Canon 209a794eb6 Initial implementation of log(onePlus:) 2020-10-01 16:39:11 -04:00
Stephen Canon af19aec6ff WIP 2020-10-01 16:39:11 -04:00
Stephen Canon ed8fc21f1e Add TODO for algorithmic improvements on tanh. 2020-10-01 16:39:11 -04:00
Stephen Canon 1cbb94ac71 First pass over hyperbolics and trig functions for Complex. 2020-10-01 16:39:11 -04:00
Stephen Canon 0b2dc469ed Moved sampling-based tests out of unit and into an exectuable target. 2020-10-01 16:39:11 -04:00
Stephen Canon efbe11a734 Fix typo expMinusOne/exp in near-overflow check. 2020-10-01 16:39:11 -04:00
Stephen Canon 4798b68203 Refactor test support to remove XCTest dependency. 2020-10-01 16:39:11 -04:00
Stephen Canon 5f408c0121 Cleanup. 2020-10-01 16:39:11 -04:00
Stephen Canon 09beddce47 WIP on complex elementary functions.
Rebased on master, then cleaned up exp and expm1. New algorithm for expm1 that gives good componentwise accuracy as well as normwise. I _think_ that this is fundamentally new; I can't recall seeing it anywhere before, though it's simple enough that I expect someone has thought of it before.

Also beefed up testing for exp and expm1. Left sketches of log/pow/sqrt/root in place, though I'm still working on filling out the testing for those.
2020-10-01 16:39:11 -04:00
Stephen Canon 2179fa1f82 Rename some tests to reflect what they actually do. 2020-10-01 16:39:11 -04:00
Stephen Canon 6d9de5d4ce Updates to resync with changes on master.
- Renamed scaled/unscaled to multiplied/divided
- Adopted new Real module name
- Adopted expMinusOne, log(onePlus:) names
2020-10-01 16:39:11 -04:00
Steve (Numerics) Canon e20b32d40f Initial pass over implementing ElementaryFunctions for Complex. 2020-10-01 16:39:11 -04:00
Stephen Canon 21282166fa Merge pull request #152 from stephentyrone/complex-trig
First pass over hyperbolics and trig functions for Complex.
2020-09-30 11:53:11 -04:00
Stephen Canon 6b24333510 Merge pull request #157 from stephentyrone/float16-availability-redux
Swap availability for #if check on Float16.
2020-09-18 16:59:35 -04:00
Stephen Canon e07b39453b Swap availability for #if check on Float16. 2020-09-18 16:01:51 -04:00
Stephen Canon 0f02c65854 Initial implementation of log(onePlus:) 2020-09-16 14:24:54 -04:00
Stephen Canon a76404b263 WIP 2020-09-15 14:33:21 -04:00
Markus Winter 298ea7d3f5 Merge pull request #6 from 8bitmp3/patch-1
Update Swift Numerics README to address feedback
2020-09-07 16:09:08 +02:00
8bitmp3 8e580358d4 Update Swift Numerics README to address feedback 2020-09-07 14:01:43 +01:00
Markus Winter 4b4dd42ad4 Merge pull request #5 from 8bitmp3/patch-1
Update Swift Numerics README to address feedback
2020-09-05 20:09:40 +02:00
8bitmp3 7be984de7e Update Swift Numerics README to address feedback 2020-09-05 18:16:28 +01:00
Markus Winter 6f96e6522d Merge pull request #4 from 8bitmp3/patch-2
Revert "new uses are discovered" in Swift Numerics README
2020-09-03 20:31:50 +02:00
8bitmp3 e95124c81f Revert "new uses are discovered" in Swift Numerics README 2020-09-03 18:21:31 +01:00
Markus Winter 2aeb3f8475 Merge pull request #3 from 8bitmp3/patch-1
Unwrap text, update Swift Numerics README
2020-09-03 19:14:54 +02:00
8bitmp3 ecfc4db4e9 Unwrap text, fix two minor syntactical errors in Swift Numerics README 2020-09-03 17:50:41 +01:00
Markus Winter f3e99a9c70 Syncs version number with latest release 2020-09-03 15:04:47 +02:00
Markus Winter 6d8d614bf2 Incorporate feedback in PR 2020-09-03 15:04:24 +02:00
Stephen Canon beb85076a5 Add TODO for algorithmic improvements on tanh. 2020-09-02 16:20:34 -04:00
Stephen Canon 6d396dfb44 First pass over hyperbolics and trig functions for Complex. 2020-09-02 16:02:41 -04:00
Stephen Canon f49d1af281 Moved sampling-based tests out of unit and into an exectuable target. 2020-09-02 09:09:39 -04:00
Markus Winter 82b04be57e Merge pull request #1 from 8bitmp3/patch-1
Enhance Swift Numerics README.md (technical writing perspective)
2020-09-02 15:06:58 +02:00
Stephen Canon 5eb865d25d Fix typo expMinusOne/exp in near-overflow check. 2020-09-02 08:49:46 -04:00
Stephen Canon 81e76b1a9a Refactor test support to remove XCTest dependency. 2020-09-02 08:49:19 -04:00
8bitmp3 dcad77ec73 Enhance Swift Numerics README.md (technical writing perspective) 2020-09-02 12:58:12 +01:00
Markus Winter 6ae59362f8 Update README to reflect inclusion of Approximate Equality 2020-09-02 09:53:06 +02:00
Stephen Canon 3d7462a834 Merge pull request #148 from stephentyrone/remove-f16-muladd
Remove muladdf16 for now.
2020-08-24 20:32:59 -04:00
Stephen Canon 0f8ef268d0 Remove muladdf16 for now. 2020-08-24 20:31:40 -04:00
Stephen Canon 694e5ae6de Cleanup. 2020-08-24 19:04:38 -04:00
Stephen Canon c26e60c6ba WIP on complex elementary functions.
Rebased on master, then cleaned up exp and expm1. New algorithm for expm1 that gives good componentwise accuracy as well as normwise. I _think_ that this is fundamentally new; I can't recall seeing it anywhere before, though it's simple enough that I expect someone has thought of it before.

Also beefed up testing for exp and expm1. Left sketches of log/pow/sqrt/root in place, though I'm still working on filling out the testing for those.
2020-08-24 19:03:20 -04:00
Stephen Canon 96a5383b0a Rename some tests to reflect what they actually do. 2020-08-24 19:01:46 -04:00
Stephen Canon 38b5251804 Updates to resync with changes on master.
- Renamed scaled/unscaled to multiplied/divided
- Adopted new Real module name
- Adopted expMinusOne, log(onePlus:) names
2020-08-24 19:01:46 -04:00
Steve (Numerics) Canon aaec0af9c8 Initial pass over implementing ElementaryFunctions for Complex. 2020-08-24 19:01:46 -04:00
Stephen Canon 3811e3bc7a Merge pull request #145 from stephentyrone/mulAdd-and-cosm1
Added mulAdd and cosMinusOne operations for Real.
2020-08-24 19:01:11 -04:00
Stephen Canon a0501be80a capitalization 2020-08-24 18:55:14 -04:00
Stephen Canon cda1b5e6f4 Added mulAdd and cosMinusOne operations for Real.
These are _mostly_ implementation hooks for Complex, but are generally useful, so I've made them public. Experimental, subject to renaming, especially mulAdd.
2020-08-24 18:52:58 -04:00
Stephen Canon fa16d7db6a Merge pull request #144 from stephentyrone/test-support
Factor test support out into a module
2020-08-24 18:51:59 -04:00
Stephen Canon a4372aa8d6 Added change suggested by Saleem for Windows/CMake build. 2020-08-24 18:31:12 -04:00
Stephen Canon 145156c40e Fix suggested by Saleem in review. 2020-08-24 16:50:10 -04:00
Stephen Canon c2d6cb716d Factor test support out into a module so Real and Complex tests can use it. 2020-08-24 16:21:25 -04:00
Stephen Canon 4077cd3461 Merge pull request #143 from stephentyrone/summer-cleanup
Rename some tests to reflect what they actually do.
2020-08-23 16:08:36 -04:00
Stephen Canon 337be4044e Rename some tests to reflect what they actually do. 2020-08-23 16:06:24 -04:00
Stephen Canon ddbc41f80b Merge pull request #140 from compnerd/complete-tests
Tests: add new tests to the Windows test suite
2020-08-05 14:25:40 -04:00
Stephen Canon 2342ba6314 Merge pull request #139 from compnerd/autolinking
Numerics: make `import Numerics` function on Windows
2020-08-05 14:23:52 -04:00
Saleem Abdulrasool 6af70e51ea Tests: add new tests to the Windows test suite
This adds the newly added tests to the Windows tests and adds a
dependency on the Numerics module which is used as well to prevent any
race conditions.
2020-08-05 18:22:33 +00:00
Saleem Abdulrasool d32bb739d4 Numerics: make import Numerics function on Windows
The `Numerics` module does not provide any symbols.  As a workaround,
provide the force link support.  Doing so exposes a bug in TBD
validation (SR-12254), which requires a workaround as well.  This
enables the use of `import Numerics` on Windows.
2020-08-05 18:21:38 +00:00
Stephen Canon 6b89e8d4b0 Merge pull request #138 from stephentyrone/relax-windows-pow-tolerances
Relax tolerances for some extreme pow cases on Windows.
2020-08-05 14:14:19 -04:00
Stephen Canon ce58d083a1 Relax tolerances for some extreme pow cases on Windows. 2020-08-05 14:13:08 -04:00
Stephen Canon 555340e882 Merge pull request #137 from compnerd/float16
build: add new source file to `RealModule`
2020-08-05 13:50:56 -04:00
Saleem Abdulrasool 7109a22972 build: add new source file to RealModule
`Float16+Real.swift` was added to the source tree, update the build
rules.
2020-08-05 10:28:19 -07:00
Stephen Canon ea6d7ffd5e Merge pull request #136 from stephentyrone/the-future-is-now
The future is now
2020-08-04 14:31:33 -04:00
Stephen Canon 97824411d9 Disable Float16 tests on swift < 5.3
This isn't actually quite the right check; what we really want is to use availability on Darwin platforms, but swift version on other platforms (that don't have the standard library in an SDK). But there's no good way to do that, so we simply make it unconditionally unavailable for earlier versions of Swift.
2020-08-04 12:18:29 -04:00
Stephen Canon d368762c95 Add swift version checks for Float16. 2020-08-04 08:30:25 -04:00
Stephen Canon 7e032e20fc Merge remote-tracking branch 'upstream/swift-5.3' 2020-08-04 08:26:26 -04:00
Stephen Canon 1ec79f5270 Add Swift version check for differentiable features. 2020-08-04 08:26:22 -04:00
Stephen Canon 44cb9f2d4a Merge pull request #133 from stephentyrone/more-float80-availability
Also mark Complex<Float80> test unavailable where needed.
2020-07-27 11:54:36 -04:00
Stephen Canon af3912cd4a Also mark Complex<Float80> test unavailable where needed. 2020-07-27 11:54:06 -04:00
Stephen Canon 4771ef24d2 Remove float16 tests for approx equality for now. 2020-07-27 11:53:28 -04:00
Stephen Canon 336740bd6d Also mark Complex<Float80> test unavailable where needed. 2020-07-27 11:53:02 -04:00
Stephen Canon 189f072825 Merge pull request #132 from stephentyrone/bugfix-availability-float80
Don't test approximate equality for Float80 on Android/Windows
2020-07-27 10:18:46 -04:00
Stephen Canon e6a343a205 Don't test approximate equality for Float80 on platforms that don't have it. 2020-07-27 10:07:05 -04:00
Stephen Canon 66ac02125c Don't test approximate equality for Float80 on platforms that don't have it. 2020-07-27 10:06:08 -04:00
Stephen Canon 4cd11553db Add Float16 tests for Approximate Equality. 2020-07-27 09:44:42 -04:00
Stephen Canon 13b74ae5f4 Merge branch 'master' into swift-5.3 2020-07-27 09:42:16 -04:00
Stephen Canon 2828bec340 Merge pull request #123 from stephentyrone/ApproximateEquality
This is a revised version of [SE-0259](https://github.com/apple/swift-evolution/blob/master/proposals/0259-approximately-equal.md) with a somewhat simpler API--there's no more special-case handling for zero. It's also more general; it works for any Numeric type whose magnitude conforms to FloatingPoint (or even any AdditiveArithmetic type with a Magnitude inferred from a supplied `norm` function). This is really nice, since it means that we get Complex and Quaternion support for free.

This new version tracks Julia's isapprox pretty closely; my opinion is that this is the only language with an approximate comparison worth discussing. The divergences from what Julia does are as follows:

- Spelling. Julia is much terser than Swift =)
- Julia defaults to using the Euclidean norm. That's not available in this generic context, and while it's more common, it's actually a less-good choice due to overflow considerations, so I'm defaulting to using the `.magnitude` property.
- When only a relativeTolerance is provided, Julia defaults to `absoluteTolerance = 0`, but I'm defaulting to `absoluteTolerance = relativeTolerance * .leastNormalMagnitude`. Perfectly reasonable arguments can be made for both choices; using zero matches the mathematical notion of a pure relative tolerance, but scaling to `.leastNormalMagnitude` better tracks the actual rounding behavior of floating-point arithmetic.
- Julia falls back on elementwise comparison when `a-b` is non-finite, but that's not possible in Swift, because there's no notion of "element" in the generic context for which this function is defined. I fall back on `a == b` instead. Again, both of these are pretty reasonable choices (neither is great, to be honest, but neither is terrible, either).
- I am not providing a "nans" parameter for now (override behavior so that nan compares approximately equal to nan). This is easy to add later, but it's also an extra knob that I would prefer to keep out of the API if we can. I may very well end up turning around and adding it for testing purposes, however =)

Addresses #3
2020-07-20 16:23:27 -04:00
Stephen Canon e69f12617b Lift the most general isApproximatelyEqual(to:) to AdditiveArithmetic.
The most general version of the API is now defined on AA as:

  ```
  public func isApproximatelyEqual<Magnitude>(
    to other: Self,
    absoluteTolerance: Magnitude,
    relativeTolerance: Magnitude = 0,
    norm: (Self) -> Magnitude
  ) -> Bool where Magnitude: FloatingPoint {
  ```

Note that AA does not have the magnitude property, so we can't default the norm in this setting. Therefore the following is kept on Numeric:

  ```
  public func isApproximatelyEqual(
    to other: Self,
    absoluteTolerance: Magnitude,
    relativeTolerance: Magnitude = 0
  ) -> Bool {
    self.isApproximatelyEqual(
      to: other,
      absoluteTolerance: absoluteTolerance,
      relativeTolerance: relativeTolerance,
      norm: \.magnitude
    )
  }
  ```

to provide the operation with norm defaulted (note: it's not optional, because then this would call itself).
2020-07-16 14:35:21 -04:00
Stephen Canon 80522b2bee Apply suggestions from code review 2020-07-14 17:41:02 -04:00
Stephen CanonandKyle Macomber a7ef6cd74c Update Sources/RealModule/ApproximateEquality.swift
Co-authored-by: Kyle Macomber <kmacomber@apple.com>
2020-07-14 17:34:02 -04:00
Stephen Canon 18ce9c0bbd Small test fix. 2020-07-14 15:18:55 -04:00
Stephen Canon 06c17a9a0f Documentation formatting. 2020-07-14 13:43:43 -04:00
Stephen Canon 2327363b24 Keypaths, #yolo 2020-07-14 13:19:00 -04:00
Stephen Canon 8b73836979 Rebased, added CMakeLists changes. 2020-07-14 12:34:27 -04:00
Stephen Canon 1dcd7f314b Dropped default-less overload, added norm for ApproxEquality.
- Removed isApproximatelyEqual(to:), since that functionality already
exists via the default value of relativeTolerance.

- Added the ability to specify a norm to use in the expert-mode
operation, defaulting to using $0.magnitude.
2020-07-14 12:33:25 -04:00
Stephen Canon 30627f2d06 Added text for asserts. 2020-07-14 12:33:25 -04:00
Stephen Canon c07076e917 Documentation improvements. 2020-07-14 12:33:25 -04:00
Stephen Canon 968d004d54 Further refinement of approximate equality
- Respell as isApproximatelyEqual(to:), by analogy to isEqual(to:),
  isLess(than:), etc.

- Refactor to eliminate the need for the Tolerance<Magnitude> type.
  Now all we have is one overloaded function with three implementations.
  This could be futher trimmed down to two versions by taking an
  optional parameter instead, but that seems a little bit less clean.

I want to write some more documentation and examples here, but this is
enough to discuss and start review.
2020-07-14 12:33:25 -04:00
Stephen Canon cfeda4df2d s/positive/non-negative/ for minimumScale. 2020-07-14 12:33:25 -04:00
Stephen Canon f275f7df53 Wrote some rough documentation
Also removed the default absolute tolerance, because in writing the documentation I realized that I couldn't reasonably justify having one.
2020-07-14 12:33:25 -04:00
Stephen Canon 7c0eb30664 Update complex test dependencies. 2020-07-14 12:33:25 -04:00
Stephen Canon 91ecc8a3b6 First crack at dusting approximate comparisons back off. 2020-07-14 12:33:25 -04:00
Stephen Canon 40b5a03063 Merge pull request #105 from compnerd/cmake
build: add initial CMake based build system
2020-07-03 09:49:53 -04:00
Stephen Canon 110beefe0b Merge pull request #105 from compnerd/cmake
build: add initial CMake based build system
2020-07-03 09:45:25 -04:00
Stephen Canon 085f6dab2e Merge branch 'master' into swift-5.3 2020-07-01 09:31:40 -04:00
Stephen Canon e97070e36c file -> filePath, too. 2020-06-29 14:52:30 -04:00
Stephen Canon 93b8e9f0df Float16 is unavailable on macOS 11. 2020-06-29 14:50:37 -04:00
Saleem Abdulrasool 697e9351e8 build: support the test suite on Windows 2020-06-25 09:46:54 -07:00
Saleem Abdulrasool f30f73ed10 build: add initial CMake based build system
This adds a CMake based build, which enables the build of swift-numerics
on Windows.  This currently does not add the test suite to the build as
there are still some issues to work out in building the full test suite
which require additional math operations to fully build.
2020-06-25 09:46:54 -07:00
Stephen Canon c634b5ddce Merge pull request #121 from dan-zheng/complex-differentiable
Define `Complex.zeroTangentVectorInitializer`.
2020-06-09 15:54:15 -04:00
Dan Zheng 86f0b33c65 Define Complex.zeroTangentVectorInitializer.
The `Differentiable.zeroTangentVectorInitializer` protocol requirement is a
closure producing a zero tangent vector, capturing minimal information from
`self`.

Fixes the `Complex: Differentiable` conformance for master toolchains.
2020-06-08 19:53:43 -07:00
Stephen Canon 593946d4aa Merge pull request #117 from markuswntr/master
Update documentation in ComplexModule
2020-06-04 12:03:44 -04:00
Markus Winter 5f09b7ef22 Update documentation in ComplexModule
Replace the now deprecated unsafeLengthSquared reference with the newer lengthSquared in the README.md of the Complex module.
2020-05-26 15:45:37 +02:00
Stephen Canon 6d75786ee0 Merge pull request #116 from stephentyrone/remove-complex-benchmarks
Remove complex benchmarks from tests for now
2020-05-05 15:18:53 -04:00
Stephen Canon 4297fbee6a Remove complex benchmarks from tests for now
I'm going to reinstate this as a binary executable target, so that we can ensure it only runs in release (and add some useful command line options via the argument parser). In the short-term, I want to unblock @compnerd's work on supporting Windows, so I'm preemtively removing the test (these tests cannot run on Windows).
2020-05-05 15:13:47 -04:00
Stephen Canon a410fd7029 Merge pull request #115 from stephentyrone/remove-broken-derivative
Also remove tests for broken derivative.
2020-05-01 08:59:40 -04:00
Stephen Canon c111cd001e Also remove tests for broken derivative. 2020-05-01 08:58:47 -04:00
Stephen Canon 52fa265ac9 Merge pull request #114 from stephentyrone/remove-broken-derivative
The derivative of Complex.init(_:_:) is broken with the current Xcode
2020-05-01 08:53:16 -04:00
Stephen Canon 750170404a The derivative of Complex.init(_:_:) is broken with the current Xcode toolchain.
Remove it for now; it'll still be present on the -5.3 branch, so we'll pick it up again when we're able to.
2020-05-01 08:50:32 -04:00
Stephen Canon a5cc950a86 Merge pull request #111 from rxwei/complex-derivatives
Make 'Complex' differentiable.
2020-04-22 16:43:46 -04:00
Stephen Canon 5ae8cd103a Merge pull request #111 from rxwei/complex-derivatives
Make 'Complex' differentiable.
2020-04-22 16:41:30 -04:00
Richard Wei 488e250259 Make 'Complex' differentiable.
* Conform `Complex` to `Differentiable`.
* Define derivatives for `init(_:_:)`, `real`, `imaginary`, `conjugate`, `+(_:_:)`, `-(_:_:)`, `*(_:_:)`, `/(_:_:)`.

Gated under `#if canImport(_Differentiation)`.
2020-04-22 13:35:36 -07:00
Stephen Canon 6e77726ac9 Merge pull request #109 from stephentyrone/swiftpm-directions
Add basic directions for adding a swiftpm dependency.
2020-04-15 11:44:55 -04:00
Stephen Canon c14381db8c Add basic directions for adding a swiftpm dependency. 2020-04-13 10:58:41 -04:00
Stephen Canon 8978159f21 Merge pull request #108 from stephentyrone/better-pown-float16
Somewhat better implementation of pow(x,n) for Float16.
2020-04-10 16:19:54 -04:00
Stephen Canon 59444343c4 Somewhat better implementation of pow(x,n) for Float16. 2020-04-10 16:16:25 -04:00
Stephen Canon ee082efdaf Fix bug for very large exponents pow(Float/Double, Int).
Just-added tests expose this issue, where the split of n into high/low parts could produce parts with different signs. If both x**high and x**low then overflow and underflow, the resulting computation would be 0*inf (or inf*0) and produce NaN instead of either zero or infinity.
2020-04-10 11:51:57 -04:00
Stephen Canon 6dc8bb4d17 Merge pull request #107 from stephentyrone/bugfix-pown
Bugfix integer power function for Float and Double with very large exponents.
2020-04-10 11:51:11 -04:00
Stephen Canon ff6a0ff2a5 Fix bug for very large exponents pow(Float/Double, Int).
Just-added tests expose this issue, where the split of n into high/low parts could produce parts with different signs. If both x**high and x**low then overflow and underflow, the resulting computation would be 0*inf (or inf*0) and produce NaN instead of either zero or infinity.
2020-04-10 11:46:22 -04:00
Stephen Canon 4db6faa3e7 Additional test coverage for pow with integer exponents.
These cases expose a bug in the current implementation; because the split of the exponent into high and low parts may produce numbers with different signs, if both parts overflow or underflow, we can end up with 0 * infinity = NaN, when the result should actually be either zero or infinity.
2020-04-10 10:11:19 -04:00
Stephen Canon 75e4116989 Additional test coverage for Float16 power with integer exponents. 2020-04-10 10:09:34 -04:00
Stephen Canon 9e1645a495 Additional test coverage for pow with integer exponents.
These cases expose a bug in the current implementation; because the split of the exponent into high and low parts may produce numbers with different signs, if both parts overflow or underflow, we can end up with 0 * infinity = NaN, when the result should actually be either zero or infinity.
2020-04-10 10:08:59 -04:00
Stephen Canon 29d25b62c5 Merge pull request #106 from stephentyrone/Float16-support
Add Real conformance for Float16.
2020-04-08 15:21:36 -04:00
Stephen Canon a35f5ba889 Add Real conformance for Float16. 2020-04-08 15:14:48 -04:00
Stephen Canon fc9ff1401d Merge pull request #104 from compnerd/swapfiles
gitignore: ignore vim swap files
2020-03-20 10:52:17 -04:00
Saleem Abdulrasool 33d10c02cd gitignore: ignore vim swap files 2020-03-13 13:02:38 -07:00
Stephen Canon 5dfc460876 Merge pull request #97 from stephentyrone/prefix-modules
Enable name lookup for modules by suffixing `Module` when needed to break ambiguity.

In particular, the following module renames are applied:

- Real -> RealModule
- Complex -> ComplexModule

This is a source-breaking change, if you currently directly import these modules. (sorry!)
The fix is to either import Numerics instead, or to use the new, suffixed, names. The good news is that fixing this should require only a straightforward search-and-replace for anyone affected.
2020-02-21 09:26:16 -05:00
Stephen Canon 014ce562a4 Update README.md 2020-02-21 09:22:40 -05:00
Stephen Canon 9dba38cc1a Update README.md 2020-02-21 09:22:40 -05:00
Stephen Canon 0fa2cd458e Update README.md 2020-02-21 09:22:40 -05:00
Stephen Canon be3d09ab26 Update README.md 2020-02-21 09:22:40 -05:00
Stephen Canon ba4469d3fd Update README.md 2020-02-21 09:22:40 -05:00
Stephen Canon 6951647e4c Update README.md 2020-02-21 09:22:40 -05:00
Stephen Canon a7c141e818 Update README.md 2020-02-21 09:22:40 -05:00
Stephen Canon 76954c06a7 Back to trailing 'Module' 2020-02-21 09:22:40 -05:00
Stephen Canon 4352c3a6a1 Put an underscore between the module prefix and name.
Ideally we'd be able to use Numerics.Module instead of underscore, but we can't always get what we want.
2020-02-21 09:22:40 -05:00
Stephen Canon 43052f0819 Prefix modules with "Numerics"; use underscored prefix for NumericsShims. 2020-02-21 09:22:40 -05:00
Stephen Canon 119377cc49 Merge pull request #99 from stephentyrone/algebraicField-should-be-signedNumeric
AlgebraicField should conform to SignedNumeric, not just Numeric.
2020-01-24 10:46:15 -05:00
Stephen Canon 016cd6a2fc AlgebraicField should conform to SignedNumeric, not just Numeric.
Because a field necessarily has additive inverses, SignedNumeric conformance is appropriate. (SignedNumeric is poorly named; it doesn't actually mean that a type has a "sign", only that there's a negation operation).
2020-01-24 10:42:11 -05:00
53 changed files with 3366 additions and 462 deletions

No files matched your search

-15
View File
@@ -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
+1
View File
@@ -4,3 +4,4 @@
/Packages
/*.xcodeproj
/.swiftpm
.*.sw?
-5
View File
@@ -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>
+33
View File
@@ -0,0 +1,33 @@
#[[
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)
if(BUILD_TESTING)
add_subdirectory(Tests)
endif()
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)
+19 -10
View File
@@ -13,21 +13,30 @@
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"]),
.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")
]
)
+99 -22
View File
@@ -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.
To propose a new feature for an existing module:
### How 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.
+16
View File
@@ -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,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
import Real
import RealModule
// MARK: - Additive structure
extension Complex: AdditiveArithmetic {
@@ -52,13 +52,31 @@ extension Complex: AdditiveArithmetic {
// and turn these into operators if/when we have it.
// (https://github.com/apple/swift-numerics/issues/12)
extension Complex {
/// `self` scaled by `a`.
@usableFromInline @_transparent
internal func multiplied(by a: RealType) -> Complex {
// This can be viewed in two different ways, which are mathematically
// equivalent: either we are computing `self * Complex(a)` (i.e.
// converting `a` to be a complex value, and then using the complex
// multiplication) or we are using the scalar product of the vector
// space structure: `Complex(a*real, a*imaginary)`.
//
// Although these two interpretations are _mathematically_ equivalent,
// they will generate different representations of the point at
// infinity in general. For example, suppose `self` is represented by
// `(infinity, 0)`. Then `self * Complex(1)` would evaluate as
// `(1*infinity - 0*0, 0*infinity + 1*0) = (infinity, nan)`, but
// the vector space interpretation produces `(infinity, 0)`. This does
// not matter much, because these are two representations of the same
// semantic value, but note that one requires four multiplies and two
// additions, while the one we use requires only two real multiplications.
Complex(x*a, y*a)
}
/// `self` unscaled by `a`.
@usableFromInline @_transparent
internal func divided(by a: RealType) -> Complex {
// See implementation notes for `multiplied` above.
Complex(x/a, y/a)
}
}
@@ -126,8 +144,8 @@ extension Complex: AlgebraicField {
/// A normalized complex number with the same phase as this value.
///
/// If such a value cannot be produced (because the phase of zero and infinity is undefined),
/// `nil` is returned.
/// If such a value cannot be produced (because the phase of zero and
/// infinity is undefined), `nil` is returned.
@inlinable
public var normalized: Complex? {
if length.isNormal {
@@ -139,16 +157,18 @@ extension Complex: AlgebraicField {
return self.divided(by: magnitude).normalized
}
/// The reciprocal of this value, if it can be computed without undue overflow or underflow.
/// The reciprocal of this value, if it can be computed without undue
/// overflow or underflow.
///
/// If z.reciprocal is non-nil, you can safely replace division by z with multiplication by this value. It is
/// not advantageous to do this for an isolated division, but if you are dividing many values by a single
/// denominator, this will often be a significant performance win.
/// If z.reciprocal is non-nil, you can safely replace division by z with
/// multiplication by this value. It is not advantageous to do this for an
/// isolated division, but if you are dividing many values by a single
/// denominator, this may sometimes be a significant performance win.
///
/// Typical use looks like this:
/// A typical use case looks something like this:
/// ```
/// func divide<T: Real>(data: [Complex<T>], by divisor: Complex<T>) -> [Complex<T>] {
/// // If divisor is well-scaled, use multiply by reciprocal.
/// // If divisor is well-scaled, multiply by reciprocal.
/// if let recip = divisor.reciprocal {
/// return data.map { $0 * recip }
/// }
@@ -156,6 +176,12 @@ extension Complex: AlgebraicField {
/// return data.map { $0 / divisor }
/// }
/// ```
///
/// Error Bounds:
///
/// Unlike real types, when working with complex types, multiplying by the
/// reciprocal instead of dividing cannot change the result. If the
/// reciprocal is non-nil, the two computations are always equivalent.
@inlinable
public var reciprocal: Complex? {
let recip = 1/self
@@ -165,5 +191,3 @@ extension Complex: AlgebraicField {
return nil
}
}
extension Complex: SignedNumeric {}
+22
View File
@@ -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)
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
import Real
import RealModule
/// A complex number represented by real and imaginary parts.
///
@@ -163,9 +163,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 +180,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 +196,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 +211,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 +243,8 @@ extension Complex {
/// This is mainly useful for interoperation with other languages, where
/// you may want to reduce each equivalence class to a single representative
/// before passing across language boundaries, but it may also be useful
/// for some serialization tasks. It's also a useful implementation detail for
/// some primitive operations.
/// for some serialization tasks. It's also a useful implementation detail
/// for some primitive operations.
@_transparent
public var canonicalized: Self {
if isZero { return .zero }
@@ -491,7 +494,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,475 @@
//===--- 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
@inlinable
public static func pow(_ z: Complex, _ w: Complex) -> Complex {
return exp(w * log(z))
}
@inlinable
public static func pow(_ 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).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 `AlgebraicField` (hence also `AdditiveArithmetic` and `Numeric`).
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.
+27
View File
@@ -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)
+2 -2
View File
@@ -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
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
/// A type modeling an algebraic [field]. Refines the `Numeric` protocol,
/// A type modeling an algebraic [field]. Refines the `SignedNumeric` protocol,
/// adding division.
///
/// A field is a set on which addition, subtraction, multiplication, and
@@ -40,29 +40,54 @@
/// See Also:
/// -
/// - Real
/// - SignedNumeric
/// - Numeric
/// - AdditiveArithmetic
///
/// [field]: https://en.wikipedia.org/wiki/Field_(mathematics)
public protocol AlgebraicField: Numeric {
public protocol AlgebraicField: SignedNumeric {
/// Replaces a with the (approximate) quotient `a/b`.
static func /=(a: inout Self, b: Self)
/// The (approximate) quotient `a/b`.
static func /(a: Self, b: Self) -> Self
/// The (approximate) reciprocal (multiplicative inverse) of this number,
/// if it is representable.
///
/// If reciprocal is non-nil, you can replace division by self with
/// multiplication by reciprocal and either get exact the same result
/// (for finite fields) or approximately the same result up to a typical
/// rounding error (for floating-point formats).
/// If self is zero and the type has no representation for infinity (as
/// in a typical finite field implementation), or if a reciprocal would
/// overflow or underflow such that it cannot be accurately represented,
/// the result is nil.
///
/// If self is zero, or if a reciprocal would overflow or underflow such
/// that it cannot be accurately represented, the result is nil. Note that
/// `.zero.reciprocal`, somewhat surprisingly, is *not* nil for `Real` or
/// `Complex` types, because these types have an `.infinity` value that
/// acts as the reciprocal of `.zero`.
/// Note that `.zero.reciprocal`, somewhat surprisingly, is *not* nil
/// for `Real` or `Complex` types, because these types have an
/// `.infinity` value that acts as the reciprocal of `.zero`.
///
/// If `x.reciprocal` is non-nil, you may be able to replace division by `x`
/// with multiplication by this value. It is not advantageous to do this
/// for an isolated division unless it is a compile-time constant visible
/// to the compiler, but if you are dividing many values by a single
/// denominator, this will often be a significant performance win.
///
/// Note that this will slightly perturb results for some fields with
/// approximate arithmetic, such as real types--using a normal division
/// is generally more accurate--but no catastrophic loss of accuracy will
/// result. For fields with exact arithmetic, or for the Complex types,
/// the results are identical.
///
/// A typical use case looks something like this:
/// ```
/// func divide<T: AlgebraicField>(data: [T], by divisor: T) -> [T] {
/// // If divisor is well-scaled, multiply by reciprocal.
/// if let recip = divisor.reciprocal {
/// return data.map { $0 * recip }
/// }
/// // Fallback on using division.
/// return data.map { $0 / divisor }
/// }
/// ```
var reciprocal: Self? { get }
}
@@ -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)
}
}
+28
View File
@@ -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)
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
import NumericsShims
import _NumericsShims
extension Double: Real {
@_transparent
@@ -158,16 +158,40 @@ extension Double: Real {
// 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) }
// Otherwise, n is too large to losslessly represent as Double, so we
// just split it into two parts, high and low. This is always exact,
// so the only source of error is pow itself and the multiplication.
// 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:
//
// mask constant is spelled in this funny way because if we just anded
// with the hex value, we'd get a compile error on 32b platforms, even
// though this whole branch is dead code on 32b.
let mask = Int(truncatingIfNeeded: 0x1f_ffff_ffff_ffff as UInt64)
let low = n & mask
let high = n - low
// 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))
}
@@ -194,4 +218,9 @@ extension Double: Real {
return libm_lgamma(x, &dontCare)
}
#endif
@_transparent
public static func _mulAdd(_ a: Double, _ b: Double, _ c: Double) -> Double {
_numerics_muladd(a, b, c)
}
}
@@ -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
/// ```
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
import NumericsShims
import _NumericsShims
extension Float: Real {
@_transparent
@@ -150,12 +150,21 @@ extension Float: Real {
// 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. Mask the low 24
// bits of n, get pow with that exponent (this contains the parity),
// then get pow with the rest (this may round, but if it does we've
// saturated anyway, so it doesn't matter).
let low = n & 0xffffff
let high = n - low
// 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))
}
@@ -182,4 +191,9 @@ extension Float: Real {
return libm_lgammaf(x, &dontCare)
}
#endif
@_transparent
public static func _mulAdd(_ a: Float, _ b: Float, _ c: Float) -> Float {
_numerics_muladdf(a, b, c)
}
}
+343
View File
@@ -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
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
import NumericsShims
import _NumericsShims
// Restrict extension to platforms for which Float80 exists.
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
@@ -1,8 +1,8 @@
# 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
@@ -28,12 +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 `Numeric`, adding the `/` and `/=` operators and a `reciprocal` property.
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:
@@ -68,7 +69,7 @@ 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
@@ -11,11 +11,12 @@
/// A type that models the real numbers.
///
/// Types conforming to this protocol provide the arithmetic and utility operations defined by
/// the `FloatingPoint` protocol, and provide all of the math functions defined by the
/// `ElementaryFunctions` and `RealFunctions` protocols. This protocol does not
/// add any additional conformances itself, but is very useful as a protocol against which to
/// write generic code. For example, we can naturally write a generic version of the a sigmoid
/// Types conforming to this protocol provide the arithmetic and utility
/// operations defined by the `FloatingPoint` protocol, and provide all of the
/// math functions defined by the `ElementaryFunctions` and `RealFunctions`
/// protocols. This protocol does not add any additional conformances itself,
/// but is very useful as a protocol against which to write generic code. For
/// example, we can naturally write a generic implementation of a sigmoid
/// function:
/// ```
/// func sigmoid<T: Real>(_ x: T) -> T {
@@ -34,12 +35,24 @@ public protocol Real: FloatingPoint, RealFunctions, AlgebraicField {
// it does allow us to default the implementation of a few operations,
// and also provides `signGamma`.
extension Real {
// Most math libraries do not provide exp10, so we need a default implementation.
// Most math libraries do not provide exp10, so we need a default
// implementation.
@_transparent
public static func exp10(_ x: Self) -> Self {
return pow(10, x)
}
/// 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.
@@ -76,11 +89,63 @@ extension Real {
}
#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
@@ -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
}
+14
View File
@@ -0,0 +1,14 @@
#[[
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)
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"
@@ -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
@@ -382,20 +382,18 @@ 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).
@@ -0,0 +1,3 @@
module _NumericsShims {
header "_NumericsShims.h"
}
+21
View File
@@ -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)
+31
View File
@@ -0,0 +1,31 @@
//===--- 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 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
}
+51
View File
@@ -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, watchOS 14.0, tvOS 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)!
}
}
+24
View File
@@ -0,0 +1,24 @@
#[[
This source file is part of the Swift Numerics open source project
Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
#]]
find_package(dispatch CONFIG QUIET)
find_package(Foundation CONFIG QUIET)
find_package(XCTest CONFIG QUIET)
add_subdirectory(ComplexTests)
add_subdirectory(RealTests)
add_executable(SwiftNumericsTestRunner
WindowsMain.swift)
target_link_libraries(SwiftNumericsTestRunner PRIVATE
ComplexTests
RealTests)
add_test(NAME SwiftNumericsTestRunner
COMMAND SwiftNumericsTestRunner)
@@ -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)
}
}
+3 -5
View File
@@ -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
+25
View File
@@ -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 -2
View File
@@ -10,8 +10,8 @@
//===----------------------------------------------------------------------===//
import XCTest
import Complex
import Real
import ComplexModule
import RealModule
final class PropertyTests: XCTestCase {
+108
View File
@@ -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
+108
View File
@@ -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
@@ -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
}
+20
View File
@@ -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)
@@ -10,7 +10,78 @@
//===----------------------------------------------------------------------===//
import XCTest
import Real
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() {
@@ -59,6 +130,15 @@ internal extension Real where Self: BinaryFloatingPoint {
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, watchOS 14.0, tvOS 7.0, *) {
Float16.elementaryFunctionChecks()
Float16.realFunctionChecks()
}
}
#endif
func testFloat() {
Float.elementaryFunctionChecks()
Float.realFunctionChecks()
+104 -32
View File
@@ -10,10 +10,14 @@
//===----------------------------------------------------------------------===//
import XCTest
import Real
import RealModule
import _TestSupport
internal extension Real where Self: BinaryFloatingPoint {
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.
@@ -27,12 +31,85 @@ internal extension Real where Self: BinaryFloatingPoint {
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.
@@ -52,18 +129,6 @@ extension Float {
assertClose(-7.0064924138100205091278464932003585e-46, Float.pow(-d, 1744361943))
assertClose( 7.0064919961905290625123586120258840e-46, Float.pow(-d, 1744361944))
assertClose(-7.0064915785710625079583096856510544e-46, Float.pow(-d, 1744361945))
// max/min exponents, these always saturate, but this will reveal
// errors in some implementations that one could try.
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))
}
}
@@ -72,6 +137,7 @@ extension Double {
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.
@@ -80,12 +146,21 @@ extension Double {
assertClose(-0.3678794411714422603312898889458068, Double.pow(-d, 0x20000000000001))
assertClose(-2.7182818284590456880451484776630468, Double.pow(-d, -0x20000000000001))
// Exponents close to overflow boundary.
assertClose( 1.7976931348623151738531864721534215e308, Double.pow(-u, 3196577161300664268))
assertClose(-1.7976931348623155730212483790972209e308, Double.pow(-u, 3196577161300664269))
assertClose( 1.7976931348623159721893102860411089e308, Double.pow(-u, 3196577161300664270))
assertClose( 1.7976931348623157075547244136070910e308, Double.pow(-d, -6393154322601327474))
assertClose(-1.7976931348623159071387553670790721e308, Double.pow(-d, -6393154322601327475))
assertClose( 1.7976931348623161067227863205510754e308, Double.pow(-d, -6393154322601327476))
#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))
@@ -93,23 +168,20 @@ extension Double {
assertClose(-2.4703282292062332640976590913373022e-324, Double.pow(-d, 6711563375777760775))
assertClose( 2.4703282292062329898361312467121758e-324, Double.pow(-d, 6711563375777760776))
assertClose(-2.4703282292062327155746034020870799e-324, Double.pow(-d, 6711563375777760777))
// max/min exponents, these always saturate, but this will reveal
// errors in some implementations that one could try.
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))
#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, watchOS 14.0, tvOS 7.0, *) {
Float16.testIntegerExponent()
}
}
#endif
func testFloat() {
Float.testIntegerExponent()
}
-83
View File
@@ -1,83 +0,0 @@
//===--- RealTestSupport.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
@discardableResult
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
}
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
))
}
+109
View File
@@ -0,0 +1,109 @@
//===--- WindowsMain.swift ------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#if os(Windows)
import XCTest
@testable
import RealTests
@testable
import ComplexTests
extension ComplexTests.ApproximateEqualityTests {
static var all = testCase([
("testFloat", ComplexTests.ApproximateEqualityTests.testFloat),
("testDouble", ComplexTests.ApproximateEqualityTests.testDouble),
])
}
extension RealTests.ApproximateEqualityTests {
static var all = testCase([
("testFloat", RealTests.ApproximateEqualityTests.testFloat),
("testDouble", RealTests.ApproximateEqualityTests.testDouble),
])
}
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
extension ElementaryFunctionChecks {
static var all = testCase([
("testFloat16", ElementaryFunctionChecks.testFloat16),
("testFloat", ElementaryFunctionChecks.testFloat),
("testDouble", ElementaryFunctionChecks.testDouble),
])
}
extension IntegerExponentTests {
static var all = testCase([
("testFloat16", IntegerExponentTests.testFloat16),
("testFloat", IntegerExponentTests.testFloat),
("testDouble", IntegerExponentTests.testDouble),
])
}
#else
extension ElementaryFunctionChecks {
static var all = testCase([
("testFloat", ElementaryFunctionChecks.testFloat),
("testDouble", ElementaryFunctionChecks.testDouble),
])
}
extension IntegerExponentTests {
static var all = testCase([
("testFloat", IntegerExponentTests.testFloat),
("testDouble", IntegerExponentTests.testDouble),
])
}
#endif
extension ArithmeticTests {
static var all = testCase([
("testPolar", ArithmeticTests.testPolar),
("testBaudinSmith", ArithmeticTests.testBaudinSmith),
("testDivisionByZero", ArithmeticTests.testDivisionByZero),
])
}
extension PropertyTests {
static var all = testCase([
("testProperties", PropertyTests.testProperties),
("testEquatableHashable", PropertyTests.testEquatableHashable),
("testCodable", PropertyTests.testCodable),
])
}
var testCases = [
ComplexTests.ApproximateEqualityTests.all,
RealTests.ApproximateEqualityTests.all,
ElementaryFunctionChecks.all,
IntegerExponentTests.all,
ArithmeticTests.all,
PropertyTests.all,
]
#if swift(>=5.3) && canImport(_Differentiation)
extension DifferentiableTests {
static var all = testCase([
("testComponentGetter", DifferentiableTests.testComponentGetter),
("testInitializer", DifferentiableTests.testInitializer),
("testConjugate", DifferentiableTests.testConjugate),
("testArithmetics", DifferentiableTests.testArithmetics),
])
}
testCases += [
DifferentiableTests.all
]
#endif
XCTMain(testCases)
#endif
+88
View File
@@ -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()