117 Commits
Author SHA1 Message Date
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 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
Stephen Canon a2aa24d236 Merge pull request #96 from benrimmington/complex-unkeyed
[Complex] Encode and decode using unkeyedContainer
2020-01-22 13:43:51 -05:00
Ben Rimmington eda432142d [Complex] Encode and decode using unkeyedContainer 2020-01-22 18:34:20 +00:00
Stephen Canon 7bd2909875 Merge pull request #91 from apple/FieldProtocol
Introduce AlgebraicField protocol
2020-01-20 13:35:59 -05:00
Stephen Canon 323542cba1 Add short notes to README docs on AlgebraicField. 2020-01-19 16:06:31 -05:00
Stephen Canon 98f3d25fe8 Rename Field -> AlgebraicField
We might walk this back in the future, but for the short-term let's avoid stomping on the generic term "Field".
2020-01-19 15:53:35 -05:00
Stephen Canon f3e1e15312 Merge pull request #93 from stephentyrone/Euclidean
s/euclidean/Euclidean/
2020-01-16 11:13:16 -05:00
Stephen Canon 8cbda03867 s/euclidean/Euclidean/ 2020-01-16 11:12:46 -05:00
Stephen Canon b6839260cb Add some clarification to documentation of .reciprocal. 2020-01-16 11:11:56 -05:00
Stephen Canon 1879299216 Avoid shadowing function argument by using a different name for local var. 2020-01-13 20:56:48 -05:00
Stephen Canon 53af148f0f Introduce Field protocol
For now, this mostly allows one to write code generic over Real and Complex types. TBD whether it should also include finite fields, or be restricted to characteristic-zero. Also bikeshedding to be done on exactly what operations should fall into this protocol and what it should be named. This is just to get discussion started.
2020-01-13 16:19:19 -05:00
Stephen Canon 2c12891617 Merge pull request #87 from stephentyrone/cleanup-real-conformances
Split conformance of Float, Double, Float80 to Real out
2019-12-27 13:42:01 -08:00
Stephen Canon f25a870cec Merge pull request #86 from stephentyrone/real-test-cleanup
Refactor RealTests
2019-12-27 13:41:33 -08:00
Stephen Canon 3d637e1302 Split conformance of Float, Double, Float80 to Real out into separate files.
Also reformat these files to be more closely in line with Swift conventions.
2019-12-27 16:39:26 -05:00
Stephen Canon b7e48c538c Refactor RealTests
Redesign and rename sanityCheck to assertClose; basic function is the same, but the implementation is a bit more straightforward and it now reports an accurate ulp error and can track maximum error if you want (we want this for some use cases).

Also move the basic sanity checks into one file and the tests that more thoroughly excercise a single function into their own files.
2019-12-27 16:35:41 -05:00
Stephen Canon 7ff707f6f8 Merge pull request #83 from stephentyrone/pown
Initial pass at pow(Self, Int) for Float and Double
2019-11-29 23:13:19 -05:00
Stephen Canon de5399615c Additional test coverage of saturating values.
Also skip out of tests that won't compile and wouldn't make sense anyway on 32b systems.
2019-11-29 23:11:15 -05:00
Stephen Canon f7842a76db Capitalization search/replace-o 2019-11-29 23:00:45 -05:00
Stephen Canon 5bf2f828ef Initial pass at implementing pow(Self,Int) with desired semantics.
We don't need to do anything special for Float80, but Float and Double require some handholding because Int values are not always representable.
2019-11-29 22:56:14 -05:00
Stephen Canon 65aac0be46 Add test cases to stress pow(_:Float/Double,:Int)
These are the hardest cases to get right; most of the fail at present.

Also some improvements to sanityCheck to handle negative values correctly and treat infinity as the next binade up (which isn't ideal for general use, but is good for this sort of rough testing.)
2019-11-29 22:54:03 -05:00
Stephen Canon 55f33b7769 Merge pull request #81 from stephentyrone/lgamma-shims-linux
Add inline decls of lgamma_r and friends on Linux, too.
2019-11-22 09:55:28 -05:00
Stephen Canon 5e978d85a2 Add inline decls of lgamma_r and friends on Linux, too. 2019-11-22 09:47:36 -05:00
45 changed files with 2491 additions and 564 deletions

No files matched your search

+1
View File
@@ -4,3 +4,4 @@
/Packages
/*.xcodeproj
/.swiftpm
.*.sw?
+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)
+10 -8
View File
@@ -15,19 +15,21 @@ 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"]),
.library(name: "RealModule", targets: ["RealModule"]),
],
dependencies: [
],
targets: [
.target(name: "Complex", dependencies: ["Real"]),
.target(name: "Numerics", dependencies: ["Complex", "Real"]),
.target(name: "NumericsShims", dependencies: []),
.target(name: "Real", dependencies: ["NumericsShims"]),
.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"]),
.target(name: "_NumericsShims", dependencies: []),
.target(name: "_TestSupport", dependencies: ["Numerics"]),
.testTarget(name: "ComplexTests", dependencies: ["_TestSupport"]),
.testTarget(name: "RealTests", dependencies: ["_TestSupport"]),
]
)
+39 -6
View File
@@ -9,9 +9,9 @@ These modules fall broadly into two categories:
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.
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 Numerics modules are fine-grained; if you need support for Complex numbers, you can import ComplexModule¹ without pulling in everything else in the library as well:
```swift
import Complex
import ComplexModule
let z = Complex<Double>.i
```
@@ -28,7 +28,21 @@ Future expansion may assume the availability of other standard interfaces such a
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
## Using Swift Numerics in your project
To use Swift Numerics in a SwiftPM project, add the following line to the dependencies in your `Package.swift` file:
```swift
.package(url: "https://github.com/apple/swift-numerics", from: "0.0.5"),
```
add `Numerics` as a dependency for your target:
```swift
.target(name: "MyTarget", dependencies: [
.product(name: "Numerics", package: "swift-numerics"),
"AnotherModule"
]),
```
and finally, add `import Numerics` in your source code.
## Contributing to Swift Numerics
Swift Numerics is a standalone library separate from the core Swift project.
In practice, it will act as a staging ground for some APIs that may eventually be incorporated into the Swift Standard Library, and when that happens such changes will be proposed to the Swift Standard Library using the established evolution process of the Swift project.
@@ -51,8 +65,8 @@ 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)
## 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)
@@ -60,4 +74,23 @@ Questions about how to use Swift Numerics modules, or issues that are not clearl
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)
## Notes
¹ Swift is currently unable to use the fully-qualified name for types when a type and module have the same name (discussion here: https://forums.swift.org/t/pitch-fully-qualified-name-syntax/28482).
This would prevent users of Swift Numerics who don't need generic types from doing things like:
```swift
import Complex
// I know I only ever want Complex<Double>, so I shouldn't need the generic parameter.
typealias Complex = Complex.Complex<Double> // doesn't work, because name lookup fails.
```
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, and users may want to define their own `Real` type (and possibly re-export the `Real` module), so the suffix is also applied there.
New modules have to evaluate this decision carefully, but can err on the side of adding the suffix.
It's expected that most users will simply `import Numerics`, so this isn't an issue for them.
+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,6 +9,8 @@
//
//===----------------------------------------------------------------------===//
import RealModule
// MARK: - Additive structure
extension Complex: AdditiveArithmetic {
@_transparent
@@ -62,7 +64,7 @@ extension Complex {
}
// MARK: - Multiplicative structure
extension Complex: Numeric {
extension Complex: AlgebraicField {
@_transparent
public static func *(z: Complex, w: Complex) -> Complex {
return Complex(z.x*w.x - z.y*w.y, z.x*w.y + z.y*w.x)
@@ -163,5 +165,3 @@ extension Complex: Numeric {
return nil
}
}
extension Complex: SignedNumeric {}
+21
View File
@@ -0,0 +1,21 @@
#[[
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)
set_target_properties(ComplexModule PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
target_link_libraries(ComplexModule PUBLIC
RealModule)
_install_target(ComplexModule)
set_property(GLOBAL APPEND PROPERTY SWIFT_NUMERICS_EXPORTS ComplexModule)
@@ -2,14 +2,14 @@
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import Real
import RealModule
/// A complex number represented by real and imaginary parts.
///
@@ -208,7 +208,7 @@ 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`
/// If you need the Euclidean norm (a.k.a. 2-norm) use the `length` or `lengthSquared`
/// properties instead.
///
/// Edge cases:
@@ -344,11 +344,23 @@ extension Complex: Hashable {
}
// MARK: - Conformance to Codable
// The synthesized conformance works correction for this protocol, unlike
// Hashable and Equatable; all we need to do is specify that we conform.
// FloatingPoint does not refine Codable, so this is a conditional conformance.
extension Complex: Encodable where RealType: Encodable { }
extension Complex: Decodable where RealType: Decodable { }
extension Complex: Decodable where RealType: Decodable {
public init(from decoder: Decoder) throws {
var unkeyedContainer = try decoder.unkeyedContainer()
let x = try unkeyedContainer.decode(RealType.self)
let y = try unkeyedContainer.decode(RealType.self)
self.init(x, y)
}
}
extension Complex: Encodable where RealType: Encodable {
public func encode(to encoder: Encoder) throws {
var unkeyedContainer = encoder.unkeyedContainer()
try unkeyedContainer.encode(x)
try unkeyedContainer.encode(y)
}
}
// MARK: - Formatting
extension Complex: CustomStringConvertible {
@@ -369,7 +381,7 @@ extension Complex: CustomDebugStringConvertible {
// MARK: - Operations for working with polar form
extension Complex {
/// The euclidean norm (a.k.a. 2-norm, `sqrt(real*real + imaginary*imaginary)`).
/// The Euclidean norm (a.k.a. 2-norm, `sqrt(real*real + imaginary*imaginary)`).
///
/// This property takes care to avoid spurious over- or underflow in
/// this computation. For example:
@@ -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
@@ -2,15 +2,15 @@
This module provides a `Complex` number type generic over an underlying `RealType`:
```swift
1> import Complex
1> import ComplexModule
2> let z = Complex(1,1) // z = 1 + i
```
This module provides approximate feature parity and memory layout compatibility with C, Fortran, and C++ complex types (although the importer cannot map the types for you, buffers may be reinterpreted to shim API defined in other languages).
The usual arithmetic operators are provided for Complex numbers, as well as conversion to and from polar coordinates and many useful properties, plus conformances to the obvious usual protocols: `Equatable`, `Hashable`, `Codable` (if the underlying `RealType` is), and `Numeric` (hence also `AdditiveArithmetic`).
The usual arithmetic operators are provided for Complex numbers, as well as conversion to and from polar coordinates and many useful properties, plus conformances to the obvious usual protocols: `Equatable`, `Hashable`, `Codable` (if the underlying `RealType` is), and `AlgebraicField` (hence also `AdditiveArithmetic` and `SignedNumeric`).
### Dependencies:
- The `Real` module.
- `RealModule`.
## Design notes
@@ -60,7 +60,7 @@ Because of this, the ∞-norm is the obvious alternative; it gives the nicest AP
- The ∞-norm is heavily used in other computational libraries; for example, it is used by the `izamax` and `icamax` functions in BLAS.
The 2-norm still needs to be available, of course, because sometimes you need it.
This functionality is accessed via the `.length` and `.unsafeLengthSquared` properties.
This functionality is accessed via the `.length` and `.lengthSquared` properties.
### Accuracy of division and multiplication
This library attempts to provide robust division and multiplication operations, with small relative error in a complex norm. It is a non-goal to deliver small componentwise errors.
+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
-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
-222
View File
@@ -1,222 +0,0 @@
//===--- ScalarConformances.swift -----------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// In theory we might be able to get away with using @_silgen_name for these
// instead of NumericShims and remove a level of (source-only) indirection.
// However, at present if we do that we get a compiler crash when this module
// and the Swift platform module are both imported (<rdar://problem/53821031>).
import NumericsShims
// MARK: Float + Real
extension Float: Real {
@_transparent public static func cos(_ x: Float) -> Float { return libm_cosf(x) }
@_transparent public static func sin(_ x: Float) -> Float { return libm_sinf(x) }
@_transparent public static func tan(_ x: Float) -> Float { return libm_tanf(x) }
@_transparent public static func acos(_ x: Float) -> Float { return libm_acosf(x) }
@_transparent public static func asin(_ x: Float) -> Float { return libm_asinf(x) }
@_transparent public static func atan(_ x: Float) -> Float { return libm_atanf(x) }
@_transparent public static func cosh(_ x: Float) -> Float { return libm_coshf(x) }
@_transparent public static func sinh(_ x: Float) -> Float { return libm_sinhf(x) }
@_transparent public static func tanh(_ x: Float) -> Float { return libm_tanhf(x) }
@_transparent public static func acosh(_ x: Float) -> Float { return libm_acoshf(x) }
@_transparent public static func asinh(_ x: Float) -> Float { return libm_asinhf(x) }
@_transparent public static func atanh(_ x: Float) -> Float { return libm_atanhf(x) }
@_transparent public static func exp(_ x: Float) -> Float { return libm_expf(x) }
@_transparent public static func expMinusOne(_ x: Float) -> Float { return libm_expm1f(x) }
@_transparent public static func log(_ x: Float) -> Float { return libm_logf(x) }
@_transparent public static func log(onePlus x: Float) -> Float { return libm_log1pf(x) }
@_transparent public static func erf(_ x: Float) -> Float { return libm_erff(x) }
@_transparent public static func erfc(_ x: Float) -> Float { return libm_erfcf(x) }
@_transparent public static func exp2(_ x: Float) -> Float { return libm_exp2f(x) }
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
@_transparent public static func exp10(_ x: Float) -> Float { return libm_exp10f(x) }
#endif
@_transparent public static func hypot(_ x: Float, _ y: Float) -> Float { return libm_hypotf(x, y) }
@_transparent public static func gamma(_ x: Float) -> Float { return libm_tgammaf(x) }
@_transparent public static func log2(_ x: Float) -> Float { return libm_log2f(x) }
@_transparent public static func log10(_ x: Float) -> Float { return libm_log10f(x) }
@_transparent public static func pow(_ x: Float, _ y: Float) -> Float {
guard x >= 0 else { return .nan }
return libm_powf(x, y)
}
@_transparent public static func pow(_ x: Float, _ n: Int) -> Float {
// TODO: this implementation is not quite correct, because n may be
// rounded in conversion to Float. This only effects very extreme cases,
// so we'll leave it alone for now; however, it gets the sign wrong if
// it rounds an odd number to an even number, so we should fix it soon.
return libm_powf(x, Float(n))
}
@_transparent public static func root(_ x: Float, _ n: Int) -> Float {
guard x >= 0 || n % 2 != 0 else { return .nan }
// Workaround the issue mentioned below for the specific case of n = 3
// where we can fallback on cbrt.
if n == 3 { return libm_cbrtf(x) }
// TODO: this implementation is not quite correct, because either n or
// 1/n may be not be representable as Float.
return Float(signOf: x, magnitudeOf: libm_powf(x.magnitude, 1/Float(n)))
}
@_transparent public static func atan2(y: Float, x: Float) -> Float {
return libm_atan2f(y, x)
}
#if !os(Windows)
@_transparent public static func logGamma(_ x: Float) -> Float {
var dontCare: Int32 = 0
return libm_lgammaf(x, &dontCare)
}
#endif
}
// MARK: Double + Real
extension Double: Real {
@_transparent public static func cos(_ x: Double) -> Double { return libm_cos(x) }
@_transparent public static func sin(_ x: Double) -> Double { return libm_sin(x) }
@_transparent public static func tan(_ x: Double) -> Double { return libm_tan(x) }
@_transparent public static func acos(_ x: Double) -> Double { return libm_acos(x) }
@_transparent public static func asin(_ x: Double) -> Double { return libm_asin(x) }
@_transparent public static func atan(_ x: Double) -> Double { return libm_atan(x) }
@_transparent public static func cosh(_ x: Double) -> Double { return libm_cosh(x) }
@_transparent public static func sinh(_ x: Double) -> Double { return libm_sinh(x) }
@_transparent public static func tanh(_ x: Double) -> Double { return libm_tanh(x) }
@_transparent public static func acosh(_ x: Double) -> Double { return libm_acosh(x) }
@_transparent public static func asinh(_ x: Double) -> Double { return libm_asinh(x) }
@_transparent public static func atanh(_ x: Double) -> Double { return libm_atanh(x) }
@_transparent public static func exp(_ x: Double) -> Double { return libm_exp(x) }
@_transparent public static func expMinusOne(_ x: Double) -> Double { return libm_expm1(x) }
@_transparent public static func log(_ x: Double) -> Double { return libm_log(x) }
@_transparent public static func log(onePlus x: Double) -> Double { return libm_log1p(x) }
@_transparent public static func erf(_ x: Double) -> Double { return libm_erf(x) }
@_transparent public static func erfc(_ x: Double) -> Double { return libm_erfc(x) }
@_transparent public static func exp2(_ x: Double) -> Double { return libm_exp2(x) }
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
@_transparent public static func exp10(_ x: Double) -> Double { return libm_exp10(x) }
#endif
#if os(macOS) && arch(x86_64)
// Workaround for macOS bug (<rdar://problem/56844150>) where hypot can
// overflow for values very close to the overflow boundary of the naive
// algorithm. Since this is only for macOS, we can just unconditionally
// use Float80, which makes the implementation trivial.
public static func hypot(_ x: Double, _ y: Double) -> Double {
if x.isInfinite || y.isInfinite { return .infinity }
let x80 = Float80(x)
let y80 = Float80(y)
return Double(Float80.sqrt(x80*x80 + y80*y80))
}
#else
@_transparent public static func hypot(_ x: Double, _ y: Double) -> Double {
return libm_hypot(x, y)
}
#endif
@_transparent public static func gamma(_ x: Double) -> Double { return libm_tgamma(x) }
@_transparent public static func log2(_ x: Double) -> Double { return libm_log2(x) }
@_transparent public static func log10(_ x: Double) -> Double { return libm_log10(x) }
@_transparent public static func pow(_ x: Double, _ y: Double) -> Double {
guard x >= 0 else { return .nan }
return libm_pow(x, y)
}
@_transparent public static func pow(_ x: Double, _ n: Int) -> Double {
// TODO: this implementation is not quite correct, because n may be
// rounded in conversion to Double. This only effects very extreme cases,
// so we'll leave it alone for now; however, it gets the sign wrong if
// it rounds an odd number to an even number, so we should fix it soon.
return libm_pow(x, Double(n))
}
@_transparent public static func root(_ x: Double, _ n: Int) -> Double {
guard x >= 0 || n % 2 != 0 else { return .nan }
// Workaround the issue mentioned below for the specific case of n = 3
// where we can fallback on cbrt.
if n == 3 { return libm_cbrt(x) }
// TODO: this implementation is not quite correct, because either n or
// 1/n may be not be representable as Double.
return Double(signOf: x, magnitudeOf: libm_pow(x.magnitude, 1/Double(n)))
}
@_transparent public static func atan2(y: Double, x: Double) -> Double {
return libm_atan2(y, x)
}
#if !os(Windows)
@_transparent public static func logGamma(_ x: Double) -> Double {
var dontCare: Int32 = 0
return libm_lgamma(x, &dontCare)
}
#endif
}
// MARK: Float80 + Real
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
extension Float80: Real {
@_transparent public static func cos(_ x: Float80) -> Float80 { return libm_cosl(x) }
@_transparent public static func sin(_ x: Float80) -> Float80 { return libm_sinl(x) }
@_transparent public static func tan(_ x: Float80) -> Float80 { return libm_tanl(x) }
@_transparent public static func acos(_ x: Float80) -> Float80 { return libm_acosl(x) }
@_transparent public static func asin(_ x: Float80) -> Float80 { return libm_asinl(x) }
@_transparent public static func atan(_ x: Float80) -> Float80 { return libm_atanl(x) }
@_transparent public static func cosh(_ x: Float80) -> Float80 { return libm_coshl(x) }
@_transparent public static func sinh(_ x: Float80) -> Float80 { return libm_sinhl(x) }
@_transparent public static func tanh(_ x: Float80) -> Float80 { return libm_tanhl(x) }
@_transparent public static func acosh(_ x: Float80) -> Float80 { return libm_acoshl(x) }
@_transparent public static func asinh(_ x: Float80) -> Float80 { return libm_asinhl(x) }
@_transparent public static func atanh(_ x: Float80) -> Float80 { return libm_atanhl(x) }
@_transparent public static func exp(_ x: Float80) -> Float80 { return libm_expl(x) }
@_transparent public static func expMinusOne(_ x: Float80) -> Float80 { return libm_expm1l(x) }
@_transparent public static func log(_ x: Float80) -> Float80 { return libm_logl(x) }
@_transparent public static func log(onePlus x: Float80) -> Float80 { return libm_log1pl(x) }
@_transparent public static func erf(_ x: Float80) -> Float80 { return libm_erfl(x) }
@_transparent public static func erfc(_ x: Float80) -> Float80 { return libm_erfcl(x) }
@_transparent public static func exp2(_ x: Float80) -> Float80 { return libm_exp2l(x) }
@_transparent public static func hypot(_ x: Float80, _ y: Float80) -> Float80 { return libm_hypotl(x, y) }
@_transparent public static func gamma(_ x: Float80) -> Float80 { return libm_tgammal(x) }
@_transparent public static func log2(_ x: Float80) -> Float80 { return libm_log2l(x) }
@_transparent public static func log10(_ x: Float80) -> Float80 { return libm_log10l(x) }
@_transparent public static func pow(_ x: Float80, _ y: Float80) -> Float80 {
guard x >= 0 else { return .nan }
return libm_powl(x, y)
}
@_transparent public static func pow(_ x: Float80, _ n: Int) -> Float80 {
// TODO: this implementation is not quite correct, because n may be
// rounded in conversion to Float80. This only effects very extreme cases,
// so we'll leave it alone for now; however, it gets the sign wrong if
// it rounds an odd number to an even number, so we should fix it soon.
return libm_powl(x, Float80(n))
}
@_transparent public static func root(_ x: Float80, _ n: Int) -> Float80 {
guard x >= 0 || n % 2 != 0 else { return .nan }
// Workaround the issue mentioned below for the specific case of n = 3
// where we can fallback on cbrt.
if n == 3 { return libm_cbrtl(x) }
// TODO: this implementation is not quite correct, because either n or
// 1/n may be not be representable as Float80.
return Float80(signOf: x, magnitudeOf: libm_powl(x.magnitude, 1/Float80(n)))
}
@_transparent public static func atan2(y: Float80, x: Float80) -> Float80 {
return libm_atan2l(y, x)
}
#if !os(Windows)
@_transparent public static func logGamma(_ x: Float80) -> Float80 {
var dontCare: Int32 = 0
return libm_lgammal(x, &dontCare)
}
#endif
}
#endif
+86
View File
@@ -0,0 +1,86 @@
//===--- AlgebraicField.swift ---------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A type modeling an algebraic [field]. Refines the `SignedNumeric` protocol,
/// adding division.
///
/// A field is a set on which addition, subtraction, multiplication, and
/// division are defined, and behave basically like those operations on
/// the real numbers. More precisely, a field is a commutative group under
/// its addition, the non-zero elements of the field form a commutative
/// group under its multiplication, and the distributitve law holds.
///
/// Some common examples of fields include:
///
/// - the rational numbers
/// - the real numbers
/// - the complex numbers
/// - the integers modulo a prime
///
/// The most familiar example of a thing that is *not* a field is the integers.
/// This may be surprising, since integers seem to have addition, subtraction,
/// multiplication and division. Why don't they form a field?
///
/// Because integer multiplication does not form a group; it's commutative and
/// associative, but integers do not have multiplicative inverses.
/// I.e. if a is any integer other than 1 or -1, there is no integer b such
/// that a*b = 1. The existence of inverses is requried to form a field.
///
/// If a type `T` conforms to the `Real` protocol, then `T` and `Complex<T>`
/// both conform to `AlgebraicField`.
///
/// See Also:
/// -
/// - Real
/// - SignedNumeric
/// - Numeric
/// - AdditiveArithmetic
///
/// [field]: https://en.wikipedia.org/wiki/Field_(mathematics)
public protocol AlgebraicField: SignedNumeric {
static func /=(a: inout Self, b: Self)
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, 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`.
var reciprocal: Self? { get }
}
extension AlgebraicField {
@_transparent
public static func /(a: Self, b: Self) -> Self {
var result = a
result /= b
return result
}
/// Implementations should be *conservative* with the reciprocal property;
/// it is OK to return `nil` even in cases where a reciprocal could be
/// represented. For this reason, a default implementation that simply
/// always returns `nil` is correct, but conforming types should provide
/// a better implementation if possible.
public var reciprocal: Self? {
return nil
}
}
@@ -0,0 +1,241 @@
//===--- 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.
///
/// - 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:absoluteTolerance:relativeTolerance:)`
/// is __not__ _transitive_. Because of this, approximately equality is
/// __not an equivalence relation__, even when restricted to non-exceptional values.
///
/// - For any point `a`, the set of values that compare approximately equal to `a` is _convex_.
/// (Under the assumption that `norm` implements a valid norm, which cannot be checked
/// by this function.)
///
/// 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.
///
/// - 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: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, 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
}
}
+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(RealModule
AlgebraicField.swift
ApproximateEquality.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)
+226
View File
@@ -0,0 +1,226 @@
//===--- Double+Real.swift ------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import _NumericsShims
extension Double: Real {
@_transparent
public static func cos(_ x: Double) -> Double {
libm_cos(x)
}
@_transparent
public static func sin(_ x: Double) -> Double {
libm_sin(x)
}
@_transparent
public static func tan(_ x: Double) -> Double {
libm_tan(x)
}
@_transparent
public static func acos(_ x: Double) -> Double {
libm_acos(x)
}
@_transparent
public static func asin(_ x: Double) -> Double {
libm_asin(x)
}
@_transparent
public static func atan(_ x: Double) -> Double {
libm_atan(x)
}
@_transparent
public static func cosh(_ x: Double) -> Double {
libm_cosh(x)
}
@_transparent
public static func sinh(_ x: Double) -> Double {
libm_sinh(x)
}
@_transparent
public static func tanh(_ x: Double) -> Double {
libm_tanh(x)
}
@_transparent
public static func acosh(_ x: Double) -> Double {
libm_acosh(x)
}
@_transparent
public static func asinh(_ x: Double) -> Double {
libm_asinh(x)
}
@_transparent
public static func atanh(_ x: Double) -> Double {
libm_atanh(x)
}
@_transparent
public static func exp(_ x: Double) -> Double {
libm_exp(x)
}
@_transparent
public static func expMinusOne(_ x: Double) -> Double {
libm_expm1(x)
}
@_transparent
public static func log(_ x: Double) -> Double {
libm_log(x)
}
@_transparent
public static func log(onePlus x: Double) -> Double {
libm_log1p(x)
}
@_transparent
public static func erf(_ x: Double) -> Double {
libm_erf(x)
}
@_transparent
public static func erfc(_ x: Double) -> Double {
libm_erfc(x)
}
@_transparent
public static func exp2(_ x: Double) -> Double {
libm_exp2(x)
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
@_transparent
public static func exp10(_ x: Double) -> Double {
libm_exp10(x)
}
#endif
#if os(macOS) && arch(x86_64)
// Workaround for macOS bug (<rdar://problem/56844150>) where hypot can
// overflow for values very close to the overflow boundary of the naive
// algorithm. Since this is only for macOS, we can just unconditionally
// use Float80, which makes the implementation trivial.
public static func hypot(_ x: Double, _ y: Double) -> Double {
if x.isInfinite || y.isInfinite { return .infinity }
let x80 = Float80(x)
let y80 = Float80(y)
return Double(Float80.sqrt(x80*x80 + y80*y80))
}
#else
@_transparent
public static func hypot(_ x: Double, _ y: Double) -> Double {
libm_hypot(x, y)
}
#endif
@_transparent
public static func gamma(_ x: Double) -> Double {
libm_tgamma(x)
}
@_transparent
public static func log2(_ x: Double) -> Double {
libm_log2(x)
}
@_transparent
public static func log10(_ x: Double) -> Double {
libm_log10(x)
}
@_transparent
public static func pow(_ x: Double, _ y: Double) -> Double {
guard x >= 0 else { return .nan }
return libm_pow(x, y)
}
@_transparent
public static func pow(_ x: Double, _ n: Int) -> Double {
// If n is exactly representable as Double, we can just call pow:
// Note that all calls on a 32b platform go down this path.
if let y = Double(exactly: n) { return libm_pow(x, y) }
// n is not representable in Double, so we will split it into two parts,
// low and high, such that (high + low) = n, and use the identity:
//
// x**(high + low) = x**high * x**low.
//
// We put the high-order 32 bits into high, and the remaining 32 bits
// in low.
//
// The exact split isn't important; all we need is that both pieces get
// less than 53 bits (so that they are exact) and that they both have
// the same sign as n.
//
// This second point is a little bit subtle--why is
// it necessary? Consider what would happen if we took x = 2 and
// n = Int.min + Int(UInt32.max), and simply naively split n without
// taking care with the sign. We would end up computing:
//
// 2**n = 2**Int.min * 2**UInt32.max
//
// The first exponent is negative, the second positive, so the first term
// underflows to zero, and the second overflows to infinity, so the final
// result is NaN, when it should be zero. In order to avoid this
// situation, we make sure that high contains n rounded *towards zero*,
// rather than using simple two's-complement truncation (which rounds
// down).
let mask = Int(truncatingIfNeeded: UInt32.max)
let round = n < 0 ? mask : 0
// The addition and subtraction below cannot actually overflow (proof:
// round is positive if n is negative, and zero otherwise, so n + round
// is guaranteed to be representable, and n and high have the same sign,
// so n - high is also representable), but it's hard to tell the compiler
// that, so I'm using wrapping operations instead.
let high = (n &+ round) & ~mask
let low = n &- high
return libm_pow(x, Double(low)) * libm_pow(x, Double(high))
}
@_transparent
public static func root(_ x: Double, _ n: Int) -> Double {
guard x >= 0 || n % 2 != 0 else { return .nan }
// Workaround the issue mentioned below for the specific case of n = 3
// where we can fallback on cbrt.
if n == 3 { return libm_cbrt(x) }
// TODO: this implementation is not quite correct, because either n or
// 1/n may be not be representable as Double.
return Double(signOf: x, magnitudeOf: libm_pow(x.magnitude, 1/Double(n)))
}
@_transparent
public static func atan2(y: Double, x: Double) -> Double {
libm_atan2(y, x)
}
#if !os(Windows)
@_transparent
public static func logGamma(_ x: Double) -> Double {
var dontCare: Int32 = 0
return libm_lgamma(x, &dontCare)
}
#endif
@_transparent
public static func _mulAdd(_ a: Double, _ b: Double, _ c: Double) -> Double {
_numerics_muladd(a, b, c)
}
}
+199
View File
@@ -0,0 +1,199 @@
//===--- Float+Real.swift -------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import _NumericsShims
extension Float: Real {
@_transparent
public static func cos(_ x: Float) -> Float {
libm_cosf(x)
}
@_transparent
public static func sin(_ x: Float) -> Float {
libm_sinf(x)
}
@_transparent
public static func tan(_ x: Float) -> Float {
libm_tanf(x)
}
@_transparent
public static func acos(_ x: Float) -> Float {
libm_acosf(x)
}
@_transparent
public static func asin(_ x: Float) -> Float {
libm_asinf(x)
}
@_transparent
public static func atan(_ x: Float) -> Float {
libm_atanf(x)
}
@_transparent
public static func cosh(_ x: Float) -> Float {
libm_coshf(x)
}
@_transparent
public static func sinh(_ x: Float) -> Float {
libm_sinhf(x)
}
@_transparent
public static func tanh(_ x: Float) -> Float {
libm_tanhf(x)
}
@_transparent
public static func acosh(_ x: Float) -> Float {
libm_acoshf(x)
}
@_transparent
public static func asinh(_ x: Float) -> Float {
libm_asinhf(x)
}
@_transparent
public static func atanh(_ x: Float) -> Float {
libm_atanhf(x)
}
@_transparent
public static func exp(_ x: Float) -> Float {
libm_expf(x)
}
@_transparent
public static func expMinusOne(_ x: Float) -> Float {
libm_expm1f(x)
}
@_transparent
public static func log(_ x: Float) -> Float {
libm_logf(x)
}
@_transparent
public static func log(onePlus x: Float) -> Float {
libm_log1pf(x)
}
@_transparent
public static func erf(_ x: Float) -> Float {
libm_erff(x)
}
@_transparent
public static func erfc(_ x: Float) -> Float {
libm_erfcf(x)
}
@_transparent
public static func exp2(_ x: Float) -> Float {
libm_exp2f(x)
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
@_transparent
public static func exp10(_ x: Float) -> Float {
libm_exp10f(x)
}
#endif
@_transparent
public static func hypot(_ x: Float, _ y: Float) -> Float {
libm_hypotf(x, y)
}
@_transparent
public static func gamma(_ x: Float) -> Float {
libm_tgammaf(x)
}
@_transparent
public static func log2(_ x: Float) -> Float {
libm_log2f(x)
}
@_transparent
public static func log10(_ x: Float) -> Float {
libm_log10f(x)
}
@_transparent
public static func pow(_ x: Float, _ y: Float) -> Float {
guard x >= 0 else { return .nan }
return libm_powf(x, y)
}
@_transparent
public static func pow(_ x: Float, _ n: Int) -> Float {
// If n is exactly representable as Float, we can just call powf:
if let y = Float(exactly: n) {
return libm_powf(x, y)
}
// Otherwise, n is too large to losslessly represent as Float.
// The range of "interesting" n is -1488522191 ... 1744361944; outside
// of this range, all x != 1 overflow or underflow, so only the parity
// of x matters. We don't really care about the specific range at all,
// only that the bounds fit exactly into two Floats.
//
// We do, however, need to be careful that high and low both have the
// same sign as n (consult the Double implementation for details of why
// this matters), so we need to be a little bit careful constructing
// them.
//
// Unlike the Double implementation, when n is very large, high will
// get rounded here; that's OK because it does not change the sign or
// parity, which are the only two bits that matter for such large
// exponents in Float.
let mask = Int(truncatingIfNeeded: 0xffffff)
let round = n < 0 ? mask : 0
let high = (n &+ round) & ~mask
let low = n &- high
return libm_powf(x, Float(low)) * libm_powf(x, Float(high))
}
@_transparent
public static func root(_ x: Float, _ n: Int) -> Float {
guard x >= 0 || n % 2 != 0 else { return .nan }
// Workaround the issue mentioned below for the specific case of n = 3
// where we can fallback on cbrt.
if n == 3 { return libm_cbrtf(x) }
// TODO: this implementation is not quite correct, because either n or
// 1/n may be not be representable as Float.
return Float(signOf: x, magnitudeOf: libm_powf(x.magnitude, 1/Float(n)))
}
@_transparent
public static func atan2(y: Float, x: Float) -> Float {
libm_atan2f(y, x)
}
#if !os(Windows)
@_transparent
public static func logGamma(_ x: Float) -> Float {
var dontCare: Int32 = 0
return libm_lgammaf(x, &dontCare)
}
#endif
@_transparent
public static func _mulAdd(_ a: Float, _ b: Float, _ c: Float) -> Float {
_numerics_muladdf(a, b, c)
}
}
+176
View File
@@ -0,0 +1,176 @@
//===--- 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
//
//===----------------------------------------------------------------------===//
#if swift(>=5.3)
import _NumericsShims
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, *)
@available(macOS, unavailable)
@available(macCatalyst, unavailable)
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
+168
View File
@@ -0,0 +1,168 @@
//===--- Float80+Real.swift -----------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import _NumericsShims
// Restrict extension to platforms for which Float80 exists.
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
extension Float80: Real {
@_transparent
public static func cos(_ x: Float80) -> Float80 {
libm_cosl(x)
}
@_transparent
public static func sin(_ x: Float80) -> Float80 {
libm_sinl(x)
}
@_transparent
public static func tan(_ x: Float80) -> Float80 {
libm_tanl(x)
}
@_transparent
public static func acos(_ x: Float80) -> Float80 {
libm_acosl(x)
}
@_transparent
public static func asin(_ x: Float80) -> Float80 {
libm_asinl(x)
}
@_transparent
public static func atan(_ x: Float80) -> Float80 {
libm_atanl(x)
}
@_transparent
public static func cosh(_ x: Float80) -> Float80 {
libm_coshl(x)
}
@_transparent
public static func sinh(_ x: Float80) -> Float80 {
libm_sinhl(x)
}
@_transparent
public static func tanh(_ x: Float80) -> Float80 {
libm_tanhl(x)
}
@_transparent
public static func acosh(_ x: Float80) -> Float80 {
libm_acoshl(x)
}
@_transparent
public static func asinh(_ x: Float80) -> Float80 {
libm_asinhl(x)
}
@_transparent
public static func atanh(_ x: Float80) -> Float80 {
libm_atanhl(x)
}
@_transparent
public static func exp(_ x: Float80) -> Float80 {
libm_expl(x)
}
@_transparent
public static func expMinusOne(_ x: Float80) -> Float80 {
libm_expm1l(x)
}
@_transparent
public static func log(_ x: Float80) -> Float80 {
libm_logl(x)
}
@_transparent
public static func log(onePlus x: Float80) -> Float80 {
libm_log1pl(x)
}
@_transparent
public static func erf(_ x: Float80) -> Float80 {
libm_erfl(x)
}
@_transparent
public static func erfc(_ x: Float80) -> Float80 {
libm_erfcl(x)
}
@_transparent
public static func exp2(_ x: Float80) -> Float80 {
libm_exp2l(x)
}
@_transparent
public static func hypot(_ x: Float80, _ y: Float80) -> Float80 {
libm_hypotl(x, y)
}
@_transparent
public static func gamma(_ x: Float80) -> Float80 {
libm_tgammal(x)
}
@_transparent
public static func log2(_ x: Float80) -> Float80 {
libm_log2l(x)
}
@_transparent
public static func log10(_ x: Float80) -> Float80 {
libm_log10l(x)
}
@_transparent
public static func pow(_ x: Float80, _ y: Float80) -> Float80 {
guard x >= 0 else { return .nan }
return libm_powl(x, y)
}
@_transparent
public static func pow(_ x: Float80, _ n: Int) -> Float80 {
// Every Int value is exactly representable as Float80, so we don't need
// to do anything fancy--unlike Float and Double, we can just call the
// libm pow function.
libm_powl(x, Float80(n))
}
@_transparent
public static func root(_ x: Float80, _ n: Int) -> Float80 {
guard x >= 0 || n % 2 != 0 else { return .nan }
// Workaround the issue mentioned below for the specific case of n = 3
// where we can fallback on cbrt.
if n == 3 { return libm_cbrtl(x) }
// TODO: this implementation is not quite correct, because either n or
// 1/n may be not be representable as Float80.
return Float80(signOf: x, magnitudeOf: libm_powl(x.magnitude, 1/Float80(n)))
}
@_transparent
public static func atan2(y: Float80, x: Float80) -> Float80 {
libm_atan2l(y, x)
}
@_transparent
public static func logGamma(_ x: Float80) -> Float80 {
var dontCare: Int32 = 0
return libm_lgammal(x, &dontCare)
}
}
#endif
@@ -1,12 +1,12 @@
# Real
# Real Module
[SE-0246] proposed an API for "basic math functions" that would make operations like sine and logarithm available in generic contexts.
It was accepted, but because of limitations in the compiler, the API could not be added to the standard library in a source-stable manner.
The `Real` module provides that API as a separate module so that you can use it right away to get access to the improved API for these operations in your projects.
`RealModule` provides that API as a separate module so that you can use it right away to get access to the improved API for these operations in your projects.
## Protocols and Methods
The module defines three protocols. The most general is `ElementaryFunctions`, which makes the following functions available:
The module defines four protocols. The most general is `ElementaryFunctions`, which makes the following functions available:
- Exponential functions: `exp`, `expMinusOne`
- Logarithmic functions: `log`, `log(onePlus:)`
- Trigonometric functions: `cos`, `sin`, `tan`
@@ -28,9 +28,13 @@ The `RealFunctions` protocol refines `ElementaryFunctions`, and adds operations
The protocol that you will use most often is `Real`, which describes a floating-point type equipped with the full set of basic math functions.
This is a great protocol to use in writing generic code, because it has all the basics that you need to implement most numeric functions.
The fourth protocol is `AlgebraicField`, which `Real` also refines.
This protocol is a very small refinement of `SignedNumeric`, adding the `/` and `/=` operators and a `reciprocal` property.
The primary use of this protocol is for writing code that is generic over real and complex types.
## Using Real
First, either import `Real` directly or import the `Numerics` umbrella module.
First, either import `RealModule` directly or import the `Numerics` umbrella module.
Suppose we were experimenting with some basic machine learning, and needed a generic [sigmoid function][Sigmoid] activation function:
@@ -65,8 +69,9 @@ When new basic floating-point types are added to Swift, like `Float16` or `Float
Not having this protocol is a significant missing feature for numerical computing in Swift, and I'm really looking forward to seeing what people do with it.
### Dependencies:
- The C standard math library (`libm`) via the `NumericShims` target.
- The C standard math library (`libm`) via the `_NumericsShims` target.
[ErrorFunction]: https://en.wikipedia.org/wiki/Error_function
[GammaFunction]: https://en.wikipedia.org/wiki/Gamma_function
[SE-0246]: https://github.com/apple/swift-evolution/blob/master/proposals/0246-mathable.md
[Sigmoid]: https://en.wikipedia.org/wiki/Sigmoid_function
@@ -26,7 +26,8 @@
/// -
/// - `ElementaryFunctions`
/// - `RealFunctions`
public protocol Real: FloatingPoint, RealFunctions {
/// - `AlgebraicField`
public protocol Real: FloatingPoint, RealFunctions, AlgebraicField {
}
// While `Real` does not provide any additional customization points,
@@ -39,6 +40,17 @@ extension Real {
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.
@@ -75,8 +87,22 @@ 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()
}
@inlinable
public var reciprocal: Self? {
let recip = 1/self
if recip.isNormal || isZero || !isFinite {
return recip
}
return nil
}
}
@@ -112,4 +112,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
@@ -11,8 +11,22 @@
#define HEADER_SHIM static inline __attribute__((__always_inline__))
// MARK: - math functions for float
// This header uses most of the libm functions, but we don't want to end up
// exporting the libm declarations to modules that include NumericsShims, so
// we don't want to actually #include <math.h>.
//
// For most of the functions, we can get around this by using __builtin_func
// instead of func, since the compiler knows about these operations, but for
// the non-standard extensions, we need to include our own declarations. This
// is a little bit risky, in that we might end up missing an attribute that
// gets added and effects calling conventions, etc, but that's expected to be
// exceedingly rare.
//
// Still, we'll eventually want to find a better solution to this problem,
// especially if people start using this package on systems that are not
// Darwin or Ubuntu.
// MARK: - math functions for float
HEADER_SHIM float libm_cosf(float x) {
return __builtin_cosf(x);
}
@@ -131,9 +145,7 @@ HEADER_SHIM float libm_log10f(float x) {
#if !defined _WIN32
HEADER_SHIM float libm_lgammaf(float x, int *signp) {
#if __APPLE__
extern float lgammaf_r(float, int *);
#endif
return lgammaf_r(x, signp);
}
#endif
@@ -253,9 +265,7 @@ HEADER_SHIM double libm_log10(double x) {
#if !defined _WIN32
HEADER_SHIM double libm_lgamma(double x, int *signp) {
#if __APPLE__
extern double lgamma_r(double, int *);
#endif
return lgamma_r(x, signp);
}
#endif
@@ -372,8 +382,26 @@ HEADER_SHIM long double libm_lgammal(long double x, int *signp) {
}
#endif
// MARK: - shims to import C complex operations for timing purposes
// 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;
}
/// 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).
// MARK: - shims to import C complex operations for timing purposes
// Clang doesn't provide complex arithmetic on Windows (because MSVC
// doesn't), so we can't define these there, or we'll get link errors.
#if !defined _WIN32
typedef struct { double real; double imag; } CComplex;
HEADER_SHIM CComplex libm_cdiv(CComplex z, CComplex w) {
@@ -389,3 +417,4 @@ HEADER_SHIM CComplex libm_cmul(CComplex z, CComplex w) {
double _Complex c = a*b;
return (CComplex){ __real__ c, __imag__ c };
}
#endif // !defined _WIN32
@@ -0,0 +1,3 @@
module _NumericsShims {
header "_NumericsShims.h"
}
+19
View File
@@ -0,0 +1,19 @@
#[[
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
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)
+106
View File
@@ -0,0 +1,106 @@
//===--- 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 RealModule
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
public typealias TestLiteralType = Float80
#else
public typealias TestLiteralType = Double
#endif
@discardableResult
public func assertClose<T>(
_ expected: TestLiteralType,
_ observed: T,
allowedError: T = 16,
file: StaticString = #file,
line: UInt = #line
) -> T where T: BinaryFloatingPoint {
// Shortcut relative-error check if we got the sign wrong; it's OK to
// underflow to zero, but we do not want to allow going right through
// zero and getting the sign wrong.
guard observed.sign == expected.sign else {
print("Sign was wrong: expected \(expected) but saw \(observed).")
XCTFail(file: file, line: line)
return .infinity
}
if observed.isNaN && expected.isNaN { return 0 }
// If T(expected) is zero or infinite, and matches observed, the error
// is zero.
let expectedT = T(expected)
if observed.isZero && expectedT.isZero { return 0 }
if observed.isInfinite && expectedT.isInfinite { return 0 }
// Special-case where only one of expectedT or observed is infinity.
// Artificially knock everything down a binade, treat actual infinity as
// the base of the next binade up.
func topBinade(signOf x: T) -> T {
T(signOf: x, magnitudeOf: T.greatestFiniteMagnitude.binade)
}
if observed.isInfinite {
return assertClose(
expected/2, topBinade(signOf: observed),
allowedError: allowedError, file: file, line: line
)
}
if expectedT.isInfinite {
return assertClose(
TestLiteralType(topBinade(signOf: expectedT)), observed/2,
allowedError: allowedError, file: file, line: line
)
}
// Compute error in ulp, compare to tolerance.
let absoluteError = (TestLiteralType(observed) - expected).magnitude
let scale = max(expectedT.magnitude, T.leastNormalMagnitude).ulp
let ulps = T(absoluteError/TestLiteralType(scale))
if ulps > allowedError {
print("ULP error was unacceptably large: expected \(expected) but saw \(observed) (\(ulps)-ulp error).")
XCTFail(file: file, line: line)
}
return ulps
}
public func assertClose<T>(
_ expected: TestLiteralType,
_ observed: T,
allowedError: T = 16,
worstError: inout T,
file: StaticString = #file,
line: UInt = #line
) where T: BinaryFloatingPoint {
worstError = max(worstError, assertClose(
expected, observed, allowedError: allowedError, file: file, line: line
))
}
public protocol FixedWidthFloatingPoint: BinaryFloatingPoint
where Exponent: FixedWidthInteger,
RawSignificand: FixedWidthInteger { }
#if swift(>=5.3)
@available(iOS 14.0, watchOS 14.0, tvOS 7.0, *)
@available(macOS, unavailable)
@available(macCatalyst, unavailable)
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
+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
#]]
add_library(ComplexTests
ApproximateEqualityTests.swift
ArithmeticTests.swift
DifferentiableTests.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,78 @@
//===--- 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))
}
func testZeroTangentVectorInitializer() {
XCTAssertEqual(Complex<Float>(-5, 5).zeroTangentVector, Complex(0, 0))
}
}
#endif
+30 -3
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
@@ -10,8 +10,8 @@
//===----------------------------------------------------------------------===//
import XCTest
import Complex
import Real
import ComplexModule
import RealModule
final class PropertyTests: XCTestCase {
@@ -102,4 +102,31 @@ final class PropertyTests: XCTestCase {
testEquatableHashable(Float80.self)
#endif
}
func testCodable<T: Codable & Real>(_ type: T.Type) throws {
let encoder = JSONEncoder()
encoder.nonConformingFloatEncodingStrategy = .convertToString(
positiveInfinity: "inf",
negativeInfinity: "-inf",
nan: "nan")
let decoder = JSONDecoder()
decoder.nonConformingFloatDecodingStrategy = .convertFromString(
positiveInfinity: "inf",
negativeInfinity: "-inf",
nan: "nan")
for expected: Complex<T> in [.zero, .one, .i, .infinity] {
let data = try encoder.encode(expected)
// print("*** \(String(decoding: data, as: Unicode.UTF8.self)) ***")
let actual = try decoder.decode(Complex<T>.self, from: data)
XCTAssertEqual(actual, expected)
}
}
func testCodable() throws {
try testCodable(Float32.self)
try testCodable(Float64.self)
// Float80 doesn't conform to Codable.
}
}
@@ -0,0 +1,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)
@@ -0,0 +1,88 @@
//===--- ElementaryFunctionChecks.swift ------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
import RealModule
import _TestSupport
internal extension ElementaryFunctions where Self: BinaryFloatingPoint {
static func elementaryFunctionChecks() {
assertClose(1.1863995522992575361931268186727044683, Self.acos(0.375))
assertClose(0.3843967744956390830381948729670469737, Self.asin(0.375))
assertClose(0.3587706702705722203959200639264604997, Self.atan(0.375))
assertClose(0.9305076219123142911494767922295555080, Self.cos(0.375))
assertClose(0.3662725290860475613729093517162641571, Self.sin(0.375))
assertClose(0.3936265759256327582294137871012180981, Self.tan(0.375))
assertClose(0.4949329230945269058895630995767185785, Self.acosh(1.125))
assertClose(0.9670596312833237113713762009167286709, Self.asinh(1.125))
assertClose(0.7331685343967135223291211023213964500, Self.atanh(0.625))
assertClose(1.0711403467045867672994980155670160493, Self.cosh(0.375))
assertClose(0.3838510679136145687542956764205024589, Self.sinh(0.375))
assertClose(0.3583573983507859463193602315531580424, Self.tanh(0.375))
assertClose(1.4549914146182013360537936919875185083, Self.exp(0.375))
assertClose(0.4549914146182013360537936919875185083, Self.expMinusOne(0.375))
assertClose(-0.980829253011726236856451127452003999, Self.log(0.375))
assertClose(0.3184537311185346158102472135905995955, Self.log(onePlus: 0.375))
assertClose(-0.7211247851537041911608191553900547941, Self.root(-0.375, 3))
XCTAssertEqual(-10, Self.root(-1000, 3))
assertClose(0.6123724356957945245493210186764728479, Self.sqrt(0.375))
assertClose(0.54171335479545025876069682133938570, Self.pow(0.375, 0.625))
assertClose(-0.052734375, Self.pow(-0.375, 3))
}
}
internal extension Real where Self: BinaryFloatingPoint {
static func realFunctionChecks() {
assertClose(1.2968395546510096659337541177924511598, Self.exp2(0.375))
assertClose(2.3713737056616552616517527574788898386, Self.exp10(0.375))
assertClose(-1.415037499278843818546261056052183491, Self.log2(0.375))
assertClose(-0.425968732272281148346188780918363771, Self.log10(0.375))
assertClose(0.54041950027058415544357836460859991, Self.atan2(y: 0.375, x: 0.625))
assertClose(0.72886898685566255885926910969319788, Self.hypot(0.375, 0.625))
assertClose(0.4041169094348222983238250859191217675, Self.erf(0.375))
assertClose(0.5958830905651777016761749140808782324, Self.erfc(0.375))
assertClose(2.3704361844166009086464735041766525098, Self.gamma(0.375))
#if !os(Windows)
assertClose( -0.11775527074107877445136203331798850, Self.logGamma(1.375))
XCTAssertEqual(.plus, Self.signGamma(1.375))
XCTAssertEqual(.minus, Self.signGamma(-2.375))
#endif
}
}
final class ElementaryFunctionChecks: XCTestCase {
#if swift(>=5.3) && !os(macOS)
func testFloat16() {
if #available(iOS 14.0, watchOS 14.0, tvOS 7.0, *) {
Float16.elementaryFunctionChecks()
Float16.realFunctionChecks()
}
}
#endif
func testFloat() {
Float.elementaryFunctionChecks()
Float.realFunctionChecks()
}
func testDouble() {
Double.elementaryFunctionChecks()
Double.realFunctionChecks()
}
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
func testFloat80() {
Float80.elementaryFunctionChecks()
Float80.realFunctionChecks()
}
#endif
}
+197
View File
@@ -0,0 +1,197 @@
//===--- IntegerExponentTests.swift ---------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
import RealModule
import _TestSupport
internal extension Real where Self: FixedWidthFloatingPoint {
static func testIntegerExponentCommon() {
// TODO: replace with seedable generator, print seed.
var g = SystemRandomNumberGenerator()
// If x is -1, then the result is ±1 with sign chosen by parity of n.
// Simply converting n to Real will flip parity when n is large, so
// first check that we get those cases right.
XCTAssertEqual(Self.pow(-1, 0), 1)
XCTAssertEqual(Self.pow(-1, 1), -1)
XCTAssertEqual(Self.pow(-1, -1), -1)
XCTAssertEqual(Self.pow(-1, 2), 1)
XCTAssertEqual(Self.pow(-1, -2), 1)
XCTAssertEqual(Self.pow(-1, Int.max - 1), 1)
XCTAssertEqual(Self.pow(-1, -Int.max + 1), 1)
XCTAssertEqual(Self.pow(-1, Int.max), -1)
XCTAssertEqual(Self.pow(-1, -Int.max), -1)
XCTAssertEqual(Self.pow(-1, Int.min), 1)
// Generate some random test values that definitely overflow or
// underflow; we want to be sure that we get the right ±0 or ±∞
// result.
for _ in 0 ..< 10 {
let x = Self.random(in: 2 ..< 4, using: &g)
let nLowerBound = 1 - Int(Self.leastNonzeroMagnitude.exponent)
let n = Int.random(in: nLowerBound ..< .max, using: &g)
let even = n & -2
let odd = even | 1
assertClose( .infinity, Self.pow(x, even))
assertClose( .infinity, Self.pow(x, odd))
assertClose( 0.0, Self.pow(1/x, even))
assertClose( 0.0, Self.pow(1/x, odd))
assertClose( .infinity, Self.pow(-x, even))
assertClose(-.infinity, Self.pow(-x, odd))
assertClose( 0.0, Self.pow(-1/x, even))
assertClose(-0.0, Self.pow(-1/x, odd))
assertClose( 0.0, Self.pow(x, -even))
assertClose( 0.0, Self.pow(x, -odd))
assertClose( .infinity, Self.pow(1/x, -even))
assertClose( .infinity, Self.pow(1/x, -odd))
assertClose( 0.0, Self.pow(-x, -even))
assertClose(-0.0, Self.pow(-x, -odd))
assertClose( .infinity, Self.pow(-1/x, -even))
assertClose(-.infinity, Self.pow(-1/x, -odd))
}
}
static func testIntegerExponentDoubleAndSmaller() {
// max/min exponents, these always saturate, but this will reveal
// errors in some implementations that one could try.
let u = Self(1).nextUp
let d = Self(1).nextDown
assertClose( .infinity, Self.pow(-u, Int.max - 1))
assertClose( 0.0, Self.pow(-d, Int.max - 1))
assertClose( 0.0, Self.pow(-u, -Int.max + 1))
assertClose( .infinity, Self.pow(-d, -Int.max + 1))
assertClose(-.infinity, Self.pow(-u, Int.max))
assertClose(-0.0, Self.pow(-d, Int.max))
assertClose(-0.0, Self.pow(-u, -Int.max))
assertClose(-.infinity, Self.pow(-d, -Int.max))
assertClose( 0.0, Self.pow(-u, Int.min))
assertClose( .infinity, Self.pow(-d, Int.min))
}
}
#if swift(>=5.3)
@available(iOS 14.0, watchOS 14.0, tvOS 7.0, *)
@available(macOS, unavailable)
extension Float16 {
static func testIntegerExponent() {
testIntegerExponentCommon()
testIntegerExponentDoubleAndSmaller()
let u = Float16(1).nextUp
let d = Float16(1).nextDown
// Smallest exponents not exactly representable as Float16.
assertClose(-7.3890572722436554354625993393835304, Float16.pow(-u, 0x801))
assertClose(-0.3676100238077049750885141244927184, Float16.pow(-d, 0x801))
// Exponents close to overflow boundary.
assertClose( 65403.86633107, Float16.pow(-u, 11360))
assertClose(-65467.73729429, Float16.pow(-u, 11361))
assertClose( 65531.67063149, Float16.pow(-u, 11362))
assertClose( 65487.96799785, Float16.pow(-d, -22706))
assertClose(-65519.96016590, Float16.pow(-d, -22707))
assertClose( 65551.96796276, Float16.pow(-d, -22708))
// Exponents close to underflow boundary.
assertClose( 5.966876499900e-8, Float16.pow(-u, -17042))
assertClose(-5.961055156973e-8, Float16.pow(-u, -17043))
assertClose( 5.955239493405e-8, Float16.pow(-u, -17044))
assertClose( 5.964109628044e-8, Float16.pow(-d, 34060))
assertClose(-5.961197465140e-8, Float16.pow(-d, 34061))
assertClose( 5.958286724190e-8, Float16.pow(-d, 34062))
}
}
#endif
extension Float {
static func testIntegerExponent() {
testIntegerExponentCommon()
testIntegerExponentDoubleAndSmaller()
let u = Float(1).nextUp
let d = Float(1).nextDown
// Smallest exponents not exactly representable as Float.
assertClose(-7.3890560989306677280287919329569359, Float.pow(-u, 0x1000001))
assertClose(-0.3678794082804575860056608283059288, Float.pow(-d, 0x1000001))
// Exponents close to overflow boundary.
assertClose(-3.4028231352500001570898203463449749e38, Float.pow(-u, 744261161))
assertClose( 3.4028235408981285772043562848249166e38, Float.pow(-u, 744261162))
assertClose(-3.4028239465463053543440887892352174e38, Float.pow(-u, 744261163))
assertClose( 3.4028233551634475284795244782720072e38, Float.pow(-d, -1488522190))
assertClose(-3.4028235579875369356575053576685267e38, Float.pow(-d, -1488522191))
assertClose( 3.4028237608116384320940078199368685e38, Float.pow(-d, -1488522192))
// Exponents close to underflow boundary.
assertClose( 7.0064936491761438872280296737844625e-46, Float.pow(-u, -872181048))
assertClose(-7.0064928139371132951305928725186420e-46, Float.pow(-u, -872181049))
assertClose( 7.0064919786981822712727285793333389e-46, Float.pow(-u, -872181050))
assertClose(-7.0064924138100205091278464932003585e-46, Float.pow(-d, 1744361943))
assertClose( 7.0064919961905290625123586120258840e-46, Float.pow(-d, 1744361944))
assertClose(-7.0064915785710625079583096856510544e-46, Float.pow(-d, 1744361945))
}
}
extension Double {
static func testIntegerExponent() {
testIntegerExponentCommon()
testIntegerExponentDoubleAndSmaller()
// Following tests only make sense (and are only necessary) on 64b platforms.
#if arch(arm64) || arch(x86_64)
let u: Double = 1.nextUp
let d: Double = 1.nextDown
// Smallest exponent not exactly representable as Double.
assertClose(-7.3890560989306502272304274605750685, Double.pow(-u, 0x20000000000001))
assertClose(-0.1353352832366126918939994949724833, Double.pow(-u, -0x20000000000001))
assertClose(-0.3678794411714422603312898889458068, Double.pow(-d, 0x20000000000001))
assertClose(-2.7182818284590456880451484776630468, Double.pow(-d, -0x20000000000001))
// Exponents close to overflow boundary.
#if os(Windows)
// TODO: It appears that the Windows pow doesn't carry enough precision
// through the computation of log(1.nextDown) to produce a good result
// for these cases; we'll want to provide a better implementation at some
// point in the future. It's acceptable in the short term, however.
let tol: Double = 360
#else
let tol: Double = 16
#endif
assertClose( 1.7976931348623151738531864721534215e308, Double.pow(-u, 3196577161300664268), allowedError: tol)
assertClose(-1.7976931348623155730212483790972209e308, Double.pow(-u, 3196577161300664269), allowedError: tol)
assertClose( 1.7976931348623159721893102860411089e308, Double.pow(-u, 3196577161300664270), allowedError: tol)
assertClose( 1.7976931348623157075547244136070910e308, Double.pow(-d, -6393154322601327474), allowedError: tol)
assertClose(-1.7976931348623159071387553670790721e308, Double.pow(-d, -6393154322601327475), allowedError: tol)
assertClose( 1.7976931348623161067227863205510754e308, Double.pow(-d, -6393154322601327476), allowedError: tol)
// Exponents close to underflow boundary.
assertClose( 2.4703282292062334560337346683707907e-324, Double.pow(-u, -3355781687888880946))
assertClose(-2.4703282292062329075106789791206172e-324, Double.pow(-u, -3355781687888880947))
assertClose( 2.4703282292062323589876232898705654e-324, Double.pow(-u, -3355781687888880948))
assertClose(-2.4703282292062332640976590913373022e-324, Double.pow(-d, 6711563375777760775))
assertClose( 2.4703282292062329898361312467121758e-324, Double.pow(-d, 6711563375777760776))
assertClose(-2.4703282292062327155746034020870799e-324, Double.pow(-d, 6711563375777760777))
#endif
}
}
final class IntegerExponentTests: XCTestCase {
#if swift(>=5.3) && !os(macOS)
func testFloat16() {
Float16.testIntegerExponent()
}
#endif
func testFloat() {
Float.testIntegerExponent()
}
func testDouble() {
Double.testIntegerExponent()
}
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
func testFloat80() {
Float80.testIntegerExponentCommon()
}
#endif
}
-109
View File
@@ -1,109 +0,0 @@
//===--- ElementaryFunctionTests.swift ------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
import Real
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
typealias TestLiteralType = Float80
#else
typealias TestLiteralType = Double
#endif
func sanityCheck<T>(_ expected: TestLiteralType, _ actual: T,
ulps allowed: T = 16,
file: StaticString = #file, line: UInt = #line)
where T: BinaryFloatingPoint {
// Default tolerance is 16 ulps; It's OK to relax this as needed for new
// platforms, as these tests are *not* intended to validate the math
// library--they are only intended to check that the Swift bindings are
// calling the right functions in the math library. It's important, however
// not to relax the tolerance beyond a few hundred ulps, because these tests
// need to detect errors where the *wrong function* is being called; e.g.
// we need to flag an implentation that inadvertently called the C hypotf
// function instead of hypot. This is especially important because the C
// shims that we're calling through will allow silent type conversions.
if actual == T(expected) || actual.isNaN && expected.isNaN {
return
}
// Compute error in ulp, compare to tolerance.
let absoluteError = T(abs(TestLiteralType(actual) - expected))
let ulpError = absoluteError / T(expected).ulp
XCTAssert(ulpError <= allowed, "\(actual) != \(expected) as \(T.self)" +
"\n \(ulpError)-ulp error exceeds \(allowed)-ulp tolerance.",
file: file, line: line)
}
internal extension ElementaryFunctions where Self: BinaryFloatingPoint {
static func elementaryFunctionTests() {
sanityCheck(1.1863995522992575361931268186727044683, Self.acos(0.375))
sanityCheck(0.3843967744956390830381948729670469737, Self.asin(0.375))
sanityCheck(0.3587706702705722203959200639264604997, Self.atan(0.375))
sanityCheck(0.9305076219123142911494767922295555080, Self.cos(0.375))
sanityCheck(0.3662725290860475613729093517162641571, Self.sin(0.375))
sanityCheck(0.3936265759256327582294137871012180981, Self.tan(0.375))
sanityCheck(0.4949329230945269058895630995767185785, Self.acosh(1.125))
sanityCheck(0.9670596312833237113713762009167286709, Self.asinh(1.125))
sanityCheck(0.7331685343967135223291211023213964500, Self.atanh(0.625))
sanityCheck(1.0711403467045867672994980155670160493, Self.cosh(0.375))
sanityCheck(0.3838510679136145687542956764205024589, Self.sinh(0.375))
sanityCheck(0.3583573983507859463193602315531580424, Self.tanh(0.375))
sanityCheck(1.4549914146182013360537936919875185083, Self.exp(0.375))
sanityCheck(0.4549914146182013360537936919875185083, Self.expMinusOne(0.375))
sanityCheck(-0.980829253011726236856451127452003999, Self.log(0.375))
sanityCheck(0.3184537311185346158102472135905995955, Self.log(onePlus: 0.375))
sanityCheck(-0.7211247851537041911608191553900547941, Self.root(-0.375, 3))
XCTAssertEqual(-10, Self.root(-1000, 3))
sanityCheck(0.6123724356957945245493210186764728479, Self.sqrt(0.375))
sanityCheck(0.54171335479545025876069682133938570, Self.pow(0.375, 0.625))
sanityCheck(-0.052734375, Self.pow(-0.375, 3))
}
}
internal extension Real where Self: BinaryFloatingPoint {
static func realFunctionTests() {
sanityCheck(1.2968395546510096659337541177924511598, Self.exp2(0.375))
sanityCheck(2.3713737056616552616517527574788898386, Self.exp10(0.375))
sanityCheck(-1.415037499278843818546261056052183491, Self.log2(0.375))
sanityCheck(-0.425968732272281148346188780918363771, Self.log10(0.375))
sanityCheck(0.54041950027058415544357836460859991, Self.atan2(y: 0.375, x: 0.625))
sanityCheck(0.72886898685566255885926910969319788, Self.hypot(0.375, 0.625))
sanityCheck(0.4041169094348222983238250859191217675, Self.erf(0.375))
sanityCheck(0.5958830905651777016761749140808782324, Self.erfc(0.375))
sanityCheck(2.3704361844166009086464735041766525098, Self.gamma(0.375))
#if !os(Windows)
sanityCheck( -0.11775527074107877445136203331798850, Self.logGamma(1.375))
XCTAssertEqual(.plus, Self.signGamma(1.375))
XCTAssertEqual(.minus, Self.signGamma(-2.375))
#endif
}
}
final class ElementaryFunctionTests: XCTestCase {
func testFloat() {
Float.elementaryFunctionTests()
Float.realFunctionTests()
}
func testDouble() {
Double.elementaryFunctionTests()
Double.realFunctionTests()
}
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
func testFloat80() {
Float80.elementaryFunctionTests()
Float80.realFunctionTests()
}
#endif
}
+111
View File
@@ -0,0 +1,111 @@
//===--- WindowsMain.swift ------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#if os(Windows)
import XCTest
@testable
import RealTests
@testable
import ComplexTests
extension ComplexTests.ApproximateEqualityTests {
static var all = testCase([
("testFloat", ComplexTests.ApproximateEqualityTests.testFloat),
("testDouble", ComplexTests.ApproximateEqualityTests.testDouble),
])
}
extension RealTests.ApproximateEqualityTests {
static var all = testCase([
("testFloat", RealTests.ApproximateEqualityTests.testFloat),
("testDouble", RealTests.ApproximateEqualityTests.testDouble),
])
}
#if swift(>=5.3)
extension ElementaryFunctionChecks {
static var all = testCase([
("testFloat16", ElementaryFunctionChecks.testFloat16),
("testFloat", ElementaryFunctionChecks.testFloat),
("testDouble", ElementaryFunctionChecks.testDouble),
])
}
#else
extension ElementaryFunctionChecks {
static var all = testCase([
("testFloat", ElementaryFunctionChecks.testFloat),
("testDouble", ElementaryFunctionChecks.testDouble),
])
}
#endif
#if swift(>=5.3)
extension IntegerExponentTests {
static var all = testCase([
("testFloat16", IntegerExponentTests.testFloat16),
("testFloat", IntegerExponentTests.testFloat),
("testDouble", IntegerExponentTests.testDouble),
])
}
#else
extension IntegerExponentTests {
static var all = testCase([
("testFloat", IntegerExponentTests.testFloat),
("testDouble", IntegerExponentTests.testDouble),
])
}
#endif
extension ArithmeticTests {
static var all = testCase([
("testPolar", ArithmeticTests.testPolar),
("testBaudinSmith", ArithmeticTests.testBaudinSmith),
("testDivisionByZero", ArithmeticTests.testDivisionByZero),
])
}
extension PropertyTests {
static var all = testCase([
("testProperties", PropertyTests.testProperties),
("testEquatableHashable", PropertyTests.testEquatableHashable),
("testCodable", PropertyTests.testCodable),
])
}
var testCases = [
ComplexTests.ApproximateEqualityTests.all,
RealTests.ApproximateEqualityTests.all,
ElementaryFunctionChecks.all,
IntegerExponentTests.all,
ArithmeticTests.all,
PropertyTests.all,
]
#if swift(>=5.3) && canImport(_Differentiation)
extension DifferentiableTests {
static var all = testCase([
("testComponentGetter", DifferentiableTests.testComponentGetter),
("testInitializer", DifferentiableTests.testInitializer),
("testConjugate", DifferentiableTests.testConjugate),
("testArithmetics", DifferentiableTests.testArithmetics),
])
}
testCases += [
DifferentiableTests.all
]
#endif
XCTMain(testCases)
#endif
+84
View File
@@ -0,0 +1,84 @@
#[[
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}" STREQUAL "aarch64")
set("${result_var_name}" "aarch64" PARENT_SCOPE)
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()