455 Commits
Author SHA1 Message Date
Stephen Canon 0098c438eb Merge pull request #277 from gwynne/biginteger
Update BigInteger branch from main
2024-01-10 13:55:22 -05:00
Gwynne Raskind 349fdf1e01 Add preliminary version of BigUInt 2023-12-26 11:12:49 -06:00
Gwynne Raskind 0d48ff5a98 Repair BigInt module after merge 2023-12-25 22:44:32 -06:00
Gwynne Raskind 1c90bdc9a9 Merge branch 'main' into biginteger 2023-12-25 22:31:33 -06:00
Stephen Canon 0111e791a1 Merge pull request #274 from stephentyrone/link-real-libm-linux
Move the -lm link command to RealModule (from _NumericsShims).
2023-12-10 17:09:03 -05:00
Stephen Canon 1883189574 Merge pull request #273 from xwu/toil-and-trouble
[_TestSupport] Fix DoubleWidth think-o that trips an assert
2023-11-30 10:59:41 -05:00
Stephen Canon e8a3ddbb3e Move the -lm link command to RealModule (from _NumericsShims).
Hopefully this resolves some niche link errors that we've seen sporadically.
2023-11-30 09:27:03 -05:00
Xiaodi Wu a7e27e16e1 [_TestSupport] Fix DoubleWidth think-os harder 2023-11-13 15:42:07 -05:00
Xiaodi Wu a0d66e1537 [_TestSupport] Fix DoubleWidth think-os 2023-11-13 15:41:52 -05:00
Stephen Canon 182c9b246b Merge pull request #271 from stephentyrone/none-some
Replace `some BinaryInteger` with an explicit generic parameter.
2023-09-29 14:34:06 -04:00
Stephen Canon b3867a9155 Replace some BinaryInteger with an explicit generic parameter.
For compatibility with pre-Swift-5.7 language versions.
2023-09-28 15:31:25 -04:00
Stephen Canon 470e4236ff Merge pull request #269 from stephentyrone/enable-spi
Add .spi.yml file to build documentation for SPI.
2023-09-20 09:56:49 -04:00
Stephen Canon 3d13ebaf94 Add .spi.yml file to build documentation for SPI. 2023-09-20 09:55:35 -04:00
Stephen Canon 485c60c6c4 Merge pull request #268 from stephentyrone/fix-tvOS-availability
Correct tvOS availability for Float16 in _TestSupport.
2023-09-20 09:52:12 -04:00
Stephen Canon b38fcb77a6 Correct tvOS availability for Float16 in _TestSupport. 2023-09-20 09:44:53 -04:00
Stephen Canon 716e22fd64 Merge pull request #218 from stephentyrone/saturating-arithmetic
Implement saturating arithmetic on FixedWidthInteger
2023-04-29 10:02:32 -04:00
Stephen Canon 35e15a381f Additional comment fixes from Guillaume 2023-04-28 22:31:31 -04:00
Stephen CanonandGuillaume Lessard bc9f6e7368 Update Sources/IntegerUtilities/ShiftWithRounding.swift
Co-authored-by: Guillaume Lessard <glessard@users.noreply.github.com>
2023-04-28 22:29:25 -04:00
Stephen CanonandGuillaume Lessard ef6dbc6e78 Update Sources/IntegerUtilities/ShiftWithRounding.swift
Co-authored-by: Guillaume Lessard <glessard@users.noreply.github.com>
2023-04-28 22:29:13 -04:00
Stephen Canon 0bb0a9acff Only run benchmarks in Release, they're meaningless in Debug. 2023-04-28 14:36:57 -04:00
Stephen Canon d59ec36291 Only run benchmarks in Release, they're meaningless in Debug. 2023-04-28 14:36:40 -04:00
Stephen Canon a118de9878 Polish README.md 2023-04-28 13:58:37 -04:00
Stephen Canon 58f4e72d8a Documentation improvements. 2023-04-28 13:34:53 -04:00
Stephen Canon 8680be387b Update README.md 2023-04-27 16:30:31 -04:00
Stephen Canon f7075cc79a Add a link to BinaryInteger.init(clamping:) in the section on new saturating arithmetic API. 2023-04-27 16:27:37 -04:00
Stephen Canon fe151134b0 Further saturating arithmetic test and implementation cleanups 2023-04-27 16:19:40 -04:00
Stephen Canon f00824e9fa More tests for saturating arithmetic -- exhaustive sampling of [U]Int8 arguments. 2023-04-26 21:50:23 -04:00
Stephen Canon 4779aef990 Test coverage for saturating shift + fix the bug that it turned up. 2023-04-26 21:20:57 -04:00
Stephen Canon dbffff1ea5 Add some basic documentation. 2023-04-26 18:34:48 -04:00
Stephen Canon 7953ef315a First pass. 2023-04-26 16:43:50 -04:00
Stephen Canon 93e5499e54 Merge pull request #214 from stephentyrone/rilakkuma
Initial pass at "relaxed" multiply and add operations.
2023-04-26 09:14:35 -04:00
Stephen Canon 740cc5012f Some cleanups to relaxed arithmetic. 2023-04-26 09:05:28 -04:00
Stephen Canon f6b0aeb607 Remove _mulAdd in favor of Relaxed.multiplyAdd. 2023-04-26 08:56:43 -04:00
Stephen Canon 313ab7266a No longer need pre-5.4 clang workaround. 2023-04-26 08:56:43 -04:00
Steve (Numerics) Canon 30c01a9fc5 Possible spelling: Relaxed.sum/product. 2023-04-26 08:56:43 -04:00
Stephen Canon 9a23fdf1c9 Fewer iterations for debug; more for release. 2023-04-26 08:56:43 -04:00
Stephen Canon 86699a7f8a Undef what we def. 2023-04-26 08:56:43 -04:00
Stephen Canon b750c890b7 Don't use reassociate(on) on older clang toolchains. 2023-04-26 08:56:43 -04:00
Stephen Canon 79390164f5 CMake support for newer tests. 2023-04-26 08:56:43 -04:00
Stephen Canon 0fff91683a Disable _Float16 shims for relaxed operations on Intel.
The C type isn't available yet in clang on i386 or x86_64; once the calling conventions are stabilized in clang, we can reenable this.
2023-04-26 08:56:43 -04:00
Stephen Canon 9c0332d570 Initial pass at "relaxed" multiply and add operations.
This commit adds the following to the RealFunctions protocol:

    static func _relaxedAdd(_:Self, _:Self) -> Self
    static func _relaxedMul(_:Self, _:Self) -> Self

These are equivalent to + and *, but have "relaxed semantics"; specifically, they license the compiler to reassociate them and to form FMA nodes, which are both significant optimizations that can easily make many common loops 8-10x faster. These transformation perturb results slightly, so they should not be enabled without care, but the results with the relaxed operations are--for most purposes--"just as good as" (and often better than) what strict operations produce. The main thing to beware of is that they are no longer portable; different compiler versions and different targets and optimization flags will result in different results.

They are underscored because they are not stable API. In particular:
- `RealFunctions` is not really the right protocol for these (and neither is `Real`). I need to do some thinking about where to attach them.
- Even if it were the right protocol, these are more like implementation hooks than the API I really want people to use (TBD).
- I like "relaxed" more than other commonly used idioms ("fast"), but I'm not sure it's the name I ultimately want.
2023-04-26 08:56:43 -04:00
Stephen Canon 97c716ba37 Merge pull request #240 from stephentyrone/bump-to-5.5
Bump tools version to 5.5, add @swift-5.4 for legacy support.
2022-12-28 18:33:20 -05:00
Steve (Numerics) Canon 8353ce4c3d Bump tools version to 5.5, add @swift-5.4 for legacy support. 2022-12-28 18:25:22 -05:00
Stephen Canon fd9722e609 Merge pull request #84 from rothomp3/BigInt
Arbitrary-precision BigInt preliminary work
2022-10-28 15:40:10 -04:00
Stephen Canon f11ce9b248 Merge branch 'biginteger' into BigInt 2022-10-28 15:39:47 -04:00
Stephen Canon 5428505255 Merge pull request #237 from stephentyrone/send-it
Mark Complex Sendable when the underlying RealType is.
2022-09-30 18:48:03 -04:00
Stephen Canon e601f16e20 Mark Complex Sendable when the underlying RealType is. 2022-09-30 14:07:49 -04:00
Stephen Canon 6c4accd836 Merge pull request #236 from stephentyrone/further-complex-pow-tweaks
Further improvement to Complex.pow(_:Self,_:Self) edge cases.
2022-09-17 15:01:40 -04:00
Stephen Canon 60a3edbaa9 Further improvement to Complex.pow(_:Self,_:Self) edge cases.
Bring pow(zero, w) in line with the behavior of pow for the underlying real type.
2022-09-17 14:56:29 -04:00
Stephen Canon 89cfa62803 Merge pull request #235 from stephentyrone/complex-pow
Fix edge-cases for Complex.pow(.zero, <Int>), and Real.pow(zero, zero)
2022-09-15 19:05:35 -04:00
Stephen Canon 2baff8fc30 Also fixup real edge cases for pow(0,0). 2022-09-15 16:10:17 -04:00
Stephen Canon b9e8b970f2 Fixup indentation. 2022-09-15 15:39:34 -04:00
Stephen Canon d34f5636c4 Fix the edge-case handling of Complex.pow(.zero, <int>) 2022-09-15 15:07:06 -04:00
Stephen Canon 2624562948 Merge pull request #233 from xymus/missing-import-for-conformance
Add missing import required to use a conformance
2022-07-12 14:31:29 -04:00
Alexis Laferrière c8e3d9f54b Add missing import required to use a conformance
A new compiler check reports a missing import for a conformance
implicitly imported:

```
Sources/_TestSupport/Error.swift:21:13: error: cannot use conformance of
'Float' to 'Real' here; 'RealModule' was not imported by this file
public func componentwiseError(_ tst: Complex<Float>, _ ref:
Complex<Double>) -> Double {
            ^
```

Address this issue in the project by adding the missing import.
2022-07-11 14:44:42 -07:00
Stephen Canon a7ceb774fe Merge pull request #231 from markuswntr/patch-1
Fix broken link to `IntegerUtilities` in README.md
2022-06-20 09:26:24 -10:00
Markus Winter 0ea36c3109 Update README.md 2022-06-16 08:16:18 +02:00
Stephen Canon 0dc8fef6e9 Merge pull request #227 from buttaface/math
Link math library on Android too
2022-04-07 22:35:51 -04:00
Stephen Canon 98a8a166df Merge pull request #226 from compnerd/patch-1
Update CMakeLists.txt to link math library on Linux.
2022-04-07 17:25:38 -04:00
Saleem Abdulrasool 0d9f0b2a98 Update CMakeLists.txt
Adjust the CMake build system to reflect the recent changes of requiring the explicit linking of libm on Linux platforms.
2022-04-07 14:24:06 -07:00
Butta 1db31ebdf0 Link math library on Android too 2022-04-07 23:27:42 +05:30
Stephen Canon 48003e8b7a Fixup banner comment on Scale.swift. 2022-04-07 10:18:54 -04:00
Stephen Canon 56db9b5ec9 Merge pull request #225 from apple/remove-differentiable
Remove conformance of Complex to Differentiable
2022-04-06 23:15:28 -04:00
Stephen Canon 5803eaf5bb Let's try a different approach. 2022-04-06 22:42:21 -04:00
Stephen Canon cc53a7b085 Make _NumericsShims a systemLibrary target. 2022-04-06 15:21:00 -04:00
Stephen Canon 027bcc5b8e Remove conformance of Complex to Differentiable
The conformance was breaking CI testing, because the CI bots use a macOS version that predates availability of the _Differentiation module, and the compiler-generated differentation operations have neither availability attributes nor checks, so any reference to those operations simply crashes in dyld because the library is not present. We can add availability, but that's not really accurate either, because these operations are not actually binary-stable, so while we wouldn't crash in dyld, we also might not work correctly in the future. We could mark them unavailable on Apple platforms, but that's also not quite right (and further means that they're not going to get a lot of attention). The best solution seems to be to remove the conformance (which was never source-stable).
2022-04-06 14:41:04 -04:00
Stephen Canon fc1b2d1e67 Merge pull request #224 from apple/documentation-formatting
Minor documentation formatting cleanup.
2022-04-06 13:21:32 -04:00
Stephen Canon 270972dd8a Minor documentation formatting cleanup. 2022-04-06 11:50:25 -04:00
Stephen Canon b6018fa8a9 Merge pull request #222 from NevinBR/patch-1
GCD bug fix
2022-04-06 10:04:39 -04:00
Stephen Canon 5bbf0e2229 Merge pull request #223 from stephentyrone/require-swift-5.4
Move baseline supported tools version to 5.4
2022-04-06 10:00:56 -04:00
Stephen Canon 27f8192a63 Attempt to work around CI misconfiguration by removing Complex Differentiable conformance. 2022-04-06 09:58:40 -04:00
Stephen Canon c4f8886a11 Move baseline supported tools version to 5.4. 2022-03-05 10:18:13 -05:00
NevinBR 7f2d022d3d GCD bug fix
The standard-library documentation for `trailingZeroBitCount` states:

> If the value is zero, then `trailingZeroBitCount` is equal to `bitWidth`.

Thus, if `T` is not a fixed-width integer type, and `x == 0`, and `y` has more trailing zeros than the representation of `x`, then the gcd calculation will be incorrect.

In particular, the left-shift by `min(xtz, ytz) == xtz` will not “undo” the earlier right-shift by `ytz`,  so the final result will be incorrectly right-shifted by `ytz - xtz`.

To fix this I have added an early exit when `x == 0`. I am not sure if this is the optimal solution, and I’m open to alternatives.

***

This change ensures that `x != 0` at the top of the loop, so I have also converted it from a `while` to a `repeat-while` loop, in order to eliminate a redundant extra comparison on the first iteration.

I don’t know if this actually affects performance, and I’m happy to change it back if that’s preferred.
2022-02-22 11:46:06 -05:00
Stephen Canon 4ce74b4235 Merge pull request #220 from stephentyrone/refactor-complex-cmake
Update complex cmake for refactoring.
2021-12-16 15:19:39 -05:00
Stephen Canon 445b0da15d Update complex cmake for refactoring. 2021-12-16 13:38:20 -05:00
Stephen Canon 9596f40d3b Merge pull request #219 from stephentyrone/refactor-complex
Refactor complex
2021-12-16 13:33:55 -05:00
Stephen Canon d329698498 remove F16/F80 stubs for complex elfns. 2021-12-11 14:57:36 -05:00
Stephen Canon ba65b0fc77 Refactor Complex module for finer granularity. 2021-12-11 11:19:29 -05:00
Stephen Canon 1939f34fde Merge pull request #217 from stephentyrone/double-width-testing-right-shift
Use DoubleWidth in stochastic rounding right-shift tests.
2021-11-24 11:40:29 -05:00
Stephen Canon 47a233758d Use DoubleWidth in stochastic rounding right-shift tests.
This lets us get rid of Double here, and get more meaningful test coverage for 64b values. Also test 128b to cover double-width itself somewhat.
2021-11-24 11:35:40 -05:00
Stephen Canon f3365bd0b4 Merge pull request #213 from DanboDuan/main
add macOS/arm64 support in the CMake build.
2021-11-18 09:17:22 -05:00
bob 8983be89c7 add arm64 support for M1 Mac 2021-11-17 20:39:39 +08:00
Stephen Canon f5b33a6c07 Merge pull request #212 from stephentyrone/integer-utils-cleanup
Minor cleanups in integer utilities.
2021-11-09 08:08:12 -05:00
Stephen Canon bfd905c9e4 Minor cleanups in integer utilities. 2021-11-03 13:53:38 -04:00
Stephen Canon 80d758ac5b Merge pull request #211 from stephentyrone/further-doublewidth-cleanup
Clean out some unnecessary stuff in DoubleWidth.
2021-11-03 09:37:41 -04:00
Stephen Canon 48099a09b4 Clean out some unnecessary stuff in DoubleWidth. 2021-11-03 09:33:32 -04:00
Stephen Canon 9e50430d23 Merge pull request #210 from stephentyrone/double-width-comments
Expand some comments on DoubleWidth basic properties and inits.
2021-11-03 09:08:24 -04:00
Stephen Canon cdb092bb31 Expand some comments on DoubleWidth basic properties and inits. 2021-11-03 08:46:34 -04:00
Stephen Canon 84044a8382 Merge pull request #209 from stephentyrone/unnecessary-endian
Remove big/little endiant distinction in representation of DoubleWidth
2021-11-03 08:38:28 -04:00
Stephen Canon db932c9871 Remove big/little endiant distinction in representation of DoubleWidth
This doesn't really add anything that we need; we might as well simply pick one.
2021-11-03 08:22:25 -04:00
Stephen Canon b501ca406c Merge pull request #197 from benrimmington/experimental
Add the `DoubleWidth` type
2021-10-27 15:48:29 -04:00
be0534a3e3 Add the DoubleWidth type
Co-authored-by: Nate Cook <natecook@apple.com>
Co-authored-by: Max Moiseev <moiseev@users.noreply.github.com>
Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>
2021-10-27 18:14:10 +01:00
Stephen Canon c74d817e8d Merge pull request #208 from markuswntr/two-sum
Add `Augmented.sum(_:_:)` aka "twoSum"
2021-10-27 12:27:16 -04:00
Markus Winter 05366d7f4a Revert names of temporary variables 2021-10-27 08:48:54 +02:00
Markus WinterandXiaodi Wu 6ec74ec80e Fix source code formatting
Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>
2021-10-27 08:28:25 +02:00
Markus Winter d4a440fd05 Update range of random values in test cases 2021-10-26 16:27:04 +02:00
Markus Winter f6e5563514 Fix argument ordering in twoSum and add test cases 2021-10-26 15:57:30 +02:00
Markus Winter 8b05d1c8e0 Update comments on the difference of sum(_:_:) and sum(large:small:) 2021-10-21 10:55:24 +02:00
Markus Winter 1e724835bd Add twoSum to augmented arithmetic 2021-10-20 23:47:27 +02:00
Stephen Canon f956c239e1 Merge pull request #203 from stephentyrone/rounding
Right shift and division with rounding.
2021-10-15 11:40:53 -04:00
Stephen Canon af5393445b Add note that integer utilities isn't stable yet. 2021-10-14 15:00:00 -04:00
Stephen Canon 43e1d4d049 Update README.md
Added link to `IntegerUtilities` module.
2021-10-14 14:58:28 -04:00
Stephen Canon 9c4bd83ca4 Update README.md 2021-10-14 14:55:27 -04:00
Stephen Canon b37b64db2e Update README.md 2021-10-14 14:53:57 -04:00
Stephen Canon 0acd49c55f Take advantage of GFM footnotes in the README. 2021-10-14 14:53:35 -04:00
Stephen Canon 24d8f51bb3 Add tests for remainder(dividingBy: -1). 2021-10-14 10:39:39 -04:00
Stephen Canon 3eaa0b3b77 Additional documentation for division/shift with rounding
Also simplifies check logic for divide with rounding, which is a modest speedup for testing.
2021-10-13 16:44:52 -04:00
Stephen Canon 710ca088d5 Renamed shifted(right:) to shifted(rightBy:). 2021-10-13 11:08:09 -04:00
Stephen Canon 1b3e3f12ed Merge pull request #207 from markuswntr/patch-1
Fix a minor typo in the comments of the sinh decomposition
2021-10-13 10:56:34 -04:00
Markus Winter 63df367680 Fix a typo in the comments of sinh expression 2021-10-13 11:47:45 +02:00
Stephen Canon 501f58252a Added division with rounding operations. 2021-10-12 17:16:57 -04:00
Stephen Canon 9837c10f9e Update README.md to refer to 1.0.0 instead of 0.1.0 2021-10-02 12:49:24 -04:00
Stephen Canon dec7339db4 Renamed RoundingMode.trap to .requireExact
Also implemented some basic statistical tests for .stochastic and reorganized code a little bit. The statistical justification of the thresholds for these tests should be explained a bit more, and we should decide on a policy in general for statistical tests that may fail sporadically, but these shouldn't be very noisy for now.
2021-09-28 11:29:10 -04:00
Stephen Canon cddd5e626d Re-arrange some things. 2021-09-26 21:54:32 -04:00
Stephen Canon 92eb76200d Cursory documentation for shifted(right:). 2021-09-26 21:43:02 -04:00
Stephen Canon eeaf9e384a More rounding mode documentation. 2021-09-26 21:24:30 -04:00
Stephen Canon d78c067765 Some documentation work. 2021-09-26 17:05:12 -04:00
Stephen Canon c124585c19 Skeleton of integer shift with rounding.
Fairly correct implementation of right-shift with rounding. Also fairly efficient, though I'm sure I'll find some cases where we're generating uncessary overflow checks upon further inspection. Nonetheless, a decent enough start.
2021-09-26 16:23:58 -04:00
Stephen Canon caca93c5c6 Merge pull request #202 from RahulBhalley/patch-1
Removed number lines for easy clipboard copying.
2021-09-26 16:08:19 -04:00
ਰਾਹੁਲ ਭੇਲੇ c3806f23ff Removed number lines for easy clipboard copying. 2021-09-25 15:11:26 +05:30
Stephen Canon bc17ae6a82 Merge pull request #201 from stephentyrone/integer-utils-readme
Resolve warnings in 5.5 build, add skeleton readme for integer utilities
2021-09-20 13:15:57 -04:00
Stephen Canon e22ff866a4 Add GCD files to CMake build. 2021-09-20 12:35:22 -04:00
Stephen Canon abb899865e resolve warnings in 5.5 tools build, add skeleton readme for integer utilities 2021-09-20 09:53:38 -04:00
Stephen Canon b6f4c44221 Merge pull request #200 from Saklad5/patch-1
Fix typo in AlgebraicField documentation
2021-09-20 09:13:52 -04:00
Jeremy Saklad ae38370107 Fix typo in AlgebraicField documentation
“distributitve” should be spelled “distributive”.
2021-09-17 14:21:34 -05:00
Stephen Canon 9d84cefefa Merge pull request #189 from NevinBR/patch-6
GCD function for BinaryInteger
2021-09-10 11:04:07 -04:00
NevinBR f2cfa8d668 Fixed typo 2021-09-10 00:04:53 -04:00
NevinBR bd68569533 Commented out ExpectFailure tests for gcd 2021-09-10 00:03:31 -04:00
NevinBR 85264c808c Reworded doc comment for gcd 2021-09-09 23:05:45 -04:00
Stephen Canon b505d3ca1d Merge pull request #198 from stephentyrone/clarify-stability-differentiable
Clarify that differentaible API is not stable.
2021-08-31 16:29:32 -04:00
Stephen Canon 7738390f54 Merge pull request #196 from stephentyrone/excluded-filenames
Explicitly exclude CMakeLists.txt and README.md files from all targets.
2021-08-31 12:35:20 -04:00
Stephen Canon 5f28ad0e97 Explicitly exclude CMakeLists.txt and README.md files from all targets.
If/when we bump swift-tools-version to 5.3 or greater, swift-pm will start complaining about these, so let's explicitly exclude them now.
2021-08-31 12:31:58 -04:00
Stephen Canon 63edd6769c Update README for 1.0.0. 2021-08-31 11:38:38 -04:00
NevinBR 8552becf91 Documented overflow behavior of gcd 2021-08-31 11:19:22 -04:00
NevinBR 89c4e42e48 Added tests for gcd overflow on Int.min 2021-08-31 11:10:40 -04:00
NevinBR 67af2fe0d9 Simplified gcd implementation 2021-08-30 17:32:03 -04:00
NevinBR 83c378f2f4 Update GCDTests.swift 2021-08-30 17:29:05 -04:00
NevinBR b8f452189b Made gcd a free function 2021-08-30 17:28:44 -04:00
Stephen Canon 0289df5635 Merge pull request #192 from apple/add-integer-utilities-dependency
Add missing IntegerUtilities dependency for Numerics module
2021-08-27 09:05:13 -04:00
Stephen Canon b9415c9ad2 Add missing IntegerUtilities dependency for Numerics module 2021-08-27 09:01:35 -04:00
Stephen Canon b68a81dbdd Merge pull request #191 from apple/revert-187-remove-sub-libraries
Revert "Remove Real and Complex _libraries_; keep modules."
2021-08-27 08:48:57 -04:00
Stephen Canon 21ff6d38fd Revert "Remove Real and Complex _libraries_; keep modules." 2021-08-27 08:45:25 -04:00
NevinBR 4fbcb11f03 Improved GCD documentation 2021-08-26 19:49:13 -04:00
Stephen Canon e29479b3aa Merge pull request #190 from stephentyrone/cmake-integer-utilities
CMake build support for the IntegerUtilities module.
2021-08-26 19:38:04 -04:00
Stephen Canon 996cf7f5b9 CMake build support for the IntegerUtilities module. 2021-08-26 15:18:40 -04:00
NevinBR 632919ce2a Create GCDTests.swift 2021-08-26 14:56:04 -04:00
NevinBR 909a77c3d9 Create GCD.swift
Binary GCD algorithm
2021-08-26 14:51:05 -04:00
Stephen Canon 4a6730b024 Merge pull request #188 from stephentyrone/rotate
Setup IntegerUtilities module, implement bitwise rotates.
2021-08-26 08:57:24 -04:00
Stephen Canon 84474a3410 Initial setup of IntegerUtilities module.
Seeded with rotate(right:) and rotate(left:) on FixedWidthInteger. These implementations are basically sane, but need documentation written for users who are not already familiar with bitwise rotation.
2021-08-25 15:36:24 -04:00
Stephen Canon 97dfcff73b Merge pull request #187 from apple/remove-sub-libraries
Remove Real and Complex _libraries_; keep modules.
2021-08-25 11:04:00 -04:00
Stephen Canon 988f1e1cea Remove Real and Complex _libraries_; keep modules.
These are vestigial, and not needed to support swift-pm.
2021-08-25 10:52:07 -04:00
Stephen Canon 32c2b64370 Merge pull request #186 from apple/complex-readme
Update README.md
2021-08-20 09:29:44 -04:00
Stephen Canon ac7a9a9a92 Merge pull request #185 from stephentyrone/reciprocal-documentation
Further expand documentation of `reciprocal` with some example use.
2021-08-20 09:20:07 -04:00
Stephen Canon 3d6bff6cae Update README.md 2021-08-20 09:18:28 -04:00
Stephen CanonandXiaodi Wu 12148ffa66 Update Sources/RealModule/Real.swift
Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>
2021-08-20 09:06:44 -04:00
Stephen CanonandXiaodi Wu 3a5c73964b Update Sources/RealModule/Real.swift
Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>
2021-08-20 09:06:36 -04:00
Stephen CanonandXiaodi Wu 32f48e6b73 Update Sources/RealModule/Real.swift
Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>
2021-08-20 09:06:27 -04:00
Stephen CanonandXiaodi Wu 05440473eb Update Sources/ComplexModule/Arithmetic.swift
Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>
2021-08-20 09:06:10 -04:00
Stephen CanonandXiaodi Wu 342d38eb3b Update Sources/RealModule/AlgebraicField.swift
Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>
2021-08-20 09:05:56 -04:00
Stephen Canon ecc77886a1 Update Sources/ComplexModule/Arithmetic.swift 2021-08-19 21:20:58 -04:00
Stephen Canon 10e75aa392 Further expand documentation of reciprocal with some example use. 2021-08-19 20:47:36 -04:00
Stephen Canon d7e692e414 Merge pull request #182 from stephentyrone/more-documentation-for-1.0
Add some documentation for AlgebraicField ops, minor fix for Augmented.
2021-08-19 16:46:36 -04:00
Stephen Canon faf13772af Add some documentation for AlgebraicField ops, minor fix for Augmented. 2021-08-19 14:50:24 -04:00
Stephen Canon 17f5b59a07 Merge pull request #181 from stephentyrone/document-augmented-arithmetic
Document the Augmented enum in RealModule in advance of 1.0
2021-08-19 14:07:31 -04:00
Stephen Canon 702c6fc1d8 Document the Augmented enum in RealModule in advance of 1.0 2021-08-19 14:00:52 -04:00
Stephen Canon f50a1acf2d Merge pull request #178 from kylemacomber/remove-xcodesamplecode-plist
Remove .xcodesamplecode.plist, which prevents editing markdown from Xcode
2021-03-23 09:03:31 -04:00
Stephen Canon 2aa93ccf24 Merge pull request #179 from stephentyrone/remove-workflows
remove workflows, no longer needed.
2021-03-21 16:01:56 -04:00
Steve (Numerics) Canon 50161d39df remove workflows, no longer needed. 2021-03-21 16:01:23 -04:00
Kyle Macomber d34cff5a13 Remove .xcodesamplecode.plist, which prevents editing markdown from Xcode 2021-03-19 12:40:59 -07:00
Stephen Canon 9f55a78685 Merge pull request #175 from stephentyrone/eighty-columns-wide-my-father-lies
80-column formatting for source doc comments
2021-03-03 20:01:35 -05:00
Steve (Numerics) Canon 5827f9a943 80-column formatting for source doc comments
Tidying, plus a few small edits. This commit should not include any code changes.
2021-03-03 14:01:09 -05:00
Stephen Canon 3cad9b69a0 Update README.md
Update version number in sample code.
2021-02-21 21:22:01 -05:00
Stephen Canon 6583ac70c3 Merge pull request #172 from stephentyrone/float16-availability
Adjust Float16 availability for Swift 5.4 toolchains.
2021-02-19 17:38:49 -05:00
Steve (Numerics) Canon 97852afaf5 Adjust Float16 availability for Swift 5.4 toolchains.
In older toolchains, Float16 is marked unavailable on all mac targets; starting with the 5.4 toolchain, it is available starting in macOS 11.0 when targeting Apple Silicon.
2021-02-19 15:53:15 -05:00
Steve (Numerics) Canon 105b59b8a4 Remove vestigal C complex shims.
These used to be used by some test appratus, but they are no longer
used and can be removed.
2021-02-19 15:16:30 -05:00
Steve (Numerics) Canon 0cf166da79 Remove zeroTangentVectorInitializer test, as the requirement has been removed from Swift main. 2021-02-19 15:11:21 -05:00
Stephen Canon 4a2cbc186b Merge pull request #166 from NevinBR/patch-5
Cleaning up some comments
2020-11-15 12:22:56 -05:00
NevinBR 5a7eb37c19 Cleaned up some comments 2020-11-11 14:05:55 -05:00
Stephen Canon 198da2adf9 Merge pull request #165 from stephentyrone/complex-elfns-inlinable
Mark all complex elementary functions inlinable
2020-11-09 16:43:31 -05:00
Stephen Canon 26c51aca1b Mark all complex elementary functions inlinable
This is kind of dubious, but necessary for performance reasons until we get dependable cross-module specialization. Also has a minor test fix for 32b platforms.
2020-11-09 16:41:45 -05:00
Stephen Canon c5a3504143 Merge pull request #164 from compnerd/update
build: update file lists for `RealModule` and `_TestSupport`
2020-11-09 14:45:44 -05:00
Saleem Abdulrasool 00c6183670 build: update file lists for RealModule and _TestSupport
Add new files to the list that were missed in the CMakeLists.txt
updates.
2020-11-09 11:23:48 -08:00
Stephen Canon ae364a28f0 Merge pull request #162 from apple/complex-elfns
Conform Complex to Elementary Functions
2020-11-09 11:39:18 -05:00
Stephen Canon e042c13415 Merge pull request #150 from markuswntr/master
Refactor README.md and include Approximate Equality as part of the RealModule.
2020-11-09 11:28:25 -05:00
Stephen Canon 16837299c1 Added inverse trig and hyperbolics, some rough test coverage. 2020-11-09 11:25:08 -05:00
Stephen Canon 0c066bd268 Merge pull request #155 from stephentyrone/complex-log1p
Augmented arithmetic implementations of log and log(onePlus:) for enhanced accuracy close to the circle where the real part of the result vanishes.
2020-11-05 15:15:35 -05:00
Stephen Canon 2b4c6701f2 log and log(onePlus:) implementations for Complex
These significantly improve on the state of the art for arguments close to the circle where the result vanishes, producing good componentwise relative accuracy as well as relative accuracy in the complex norm.

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

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

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

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

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

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

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

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

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

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

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

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

I want to write some more documentation and examples here, but this is
enough to discuss and start review.
2020-07-14 12:33:25 -04:00
Stephen Canon cfeda4df2d s/positive/non-negative/ for minimumScale. 2020-07-14 12:33:25 -04:00
Stephen Canon f275f7df53 Wrote some rough documentation
Also removed the default absolute tolerance, because in writing the documentation I realized that I couldn't reasonably justify having one.
2020-07-14 12:33:25 -04:00
Stephen Canon 7c0eb30664 Update complex test dependencies. 2020-07-14 12:33:25 -04:00
Stephen Canon 91ecc8a3b6 First crack at dusting approximate comparisons back off. 2020-07-14 12:33:25 -04:00
Stephen Canon 40b5a03063 Merge pull request #105 from compnerd/cmake
build: add initial CMake based build system
2020-07-03 09:49:53 -04:00
Stephen Canon 110beefe0b Merge pull request #105 from compnerd/cmake
build: add initial CMake based build system
2020-07-03 09:45:25 -04:00
Stephen Canon 085f6dab2e Merge branch 'master' into swift-5.3 2020-07-01 09:31:40 -04:00
Stephen Canon e97070e36c file -> filePath, too. 2020-06-29 14:52:30 -04:00
Stephen Canon 93b8e9f0df Float16 is unavailable on macOS 11. 2020-06-29 14:50:37 -04:00
Saleem Abdulrasool 697e9351e8 build: support the test suite on Windows 2020-06-25 09:46:54 -07:00
Saleem Abdulrasool f30f73ed10 build: add initial CMake based build system
This adds a CMake based build, which enables the build of swift-numerics
on Windows.  This currently does not add the test suite to the build as
there are still some issues to work out in building the full test suite
which require additional math operations to fully build.
2020-06-25 09:46:54 -07:00
Robert Thompson 935eac199c Merge pull request #7 from benrimmington/BigInt
[BigInt] Rename module
2020-06-11 15:13:18 -04: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
Ben Rimmington 2f60891517 [BigInt] Rename module
See also: apple/swift-numerics#97
2020-04-24 12:39:49 +01: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
Robert Thompson 5ea7711e02 Probably a slightly faster way to get trailingZeroBitCOunt 2020-02-19 15:15:42 -05:00
Robert Thompson b74c1ce133 Fix trailingZeroBitCount as per @nixberg
Also add a couple tests for it
2020-02-14 16:23:37 -05:00
Robert Thompson cd88f161eb Fix two tests for arm32, should all pass now 2020-01-29 10:48:46 -05:00
Robert Thompson aaeb9029e9 Another fix for conversion of multi-word Ints 2020-01-29 10:42:52 -05:00
Robert Thompson 52e7e70caf Actual fix for multi-word integer types 2020-01-29 10:07:34 -05:00
Robert Thompson caeeaaa9dd Another fix for arm32 and actually for anything with multi-word ints
UInt64, Int64, etc have more than one word on 32-bit architectures
2020-01-29 09:55:10 -05:00
Robert Thompson cc5f7e5d18 Apparently the @testable was only working in Xcode 2020-01-28 17:55:39 -05:00
Robert Thompson feeac39506 Whoops, this is better 2020-01-28 17:53:23 -05:00
Robert Thompson 19951768df Another case where we'd get wrong negatives possibly 2020-01-28 17:51:45 -05:00
Robert Thompson 87900161d6 Normalize the remainder! 2020-01-28 17:36:55 -05:00
Robert Thompson 6e0f0094dc fix tests compiling on arm32 2020-01-28 16:09:32 -05:00
Robert Thompson 7d6e5cda3e Clean up division a bit more 2020-01-28 16:02:30 -05:00
Robert Thompson e4f5257d0a fix division
Re-write _findQhat from scratch, add check for division by single digit
number in _div
2020-01-28 14:05:22 -05:00
Robert Thompson 9e1a1f5e8a Merge branch 'BigInt' of github.com:rothomp3/swift-numerics into BigInt 2020-01-27 12:31:33 -05:00
Robert Thompson 7026eb4085 more tests for division 2020-01-27 12:31:26 -05:00
Robert Thompson 1a29830c82 Merge pull request #6 from benrimmington/BigInt
[BigIntTests] Use generic testBinaryFloatingPoint
2020-01-27 12:17:45 -05:00
Ben Rimmington 5919d3f48f [BigIntTests] Use generic testBinaryFloatingPoint 2020-01-27 15:17:43 +00: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
Robert Thompson e3d01dd680 First step to increasing test coverage 2020-01-22 10:16:01 -05:00
Robert Thompson 90d5ddd1f6 Fix failing tests (@benrimminton: it turned out simple)
If the last computed digit of a BinaryFloatingPoint source is > Int.max,
we need to add an extra zero digit to the end so we're not negative!
2020-01-21 16:59:28 -05:00
Robert Thompson e41c631052 Merge pull request #5 from benrimmington/BigInt
[BigInt] Add tests for floating-point conversions
2020-01-21 16:49:41 -05:00
Ben Rimmington 6e85aa2bbd [BigInt] Revert the BinaryFloatingPoint conversion 2020-01-21 19:47:19 +00:00
Ben Rimmington ceee280ebe [BigIntTests] Don't use the CLongDouble typealias 2020-01-21 18:09:39 +00:00
Ben Rimmington 3501fa7c61 [BigInt] Restore precondition message for inf/nan 2020-01-21 17:30:47 +00:00
Ben Rimmington ca75d2d124 [BigInt] Move pow(_:_:) into test-only extension 2020-01-21 16:24:51 +00:00
Ben Rimmington ffdaf86868 [BigIntTests] Change fac(BigInt(512)) to BigInt.fac(512) 2020-01-21 13:30:21 +00:00
Ben Rimmington bf9afea2eb [BigIntTests] Add testFloatingPoint_signalingNaN() 2020-01-21 08:36:48 +00:00
Stephen Canon 7bd2909875 Merge pull request #91 from apple/FieldProtocol
Introduce AlgebraicField protocol
2020-01-20 13:35:59 -05:00
Ben Rimmington 4c425513cd [BigIntTests] Use fac(_:) to test Strideable 2020-01-20 13:05:49 +00:00
Ben Rimmington fc7b3bf44f [BigIntTests] Update expected descriptions 2020-01-20 11:48:46 +00:00
Ben Rimmington 0dee6d0927 [BigIntTests] Move other test methods 2020-01-20 11:05:12 +00:00
Ben Rimmington cfc63e8adc [BigIntTests] Move testFloatingPoint_...() methods 2020-01-20 10:30:16 +00: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
Ben Rimmington 01c30961ef [BigIntTests] Move the typealias of CLongDouble 2020-01-19 20:31:22 +00:00
Ben Rimmington 05a45984d9 [BigInt] Update signum(), add testSignum() 2020-01-19 19:48:07 +00:00
Ben Rimmington cfc2cd7c97 [BigIntTests] Add measure {} to testFactorial() 2020-01-19 12:32:11 +00:00
Ben Rimmington 98023c3575 [BigInt] Combine *= and << into simpler <<= 2020-01-19 10:31:39 +00:00
Ben Rimmington 506ea36331 [BigIntTests] Update testFloatingPoint_random() 2020-01-19 09:37:20 +00:00
Ben Rimmington 1b733de54a [BigInt] Fix initializers with BinaryFloatingPoint 2020-01-18 19:44:27 +00:00
Ben Rimmington 937c292898 [BigIntTests] Add testFloatingPoint_...() methods
The testFloatingPoint_greatestFiniteMagnitude() method currently fails.
2020-01-18 19:38:05 +00:00
Robert Thompson 49121f353a Merge pull request #4 from benrimmington/BigInt
[BigIntTests] Add min and max Int1024 descriptions
2020-01-17 14:23:20 -05:00
Ben Rimmington e632de88c4 [BigIntTests] Add testFactorial() 2020-01-17 13:51:21 +00:00
Ben Rimmington b03af80076 [BigInt] Change self = -self to self.negate() 2020-01-17 07:33:36 +00:00
Ben Rimmington 6f4374cd99 [BigIntTests] Add min and max Int1024 descriptions 2020-01-17 07:32:52 +00:00
Robert Thompson d36d9ce02e Remove superfluous CustomStringConvertible impl 2020-01-16 17:08:52 -05:00
Robert Thompson fac716fdb2 Fix implementation of <
Previously, all BigInts were less than themselves. This is no longer
true. Discovered thanks to @lorentey and @benrimmington re: discussion
on explicit implementation of `!=`.
2020-01-16 15:15:37 -05:00
Robert Thompson 7ca51a3e50 normalize words in the BinaryInteger bitPattern init
as per @lorentey
2020-01-16 14:25:46 -05:00
Robert Thompson 1ddbbfe0d1 Rename internal init as per @lorentey 2020-01-16 14:24:24 -05:00
Robert Thompson eab5a94499 Merge pull request #3 from benrimmington/BigInt
[BigInt] Update tests and SignedNumeric operator
2020-01-16 14:19:55 -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
Ben Rimmington a6ecb7442a [BigIntTests] Update testRadicesAndNumerals() 2020-01-16 14:50:19 +00:00
Ben Rimmington 2410717a17 [BigInt] Update the SignedNumeric prefix operator 2020-01-16 13:12:29 +00:00
Ben Rimmington 7ae61f775b [BigIntTests] Update testLosslessStringConvertible 2020-01-16 13:04:39 +00:00
Ben Rimmington fe212356fd [BigIntTests] Rename testRandomDescriptions() 2020-01-16 12:40:02 +00:00
Ben Rimmington 830927ecbb [BigIntTests] Rewrite testMinMaxDescriptions() 2020-01-16 12:19:33 +00:00
Robert Thompson fd8049e481 remove debugging code from test 2020-01-15 15:25:11 -05:00
Robert Thompson 0b121fd774 Fix failing tests (@benrimmington)
We were not correctly handling the case where two single-word operands
added up to a number > Int.max. Also, negate (and `-`) was not removing
excess words, resulting in identical numbers not comparing equal!
2020-01-15 15:13:58 -05:00
Robert Thompson 72f1cb3554 Merge branch 'BigInt' of github.com:rothomp3/swift-numerics into BigInt 2020-01-15 14:15:36 -05:00
Robert Thompson 0e58379b4f explicitly call out TAOCP by Knuth 2020-01-15 14:15:27 -05:00
Robert Thompson ddaf8be1a2 Merge pull request #2 from benrimmington/BigInt
[BigInt] Update LosslessStringConvertible, etc.
2020-01-15 14:07:37 -05:00
Ben Rimmington 9ddc664ef1 [BigIntTests] Remove messages from XCTAssert calls 2020-01-15 06:51:21 +00:00
Ben Rimmington b39dd05db3 [BigIntTests] Update the testExample() method 2020-01-15 06:44:41 +00:00
Ben Rimmington 1cb69383a5 [BigIntTests] Wrap to 80 characters 2020-01-15 03:53:16 +00:00
Ben Rimmington c9d72fc3ae [BigIntTests] Trim trailing whitespace 2020-01-15 03:34:14 +00:00
Ben Rimmington 4ec520a726 [BigIntTests] Update the testCodable() method
Top-level JSON fragments might fail on Linux, so encode Range<BigInt> instead.

<https://bugs.swift.org/browse/SR-6163>
2020-01-15 03:30:50 +00:00
Ben Rimmington 8c378528de [BigInt] Update the Codable conformance 2020-01-15 00:59:46 +00:00
Ben Rimmington 3cf0b0cf74 [BigInt] Update the LosslessStringConvertible init
This performs 6x faster (measured with a 1000-digit string).

But it doesn't fix the testMinMaxDescriptions() failures.
2020-01-15 00:47:04 +00:00
Ben Rimmington f6a3d2d4e4 [BigIntTests] Add testMinMaxDescriptions() method
This currently fails for:

BigInt(Int64.min) - 2
BigInt(Int64.min) - 1
BigInt(Int64.max) + 1
BigInt(Int64.max) + 2
2020-01-15 00:17:17 +00:00
Robert Thompson 036ab5fe94 Conform to Codable with default implementation
Since we have only a single stored property which itself already
conforms to `Codable`, there's no need to go down the rabbit hole of
explicitly implementing it. If someone wants to do it to produce a more
human-readable JSON (eg, as a string instead of an array of integers),
then you're welcome to.
2020-01-14 15:07:08 -05:00
Robert Thompson 7c6e2ce0d8 Explicitly implement public mutating func negate()
As per the TODO put in by @benrimmington. I'm not 100% sure this is
actually better than the default implementation provided by
`SignedNumeric`, but there's a chance it is.
2020-01-14 15:00:38 -05:00
Robert Thompson 3a4cc1c623 Merge pull request #1 from benrimmington/BigInt
[BigInt] Reorganize into extensions by conformance
2020-01-14 14:47:02 -05:00
Ben Rimmington 4d7e4e9b97 [BigInt] Rename private _findQhat method 2020-01-14 04:44:44 +00:00
Ben Rimmington 3c916262e0 [BigInt] Update bitWidth and magnitude properties 2020-01-14 02:46:47 +00:00
Ben Rimmington 831f06ac78 [BigInt] Add the MARK and TODO comments 2020-01-14 02:44:38 +00:00
Ben Rimmington d15400e6ab [BigInt] Add the Words typealias 2020-01-14 02:39:59 +00:00
Ben Rimmington 5be3b4e526 [BigInt] Move the BinaryInteger methods 2020-01-14 02:38:53 +00:00
Ben Rimmington acd8568864 [BigInt] Move the BinaryInteger operators 2020-01-14 02:36:23 +00:00
Ben Rimmington 11d5225f3b [BigInt] Move the BinaryInteger properties 2020-01-14 02:26:50 +00:00
Ben Rimmington 19d3491df4 [BigInt] Move the BinaryInteger initializers 2020-01-14 02:25:37 +00:00
Ben Rimmington 819ebd90c4 [BigInt] Move the SignedNumeric conformance 2020-01-14 02:16:00 +00:00
Ben Rimmington 5b84051f2a [BigInt] Move the Numeric conformance 2020-01-14 02:14:30 +00:00
Ben Rimmington cb5e7f3c7a [BigInt] Move the AdditiveArithmetic conformance 2020-01-14 02:09:45 +00:00
Ben Rimmington 5cb9b95ce8 [BigInt] Move the ExpressibleByIntegerLiteral conformance 2020-01-14 02:05:42 +00:00
Ben Rimmington 5db4a69e57 [BigInt] Move the LosslessStringConvertible conformance 2020-01-14 02:04:16 +00:00
Ben Rimmington 2419741a7c [BigInt] Move the CustomStringConvertible conformance 2020-01-14 02:00:12 +00:00
Ben Rimmington 368caf5b3f [BigInt] Move the Comparable conformance 2020-01-14 01:58:03 +00:00
Stephen Canon 1879299216 Avoid shadowing function argument by using a different name for local var. 2020-01-13 20:56:48 -05:00
Ben Rimmington a799618103 [BigInt] Move the Hashable conformance 2020-01-14 01:56:43 +00:00
Ben Rimmington dbf743b314 [BigInt] Move the Equatable conformance 2020-01-14 01:54:58 +00:00
Ben Rimmington 2f40de6195 [BigInt] Move _isNegative and _digits properties 2020-01-14 01:52:01 +00:00
Ben Rimmington 38073d2ab5 [BigInt] Move init(words:) and init(bitPattern:) 2020-01-14 01:49:26 +00:00
Ben Rimmington 2863c44182 [BigInt] Remove the isSigned property 2020-01-14 01:42:43 +00: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
Robert Thompson e490f1fc66 Explicitly implment hash(into:) per @benrimmington feedback
Technically, I believe the auto-generated implementation was already
doing exactly this, since `words` is the only stored property of
`BigInt`. However, it rarely hurts to be explicit.
2020-01-13 14:45:48 -05:00
Robert Thompson 67858690eb Update LosslessStringConvertible initializer
as per further suggestions from @Wildchild9, adding in the removing
leading zeros part I missed.
2019-12-30 16:01:04 -05:00
Robert Thompson cced27a6c0 Missed a spot where things should be alphabetical 2019-12-30 15:50:03 -05:00
Robert Thompson 821fcbd6a4 Update following suggestions from @benrimmington
Includes reformatting to use 2-space indentation and the correct file
headers, among other simplifications.
2019-12-30 15:46:18 -05:00
Robert Thompson b46dcf96c6 oops, change both occurrences of digitsAndDash 2019-12-30 15:13:26 -05:00
Robert ThompsonandBen Rimmington eceae6d7bd Update Sources/BigInt/BigInt.swift
As per benrimmington's excellent suggestion

Co-Authored-By: Ben Rimmington <me@benrimmington.com>
2019-12-30 15:12:20 -05:00
Robert Thompson ac50a90a60 whoops 2019-12-30 10:44:48 -05:00
Robert Thompson 524dc69ae1 slightly refactor LosslessStringConvertible initializer as per PR feedback 2019-12-30 10:41:40 -05:00
Robert Thompson ea2b6f8deb BigInt no longer depends on NumericsShims 2019-12-30 10:33:00 -05:00
Robert Thompson cb56525312 Address PR feedback
Eliminate unnecessary math function calls, and also handle floating
point edge cases better.
2019-12-30 10:33:00 -05:00
Robert Thompson bc2f9fb7c6 Use NumericShims for math functions 2019-12-30 10:33:00 -05:00
Robert Thompson 96d41bcf9f Initial commit of BigInt 2019-12-30 10:33:00 -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
Stephen Canon 2b63fc844e Merge pull request #78 from stephentyrone/lengthSquared
Rename unsafeLengthSquared -> lengthSquared
2019-11-20 16:27:40 -05:00
Stephen Canon f6c2c34910 Rename unsafeLengthSquared -> lengthSquared
Also further tweak polar init for Complex to allow (-infinity, θ) when θ is not finite.
2019-11-20 16:15:10 -05:00
Stephen Canon f1d78c4d98 Merge pull request #77 from stephentyrone/zero-length-polar-init
Address behavior of Complex.init(length:phase:)
2019-11-20 16:03:09 -05:00
Stephen CanonandRichard Wei 5931d036ab Update Sources/Complex/Complex.swift
Co-Authored-By: Richard Wei <rxrwei@gmail.com>
2019-11-20 14:56:31 -05:00
Stephen Canon 565839d673 Address behavior of Complex.init(length:phase:)
Instead of being failable, adopt the following policy:
- If length is zero or infinity, the phase does not matter.
- Otherwise, the phase must be finite or a precondition failure occurs.

Discussion here: https://github.com/apple/swift-numerics/issues/51
2019-11-20 14:32:19 -05:00
Stephen Canon f96c6c2066 Rename swift.yml to macos.yml 2019-11-18 16:34:11 -05:00
Stephen Canon ee54cc2075 Let's tryout workflows 2019-11-13 17:17:32 -05:00
89 changed files with 11109 additions and 1428 deletions

No files matched your search

+1
View File
@@ -4,3 +4,4 @@
/Packages
/*.xcodeproj
/.swiftpm
.*.sw?
+4
View File
@@ -0,0 +1,4 @@
version: 1
builder:
configs:
- documentation_targets: [Numerics, RealModule, ComplexModule, BigIntModule]
-5
View File
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array/>
</plist>
+33
View File
@@ -0,0 +1,33 @@
#[[
This source file is part of the Swift Numerics open source project
Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
#]]
cmake_minimum_required(VERSION 3.16)
project(swift-numerics
LANGUAGES Swift)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/modules)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift)
include(CTest)
include(SwiftSupport)
add_subdirectory(Sources)
if(BUILD_TESTING)
add_subdirectory(Tests)
endif()
get_property(SWIFT_NUMERICS_EXPORTS GLOBAL PROPERTY SWIFT_NUMERICS_EXPORTS)
export(TARGETS ${SWIFT_NUMERICS_EXPORTS}
NAMESPACE SwiftNumerics::
FILE swift-numerics-config.cmake
EXPORT_LINK_INTERFACE_LIBRARIES)
+90 -12
View File
@@ -1,9 +1,9 @@
// swift-tools-version:5.0
// swift-tools-version:5.5
//===--- Package.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
// Copyright (c) 2019-2021 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
@@ -12,22 +12,100 @@
import PackageDescription
let excludedFilenames = ["CMakeLists.txt", "README.md"]
let package = Package(
name: "swift-numerics",
products: [
.library(name: "Complex", targets: ["Complex"]),
.library(name: "BigIntModule", targets: ["BigIntModule"]),
.library(name: "ComplexModule", targets: ["ComplexModule"]),
.library(name: "Numerics", targets: ["Numerics"]),
.library(name: "Real", targets: ["Real"]),
],
dependencies: [
.library(name: "RealModule", targets: ["RealModule"]),
],
targets: [
.target(name: "Complex", dependencies: ["Real"]),
.target(name: "Numerics", dependencies: ["Complex", "Real"]),
.target(name: "NumericsShims", dependencies: []),
.target(name: "Real", dependencies: ["NumericsShims"]),
// MARK: - Public API
.target(
name: "BigIntModule",
dependencies: [],
exclude: excludedFilenames
),
.testTarget(name: "ComplexTests", dependencies: ["Complex", "NumericsShims"]),
.testTarget(name: "RealTests", dependencies: ["Real"]),
.target(
name: "ComplexModule",
dependencies: ["RealModule"],
exclude: excludedFilenames
),
.target(
name: "IntegerUtilities",
dependencies: [],
exclude: excludedFilenames
),
.target(
name: "Numerics",
dependencies: ["ComplexModule", "IntegerUtilities", "RealModule", "BigIntModule"],
exclude: excludedFilenames
),
.target(
name: "RealModule",
dependencies: ["_NumericsShims"],
exclude: excludedFilenames,
linkerSettings: [
.linkedLibrary("m", .when(platforms: [.linux, .android]))
]
),
// MARK: - Implementation details
.target(
name: "_NumericsShims",
exclude: excludedFilenames
),
.target(
name: "_TestSupport",
dependencies: ["Numerics"],
exclude: ["CMakeLists.txt"]
),
// MARK: - Unit test bundles
.testTarget(
name: "BigIntTests",
dependencies: ["BigIntModule"]
),
.testTarget(
name: "ComplexTests",
dependencies: ["_TestSupport"],
exclude: ["CMakeLists.txt"]
),
.testTarget(
name: "IntegerUtilitiesTests",
dependencies: ["IntegerUtilities", "_TestSupport"],
exclude: ["CMakeLists.txt"]
),
.testTarget(
name: "RealTests",
dependencies: ["_TestSupport"],
exclude: ["CMakeLists.txt"]
),
// MARK: - Test executables
.executableTarget(
name: "ComplexLog",
dependencies: ["Numerics", "_TestSupport"],
path: "Tests/Executable/ComplexLog"
),
.executableTarget(
name: "ComplexLog1p",
dependencies: ["Numerics", "_TestSupport"],
path: "Tests/Executable/ComplexLog1p"
)
]
)
+111
View File
@@ -0,0 +1,111 @@
// swift-tools-version:5.4
//===--- Package.swift ----------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2021 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import PackageDescription
let excludedFilenames = ["CMakeLists.txt", "README.md"]
let package = Package(
name: "swift-numerics",
products: [
.library(name: "BigIntModule", targets: ["BigIntModule"]),
.library(name: "ComplexModule", targets: ["ComplexModule"]),
.library(name: "Numerics", targets: ["Numerics"]),
.library(name: "RealModule", targets: ["RealModule"]),
],
targets: [
// MARK: - Public API
.target(
name: "BigIntModule",
dependencies: [],
exclude: excludedFilenames
),
.target(
name: "ComplexModule",
dependencies: ["RealModule"],
exclude: excludedFilenames
),
.target(
name: "IntegerUtilities",
dependencies: [],
exclude: excludedFilenames
),
.target(
name: "Numerics",
dependencies: ["ComplexModule", "IntegerUtilities", "RealModule", "BigIntModule"],
exclude: excludedFilenames
),
.target(
name: "RealModule",
dependencies: ["_NumericsShims"],
exclude: excludedFilenames,
linkerSettings: [
.linkedLibrary("m", .when(platforms: [.linux, .android]))
]
),
// MARK: - Implementation details
.target(
name: "_NumericsShims",
exclude: excludedFilenames
),
.target(
name: "_TestSupport",
dependencies: ["Numerics"],
exclude: ["CMakeLists.txt"]
),
// MARK: - Unit test bundles
.testTarget(
name: "BigIntTests",
dependencies: ["BigIntModule"]
),
.testTarget(
name: "ComplexTests",
dependencies: ["_TestSupport"],
exclude: ["CMakeLists.txt"]
),
.testTarget(
name: "IntegerUtilitiesTests",
dependencies: ["IntegerUtilities", "_TestSupport"],
exclude: ["CMakeLists.txt"]
),
.testTarget(
name: "RealTests",
dependencies: ["_TestSupport"],
exclude: ["CMakeLists.txt"]
),
// MARK: - Test executables
.executableTarget(
name: "ComplexLog",
dependencies: ["Numerics", "_TestSupport"],
path: "Tests/Executable/ComplexLog"
),
.executableTarget(
name: "ComplexLog1p",
dependencies: ["Numerics", "_TestSupport"],
path: "Tests/Executable/ComplexLog1p"
)
]
)
+99 -22
View File
@@ -1,63 +1,140 @@
# Swift Numerics
## Introduction
Swift Numerics provides a set of modules that support numerical computing in Swift.
These modules fall broadly into two categories:
- API that is too specialized to go into the standard library, but which is sufficiently general to be centralized in a single common package.
- API that is under active development toward possible future inclusion in the standard library.
There is some overlap between these two categories, and API that begins in the first category may migrate to the second as it matures and new uses are discovered.
There is some overlap between these two categories, and an API that begins in the first category may migrate into the second as it matures and new uses are discovered.
Swift Numerics modules are fine-grained.
For example, if you need support for Complex numbers, you can import ComplexModule[^1] as a standalone module:
Swift Numerics modules are fine-grained; if you need support for Complex numbers, you can import the Complex module without pulling in everything else in the library as well:
```swift
import Complex
import ComplexModule
let z = Complex<Double>.i
```
However, there is also a top-level `Numerics` module that simply re-exports the complete public interface of swift-numerics:
There is also a top-level `Numerics` module that re-exports the complete public interface of Swift Numerics:
```swift
import Numerics
// All swift-numerics API is now available
// The entire Swift Numerics API is now available
```
Swift Numerics modules have minimal dependencies on other projects.
The current modules assume only the availability of the Swift and C standard libraries and the runtime support provided by compiler-rt.
Future expansion may assume the availability of other standard interfaces such as [BLAS (Basic Linear Algebra Subprograms)](https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms) and [LAPACK (Linear Algebra Package)](https://en.wikipedia.org/wiki/LAPACK), but modules with more specialized dependencies (or dependencies that are not available on all platforms supported by Swift) belong in a separate package.
Future expansion may assume the availability of other standard interfaces, such as [BLAS (Basic Linear Algebra Subprograms)](https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms) and [LAPACK (Linear Algebra Package)](https://en.wikipedia.org/wiki/LAPACK), but modules with more specialized dependencies (or dependencies that are not available on all platforms supported by Swift) belong in a separate package.
Because we intend to make it possible to adopt Swift Numerics modules in the standard library at some future point, Swift Numerics uses the same license and contribution guidelines as the Swift project.
## Process
Swift Numerics is a standalone library separate from the core Swift project.
In practice, it will act as a staging ground for some APIs that may eventually be incorporated into the Swift Standard Library, and when that happens such changes will be proposed to the Swift Standard Library using the established evolution process of the Swift project.
## Using Swift Numerics in your project
To use Swift Numerics in a SwiftPM project:
1. Add the following line to the dependencies in your `Package.swift` file:
```swift
.package(url: "https://github.com/apple/swift-numerics", from: "1.0.0"),
```
2. Add `Numerics` as a dependency for your target:
```swift
.target(name: "MyTarget", dependencies: [
.product(name: "Numerics", package: "swift-numerics"),
"AnotherModule"
]),
```
3. Add `import Numerics` in your source code.
## Source stability
The Swift Numerics package is source stable; version numbers follow [Semantic Versioning](https://semver.org).
The public API of the `swift-numerics` package consists of non-underscored declarations that are marked either `public` or `usableFromInline` in modules re-exported by the top-level `Numerics` module.
Interfaces that aren't part of the public API may continue to change in any release, including patch releases.
Note that contents of the `_NumericsShims` and `_TestSupport` modules, as well as contents of the `Tests` directory, explicitly are not public API.
The definitions therein may therefore change at whim, and the entire module may be removed in any new release.
If you have a use case that requires underscored operations, please raise an issue to request that they be made public API.
Future minor versions of the package may introduce changes to these rules as needed.
We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate.
Accordingly, from time to time, we expect that new versions of this package will require clients to upgrade to a more recent Swift toolchain release.
Requiring a new Swift release will only require a minor version bump.
## Contributing to Swift Numerics
Swift Numerics is a standalone library that is separate from the core Swift project, but it will sometimes act as a staging ground for APIs that will later be incorporated into the Swift Standard Library.
When that happens, such changes will be proposed to the Swift Standard Library using the established evolution process of the Swift project.
Swift Numerics uses GitHub issues to track bugs and features. We use pull requests for development.
To propose a new module:
### How to propose a new module
1. Raise an issue with the [new module] tag.
2. Raise a PR with an implementation sketch.
3. Once you have some consensus, ask an admin to create a feature branch against which PRs can be raised.
4. When the design has stabilized and is functional enough to be useful, raise a PR to merge the new module to master.
To propose a new feature for an existing module:
### How to propose a new feature for an existing module
1. Raise an issue with the [enhancement] tag.
2. Raise a PR with your implementation, and discuss the implementation there.
3. Once there is a consensus that the new feature is desirable and the design is suitable, it can be merged.
To fix a bug, or make smaller improvements:
1. Raise a PR with your change. Be sure to add test coverage for whatever changes you are making.
### How to fix a bug, or make smaller improvements
Questions about how to use Swift Numerics modules, or issues that are not clearly bugs can be discussed in the ["Swift Numerics" section of the Swift forums.](https://forums.swift.org/c/related-projects/swift-numerics)
1. Raise a PR with your change.
2. Make sure to add test coverage for whatever changes you are making.
### Forums
Questions about how to use Swift Numerics modules, or issues that are not clearly bugs can be discussed in the ["Swift Numerics" section of the Swift forums](https://forums.swift.org/c/related-projects/swift-numerics).
## Modules
1. [Real](Sources/Real/README.md)
2. [Complex](Sources/Complex/README.md)
1. [`RealModule`](Sources/RealModule/README.md)
2. [`ComplexModule`](Sources/ComplexModule/README.md)
3. [`IntegerUtilities`](Sources/IntegerUtilities/README.md) (on main only, not yet present in a released tag)
4. [`BigIntModule`](Sources/BigIntModule/README.md) (on branch only)
## Future expansion
1. [Approximate Equality](https://github.com/apple/swift-numerics/issues/3)
2. [Large Fixed-Width Integers](https://github.com/apple/swift-numerics/issues/4)
3. [Arbitrary-Precision Integers](https://github.com/apple/swift-numerics/issues/5)
4. [Shaped Arrays](https://github.com/apple/swift-numerics/issues/6)
5. [Decimal Floating-point](https://github.com/apple/swift-numerics/issues/7)
6. [Float16](https://github.com/apple/swift-numerics/issues/8)
1. [Large Fixed-Width Integers](https://github.com/apple/swift-numerics/issues/4)
2. [Arbitrary-Precision Integers](https://github.com/apple/swift-numerics/issues/5)
3. [Shaped Arrays](https://github.com/apple/swift-numerics/issues/6)
4. [Decimal Floating-point](https://github.com/apple/swift-numerics/issues/7)
[^1]: The module is named `ComplexModule` instead of `Complex` because Swift is currently unable to use the fully-qualified name for types when a type and module have the same name (discussion here: https://forums.swift.org/t/pitch-fully-qualified-name-syntax/28482).
This would prevent users of Swift Numerics who don't need generic types from doing things such as:
```swift
import Complex
// I know I only ever want Complex<Double>, so I shouldn't need the generic parameter.
typealias Complex = Complex.Complex<Double> // This doesn't work, because name lookup fails.
```
For this reason, modules that would have this ambiguity are suffixed with `Module` within Swift Numerics:
```swift
import ComplexModule
// I know I only ever want Complex<Double>, so I shouldn't need the generic parameter.
typealias Complex = ComplexModule.Complex<Double>
// But I can still refer to the generic type by qualifying the name if I need it occasionally:
let a = ComplexModule.Complex<Float>
```
The `Real` module does not contain a `Real` type, but does contain a `Real` protocol.
Users may want to define their own `Real` type (and possibly re-export the `Real` module)--that is why the suffix is also applied there.
New modules have to evaluate this decision carefully, but can err on the side of adding the suffix.
It's expected that most users will simply `import Numerics`, so this isn't an issue for them.
+810
View File
@@ -0,0 +1,810 @@
//===--- BigInt.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
//
//===----------------------------------------------------------------------===//
public struct BigInt: SignedInteger {
public typealias Words = [UInt]
public private(set) var words: Words
@usableFromInline
internal init(_uncheckedWords: Words) {
self.words = _uncheckedWords
}
public init<T>(bitPattern source: T) where T: BinaryInteger {
words = Words(source.words)
BigInt._dropExcessWords(words: &words)
}
@usableFromInline
internal var _isNegative: Bool {
words[words.endIndex - 1] > Int.max
}
private static let _digits: [BigInt] = (0 ... 36).map {
BigInt(_uncheckedWords: [UInt(bitPattern: $0)])
}
private static let _digitRadix = BigInt(_uncheckedWords: [0, 1])
}
// MARK: - Basic Behaviors
extension BigInt: Equatable {
@inlinable
public static func == (lhs: BigInt, rhs: BigInt) -> Bool {
lhs.words == rhs.words
}
@inlinable
public static func != (lhs: BigInt, rhs: BigInt) -> Bool {
!(lhs == rhs)
}
}
extension BigInt: Hashable {
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(words)
}
}
extension BigInt: Comparable {
@inlinable
public static func < (lhs: BigInt, rhs: BigInt) -> Bool {
let lhsNegative = lhs._isNegative
let rhsNegative = rhs._isNegative
if lhsNegative && !rhsNegative { return true }
if rhsNegative && !lhsNegative { return false }
if (lhsNegative && rhsNegative) || (!lhsNegative && !rhsNegative) {
if lhs.words.count > rhs.words.count {
return lhsNegative ? true : false
}
if lhs.words.count < rhs.words.count {
return lhsNegative ? false : true
}
for i in stride(from: lhs.words.count - 1, through: 0, by: -1) {
if lhs.words[i] > rhs.words[i] {
return false
} else if lhs.words[i] < rhs.words[i] {
return true
}
}
}
return false
}
}
extension BigInt: LosslessStringConvertible {
public init?(_ description: String) {
self.init(description, radix: 10)
}
public init?<T>(_ description: T, radix: Int = 10) where T: StringProtocol {
precondition(2 ... 36 ~= radix, "Radix not in range 2 ... 36")
self = 0
let isNegative = description.hasPrefix("-")
let hasPrefix = isNegative || description.hasPrefix("+")
let utf8 = description.utf8.dropFirst(hasPrefix ? 1 : 0)
guard !utf8.isEmpty else { return nil }
for var byte in utf8 {
switch byte {
case UInt8(ascii: "0") ... UInt8(ascii: "9"):
byte -= UInt8(ascii: "0")
case UInt8(ascii: "A") ... UInt8(ascii: "Z"):
byte -= UInt8(ascii: "A")
byte += 10
case UInt8(ascii: "a") ... UInt8(ascii: "z"):
byte -= UInt8(ascii: "a")
byte += 10
default:
return nil
}
guard byte < radix else { return nil }
self *= BigInt._digits[radix]
self += BigInt._digits[Int(byte)]
}
if isNegative {
self.negate()
}
}
}
extension BigInt: Decodable {
public init(from decoder: Decoder) throws {
let singleValueContainer = try decoder.singleValueContainer()
let description = try singleValueContainer.decode(String.self)
guard let result = BigInt(description) else {
throw DecodingError.dataCorruptedError(
in: singleValueContainer,
debugDescription: "BigInt(\(description.debugDescription)) failed")
}
self = result
}
}
extension BigInt: Encodable {
public func encode(to encoder: Encoder) throws {
var singleValueContainer = encoder.singleValueContainer()
try singleValueContainer.encode(description)
}
}
// MARK: - Numeric Protocols
extension BigInt: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
if value >= 0, value < BigInt._digits.count {
self = BigInt._digits[value]
} else {
words = [UInt(bitPattern: value)]
}
}
}
extension BigInt: AdditiveArithmetic {
@inlinable
public static func + (lhs: BigInt, rhs: BigInt) -> BigInt {
var result = lhs
result += rhs
return result
}
public static func += (lhs: inout BigInt, rhs: BigInt) {
if lhs.words.count == 1, rhs.words.count == 1 {
let lhsWord = lhs.words[0]
let rhsWord = rhs.words[0]
let (result, isOverflow) = lhsWord.addingReportingOverflow(rhsWord)
if !isOverflow && result < Int.max {
lhs.words[0] = result
return
}
let knownNegativeResult = lhsWord > Int.max && rhsWord > Int.max
if lhsWord > Int.max || rhsWord > Int.max, !knownNegativeResult {
// positive + negative is always smaller, so overflow is a red herring
lhs.words[0] = result
return
}
}
var isOverflow = false
var rhsWords = rhs.words
lhs.words.append(lhs._isNegative ? UInt.max : 0)
rhsWords.append(rhs._isNegative ? UInt.max : 0)
BigInt._signExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
var temp: UInt = 0
for index in 0 ..< lhs.words.count {
var carryOverflow = false
if isOverflow {
(temp, carryOverflow) = rhsWords[index].addingReportingOverflow(1)
} else {
temp = rhsWords[index]
}
(lhs.words[index], isOverflow) = lhs.words[index].addingReportingOverflow(temp)
isOverflow = carryOverflow || isOverflow
}
BigInt._dropExcessWords(words: &lhs.words)
}
@inlinable
public static func - (lhs: BigInt, rhs: BigInt) -> BigInt {
var result = lhs
result -= rhs
return result
}
@inlinable
public static func -= (lhs: inout BigInt, rhs: BigInt) {
lhs += -rhs
}
}
extension BigInt: Numeric {
public init?<T>(exactly source: T) where T: BinaryInteger {
self.init(source)
}
public var magnitude: BigInt { _isNegative ? -self : self }
public static func * (lhs: BigInt, rhs: BigInt) -> BigInt {
let lhsIsNeg = lhs.words[lhs.words.endIndex - 1] > Int.max
let rhsIsNeg = rhs.words[rhs.words.endIndex - 1] > Int.max
let lhsWords = lhsIsNeg ? (-lhs).words : lhs.words
let rhsWords = rhsIsNeg ? (-rhs).words : rhs.words
let count = lhsWords.count + rhsWords.count + 1
var newWords = Words(repeating: 0, count: count)
for i in 0 ..< rhsWords.count {
var carry: UInt = 0
var digit: UInt = 0
var lastJ: Int = 0
for j in i ..< (lhsWords.count + i) {
var (high, low) = rhsWords[i].multipliedFullWidth(by: lhsWords[j - i])
var isOverflow: Bool
(digit, isOverflow) = low.addingReportingOverflow(newWords[j])
if isOverflow {
high += 1
}
(digit, isOverflow) = digit.addingReportingOverflow(carry)
if isOverflow {
high += 1
}
carry = high
newWords[j] = digit
lastJ = j
}
if carry != 0 {
let isOverflow: Bool
(digit, isOverflow) = newWords[lastJ + 1].addingReportingOverflow(carry)
if isOverflow {
carry = 1
}
newWords[lastJ + 1] = digit
}
}
for i in stride(from: count - 1, through: 1, by: -1) {
if newWords[i] == 0, newWords[i - 1] <= Int.max {
newWords.removeLast()
} else {
break
}
}
if lhsIsNeg || rhsIsNeg, !(lhsIsNeg && rhsIsNeg) {
return -BigInt(_uncheckedWords: newWords)
}
return BigInt(_uncheckedWords: newWords)
}
@inlinable
public static func *= (lhs: inout BigInt, rhs: BigInt) {
lhs = lhs * rhs
}
}
extension BigInt: SignedNumeric {
public mutating func negate() {
var isOverflow = true
for i in 0 ..< words.count {
if isOverflow {
(words[i], isOverflow) = (~words[i]).addingReportingOverflow(1)
} else {
words[i] = ~words[i]
}
}
BigInt._dropExcessWords(words: &words)
}
@inlinable
public static prefix func - (x: BigInt) -> BigInt {
var result = x
result.negate()
return result
}
}
extension BigInt: BinaryInteger {
public init?<T>(exactly source: T) where T: BinaryFloatingPoint {
guard source.isFinite, source == source.rounded(.towardZero) else {
return nil
}
self.init(source)
}
public init<T>(_ source: T) where T: BinaryFloatingPoint {
precondition(
source.isFinite,
"""
\(type(of: source)) value cannot be converted to BigInt because it is \
either infinite or NaN
""")
let isNegative = source < 0.0
var float = isNegative ? -source : source
if let _ = UInt(exactly: T.greatestFiniteMagnitude) {
words = [UInt(float)]
} else {
var words = Words()
let radix = T(sign: .plus, exponent: T.Exponent(UInt.bitWidth), significand: 1)
repeat {
let digit = UInt(float.truncatingRemainder(dividingBy: radix))
words.append(digit)
float = (float / radix).rounded(.towardZero)
} while float != 0
if let last = words.last, last >= Int.max {
words.append(0)
}
self.words = words
}
if isNegative {
self.negate()
}
}
public init<T>(_ source: T) where T: BinaryInteger {
if source >= 0, source < BigInt._digits.count {
self = BigInt._digits[Int(source)]
} else {
words = Words(source.words)
if source > 0 && source.words[source.words.endIndex - 1] > Int.max {
words.append(0)
}
// needed to handle sign-extended multi-word numbers that
// actually fit in a single word
BigInt._dropExcessWords(words: &words)
}
}
public init<T>(clamping source: T) where T: BinaryInteger {
self.init(source)
}
public init<T>(truncatingIfNeeded source: T) where T: BinaryInteger {
words = Words(source.words)
}
public var bitWidth: Int { words.count * UInt.bitWidth }
public var trailingZeroBitCount: Int {
var totalZeros = 0
for word in words {
if word == 0 {
totalZeros += UInt.bitWidth
} else {
totalZeros += word.trailingZeroBitCount
break
}
}
return totalZeros
}
@inlinable
public static func / (lhs: BigInt, rhs: BigInt) -> BigInt {
let (result, _) = _div(lhs: lhs, rhs: rhs)
return result
}
@inlinable
public static func /= (lhs: inout BigInt, rhs: BigInt) {
lhs = lhs / rhs
}
@inlinable
public static func % (lhs: BigInt, rhs: BigInt) -> BigInt {
let (_, result) = _div(lhs: lhs, rhs: rhs)
return result
}
@inlinable
public static func %= (lhs: inout BigInt, rhs: BigInt) {
lhs = lhs % rhs
}
@inlinable
public static prefix func ~ (x: BigInt) -> BigInt {
let newWords = x.words.map { ~$0 }
return BigInt(_uncheckedWords: Words(newWords))
}
public static func &= (lhs: inout BigInt, rhs: BigInt) {
var rhsWords = rhs.words
BigInt._signExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
for i in 0 ..< rhsWords.count {
lhs.words[i] &= rhsWords[i]
}
BigInt._dropExcessWords(words: &lhs.words)
}
public static func |= (lhs: inout BigInt, rhs: BigInt) {
var rhsWords = rhs.words
BigInt._signExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
for i in 0 ..< rhsWords.count {
lhs.words[i] |= rhsWords[i]
}
BigInt._dropExcessWords(words: &lhs.words)
}
public static func ^= (lhs: inout BigInt, rhs: BigInt) {
var rhsWords = rhs.words
BigInt._signExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
for i in 0 ..< rhsWords.count {
lhs.words[i] &= rhsWords[i]
}
BigInt._dropExcessWords(words: &lhs.words)
}
public static func <<= <RHS>(lhs: inout BigInt, rhs: RHS) where RHS: BinaryInteger {
if rhs.signum() < 0 {
lhs >>= rhs.magnitude
return
}
let wordLength = UInt.bitWidth
let isNegative = lhs._isNegative
let (fullWords, remainder) = rhs.quotientAndRemainder(dividingBy: RHS(wordLength))
lhs.words = Words(repeating: 0, count: Int(fullWords)) + lhs.words + [isNegative ? UInt.max : 0]
if remainder > 0 {
var value: UInt = 0
for i in 0 ..< lhs.words.count {
let temp = lhs.words[i] >> (wordLength - Int(remainder))
lhs.words[i] <<= Int(remainder)
if i > 0 {
lhs.words[i] &= UInt.max << Int(remainder)
lhs.words[i] |= value
}
value = temp
}
if isNegative {
lhs.words[lhs.words.count - 1] |= (UInt.max << Int(remainder))
}
}
BigInt._dropExcessWords(words: &lhs.words)
}
public static func >>= <RHS>(lhs: inout BigInt, rhs: RHS) where RHS: BinaryInteger {
if rhs.signum() < 0 {
lhs <<= rhs.magnitude
return
}
let wordLength = UInt.bitWidth
let isNegative = lhs._isNegative
let (fullWords, remainder) = rhs.quotientAndRemainder(dividingBy: RHS(wordLength))
if fullWords < lhs.words.count {
lhs.words.removeFirst(Int(fullWords))
} else {
lhs = isNegative ? -1 : 0
return
}
if remainder > 0 {
let mask = ~(UInt.max << remainder)
var value: UInt = 0
for i in stride(from: lhs.words.count - 1, through: 0, by: -1) {
let temp = lhs.words[i] & mask
lhs.words[i] >>= remainder
lhs.words[i] |= (value << (UInt.bitWidth - Int(remainder)))
value = temp
}
}
if isNegative {
lhs.words[lhs.words.count - 1] |= (UInt.max << (UInt.bitWidth - Int(remainder)))
}
BigInt._dropExcessWords(words: &lhs.words)
}
@inlinable
public func quotientAndRemainder(dividingBy rhs: BigInt) -> (quotient: BigInt, remainder: BigInt) {
return BigInt._div(lhs: self, rhs: rhs)
}
@inlinable
public func signum() -> BigInt { _isNegative ? -1 : (self == 0) ? 0 : 1 }
}
// MARK: -
extension BigInt {
/// See _The Art of Computer Programming_ volume 2 by Donald Knuth, Section 4.3.1: The Classical Algorithms
private static func _findQhat(
high: UInt,
low: UInt.Magnitude,
divisor: UInt,
nextVdigit: UInt,
nextUdigit: UInt
) -> UInt {
var qhat: Array<UInt>
var rhat: Array<UInt>
if high >= divisor {
let v = divisor
let u = [low, high]
var r: UInt = 0
qhat = Words(repeating: 0, count: 2)
for j in (0...1).reversed() {
let uj = u[j]
(qhat[j], r) = v.dividingFullWidth((r, uj))
}
BigInt._dropExcessWords(words: &qhat)
rhat = [r]
} else {
let (qhatWord, rhatWord) = divisor.dividingFullWidth((high, low))
qhat = [qhatWord]
rhat = [rhatWord]
}
repeat {
var qhatTooLarge = false
if qhat.count > 1 {
qhatTooLarge = true
} else {
// All of the following is computing and checking qhat*v_n-2 > rhat*b + u_j+n-2
// from TAoCP Volume 2 Section 4.3.1, Algorithm D, step D3
let (comp_lhs_hi, comp_lhs_lo) = qhat[0].multipliedFullWidth(by: nextVdigit)
if comp_lhs_hi > rhat[0] {
qhatTooLarge = true
} else if comp_lhs_hi == rhat[0] && comp_lhs_lo > nextUdigit {
qhatTooLarge = true
}
}
// high >= divisor is standing in for the test qhat >= b from Algorithm D step D3
if qhatTooLarge {
// begin qhat -= 1
if qhat.count == 1 {
qhat[0] -= 1
} else {
let (qlow, underflow) = qhat[0].subtractingReportingOverflow(1)
qhat[0] = qlow
if qhat[1] > 0 && underflow {
qhat[1] -= 1
if qhat[1] == 0 {
qhat.remove(at: 1)
}
}
}
// end qhat -= 1
// begin rhat += divisor
let (rhatResult, overflow) : (UInt, Bool)
if rhat.count == 1 || rhat[1] == 0 {
(rhatResult, overflow) = rhat[0].addingReportingOverflow(divisor)
rhat[0] = rhatResult
if overflow {
rhat.append(1)
}
} // we don't need an else because rhat is already larger than BigInt._digitRadix
// end rhat += divisor
} else {
break
}
} while rhat.count == 1 // equivalent to rhat < b
return qhat[0]
}
/// See _The Art of Computer Programming_ volume 2 by Donald Knuth, Section 4.3.1: The Classical Algorithms
@usableFromInline
internal static func _div(lhs: BigInt, rhs: BigInt) -> (quotient: BigInt, remainder: BigInt) {
precondition(rhs != _digits[0], "Division by zero error!")
if lhs.words.count == 1, rhs.words.count == 1 {
let (quot, rem) = Int(bitPattern: lhs.words[0]).quotientAndRemainder(dividingBy: Int(bitPattern: rhs.words[0]))
return (BigInt(_uncheckedWords: [UInt(bitPattern: quot)]), BigInt(_uncheckedWords: [UInt(bitPattern: rem)]))
}
let lhsIsNeg = lhs._isNegative
let rhsIsNeg = rhs._isNegative
var lhsWords = lhsIsNeg ? (-lhs).words : lhs.words
var rhsWords = rhsIsNeg ? (-rhs).words : rhs.words
// See the answer to exercise 16 in Section 4.3.1 of TAOCP
if rhsWords.count == 1 || (rhsWords.count == 2 && rhsWords[1] == 0) {
let v = rhsWords[0]
let u = lhsWords
var r: UInt = 0
var quot = Words(repeating: 0, count: u.count)
for j in (0...(u.count - 1)).reversed() {
let uj = u[j]
(quot[j], r) = v.dividingFullWidth((r, uj))
}
if quot[u.count - 1] > UInt(Int.max) {
quot.append(0)
}
BigInt._dropExcessWords(words: &quot)
return (quotient: BigInt(_uncheckedWords: quot), remainder: BigInt(r))
}
while rhsWords[rhsWords.endIndex - 1] == 0 {
rhsWords.removeLast()
}
if rhsWords.count > lhsWords.count { return (0, lhs) }
if lhsWords.count <= rhsWords.count {
for _ in 0 ... (rhsWords.count - lhsWords.count) {
lhsWords.append(0)
}
}
let m = lhsWords.count - rhsWords.count
let n = rhsWords.count
let bitWidth = UInt(UInt.bitWidth)
let s = UInt(rhsWords[n - 1].leadingZeroBitCount)
let rn = UnsafeMutablePointer<UInt>.allocate(capacity: n)
rn.initialize(repeating: 0, count: n)
defer { rn.deallocate() }
for i in (1 ... (n - 1)).reversed() {
rn[i] = (rhsWords[i] << s) | (rhsWords[i - 1] >> (bitWidth - s))
}
rn[0] = rhsWords[0] << s
let ln = UnsafeMutablePointer<UInt>.allocate(capacity: m + n + 1)
ln.initialize(repeating: 0, count: m + n + 1)
defer { ln.deallocate() }
ln[m + n] = lhsWords[m + n - 1] >> (bitWidth - s)
for i in (1 ... (m + n - 1)).reversed() {
ln[i] = (lhsWords[i] << s) | (lhsWords[i - 1] >> (bitWidth - s))
}
ln[0] = lhsWords[0] << s
let resultSize = m + 1
var quot = Words(repeating: 0, count: resultSize)
for j in (0 ... m).reversed() {
let qhat = _findQhat(
high: ln[j + n],
low: UInt.Magnitude(ln[j + n - 1]),
divisor: rn[n - 1],
nextVdigit: rn[n - 2],
nextUdigit: ln[j + n - 2])
var carry: UInt = 0
var isOverflow = false
var borrow: UInt = 0
var underflow = false
for i in 0 ..< n {
if borrow > 0 {
(ln[i + j], underflow) = ln[i + j].subtractingReportingOverflow(borrow)
borrow = underflow ? 1 : 0
}
var (pHigh, pLow) = qhat.multipliedFullWidth(by: rn[i])
(pLow, isOverflow) = pLow.addingReportingOverflow(carry)
if isOverflow {
pHigh += 1
}
(ln[i + j], underflow) = ln[i + j].subtractingReportingOverflow(pLow)
if underflow {
borrow += 1
}
carry = pHigh
}
(ln[j + n], underflow) = ln[j + n].subtractingReportingOverflow(carry + borrow)
if underflow {
let newQhat = qhat - 1
carry = 0
var total: UInt = 0
for i in 0 ..< n {
(total, isOverflow) = ln[i + j].addingReportingOverflow(carry)
carry = isOverflow ? 1 : 0
(ln[i + j], isOverflow) = total.addingReportingOverflow(rn[i])
if carry == 0 { carry = isOverflow ? 1 : 0 }
}
(ln[j + n], _) = ln[j + n].addingReportingOverflow(carry)
quot[j] = newQhat
} else {
quot[j] = qhat
}
}
var rem = Words(repeating: 0, count: n)
for i in 0 ..< (n - 1) {
rem[i] = (ln[i] >> s) | ln[i + 1] << (bitWidth - s)
}
rem[n - 1] = ln[n - 1] >> s
if rem[n - 1] > UInt(Int.max) {
rem.append(0)
}
BigInt._dropExcessWords(words: &quot)
BigInt._dropExcessWords(words: &rem)
return (BigInt(_uncheckedWords: quot), BigInt(_uncheckedWords: rem))
}
private static func _signExtend(lhsWords: inout Words, rhsWords: inout Words) {
let lhsIsNeg = (lhsWords.last ?? 0) >> (UInt.bitWidth - Int(1)) == 1
let rhsIsNeg = (rhsWords.last ?? 0) >> (UInt.bitWidth - Int(1)) == 1
if lhsWords.count > rhsWords.count {
for _ in 0 ..< (lhsWords.count - rhsWords.count) {
rhsIsNeg ? rhsWords.append(UInt.max) : rhsWords.append(0)
}
} else if rhsWords.count > lhsWords.count {
for _ in 0 ..< (rhsWords.count - lhsWords.count) {
lhsIsNeg ? lhsWords.append(UInt.max) : lhsWords.append(0)
}
}
}
@usableFromInline
internal static func _dropExcessWords(words: inout Words) {
while words.count > 1, words[words.endIndex - 1] == 0 {
if words[words.endIndex - 2] <= Int.max {
words.removeLast()
} else {
break
}
}
while words.count > 1, words[words.endIndex - 1] == UInt.max {
if words[words.endIndex - 2] > Int.max {
words.removeLast()
} else {
break
}
}
}
}
+751
View File
@@ -0,0 +1,751 @@
//===--- BigUInt.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
//
//===----------------------------------------------------------------------===//
public struct BigUInt: UnsignedInteger {
public typealias Words = [UInt]
public private(set) var words: Words
@usableFromInline
internal init(_uncheckedWords: Words) {
self.words = _uncheckedWords
}
public init<T>(bitPattern source: T) where T: BinaryInteger {
words = Words(source.words)
BigUInt._dropExcessWords(words: &words)
}
@usableFromInline
internal var _isNegative: Bool {
words[words.endIndex - 1] > Int.max
}
private static let _digits: [BigUInt] = (0 ... 36).map {
BigUInt(_uncheckedWords: [UInt(bitPattern: $0)])
}
private static let _digitRadix = BigInt(_uncheckedWords: [0, 1])
}
// MARK: - Basic Behaviors
extension BigUInt: Equatable {
@inlinable
public static func == (lhs: BigUInt, rhs: BigUInt) -> Bool {
lhs.words == rhs.words
}
@inlinable
public static func != (lhs: BigUInt, rhs: BigUInt) -> Bool {
!(lhs == rhs)
}
}
extension BigUInt: Hashable {
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(words)
}
}
extension BigUInt: Comparable {
@inlinable
public static func < (lhs: BigUInt, rhs: BigUInt) -> Bool {
let lhsNegative = lhs._isNegative
let rhsNegative = rhs._isNegative
if lhsNegative && !rhsNegative { return true }
if rhsNegative && !lhsNegative { return false }
if (lhsNegative && rhsNegative) || (!lhsNegative && !rhsNegative) {
if lhs.words.count > rhs.words.count {
return lhsNegative ? true : false
}
if lhs.words.count < rhs.words.count {
return lhsNegative ? false : true
}
for i in stride(from: lhs.words.count - 1, through: 0, by: -1) {
if lhs.words[i] > rhs.words[i] {
return false
} else if lhs.words[i] < rhs.words[i] {
return true
}
}
}
return false
}
}
extension BigUInt: LosslessStringConvertible {
public init?(_ description: String) {
self.init(description, radix: 10)
}
public init?<T>(_ description: T, radix: Int = 10) where T: StringProtocol {
precondition(2 ... 36 ~= radix, "Radix not in range 2 ... 36")
self = 0
let hasPrefix = description.hasPrefix("+")
let utf8 = description.utf8.dropFirst(hasPrefix ? 1 : 0)
guard !utf8.isEmpty else { return nil }
for var byte in utf8 {
switch byte {
case UInt8(ascii: "0") ... UInt8(ascii: "9"):
byte -= UInt8(ascii: "0")
case UInt8(ascii: "A") ... UInt8(ascii: "Z"):
byte -= UInt8(ascii: "A")
byte += 10
case UInt8(ascii: "a") ... UInt8(ascii: "z"):
byte -= UInt8(ascii: "a")
byte += 10
default:
return nil
}
guard byte < radix else { return nil }
self *= BigUInt._digits[radix]
self += BigUInt._digits[Int(byte)]
}
}
}
extension BigUInt: Decodable {
public init(from decoder: Decoder) throws {
let singleValueContainer = try decoder.singleValueContainer()
let description = try singleValueContainer.decode(String.self)
guard let result = BigUInt(description) else {
throw DecodingError.dataCorruptedError(
in: singleValueContainer,
debugDescription: "BigUInt(\(description.debugDescription)) failed")
}
self = result
}
}
extension BigUInt: Encodable {
public func encode(to encoder: Encoder) throws {
var singleValueContainer = encoder.singleValueContainer()
try singleValueContainer.encode(description)
}
}
// MARK: - Numeric Protocols
extension BigUInt: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
if value < BigUInt._digits.count {
self = BigUInt._digits[value]
} else {
words = [UInt(bitPattern: value)]
}
}
}
extension BigUInt: AdditiveArithmetic {
@inlinable
public static func + (lhs: BigUInt, rhs: BigUInt) -> BigUInt {
var result = lhs
result += rhs
return result
}
public static func += (lhs: inout BigUInt, rhs: BigUInt) {
if lhs.words.count == 1, rhs.words.count == 1 {
let lhsWord = lhs.words[0]
let rhsWord = rhs.words[0]
let (result, isOverflow) = lhsWord.addingReportingOverflow(rhsWord)
if !isOverflow && result < Int.max {
lhs.words[0] = result
return
}
let knownNegativeResult = lhsWord > Int.max && rhsWord > Int.max
if lhsWord > Int.max || rhsWord > Int.max, !knownNegativeResult {
// positive + negative is always smaller, so overflow is a red herring
lhs.words[0] = result
return
}
}
var isOverflow = false
var rhsWords = rhs.words
lhs.words.append(0)
rhsWords.append(0)
BigUInt._zeroExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
var temp: UInt = 0
for index in 0 ..< lhs.words.count {
var carryOverflow = false
if isOverflow {
(temp, carryOverflow) = rhsWords[index].addingReportingOverflow(1)
} else {
temp = rhsWords[index]
}
(lhs.words[index], isOverflow) = lhs.words[index].addingReportingOverflow(temp)
isOverflow = carryOverflow || isOverflow
}
BigUInt._dropExcessWords(words: &lhs.words)
}
@inlinable
public static func - (lhs: BigUInt, rhs: BigUInt) -> BigUInt {
var result = lhs
result -= rhs
return result
}
@inlinable
public static func -= (lhs: inout BigUInt, rhs: BigUInt) {
lhs = .init(_uncheckedWords: (BigInt(_uncheckedWords: lhs.words) + -BigInt(_uncheckedWords: rhs.words)).words)
}
}
extension BigUInt: Numeric {
public init?<T>(exactly source: T) where T: BinaryInteger {
self.init(source)
}
public var magnitude: BigUInt { self }
public static func * (lhs: BigUInt, rhs: BigUInt) -> BigUInt {
let lhsWords = lhs.words
let rhsWords = rhs.words
let count = lhsWords.count + rhsWords.count + 1
var newWords = Words(repeating: 0, count: count)
for i in 0 ..< rhsWords.count {
var carry: UInt = 0
var digit: UInt = 0
var lastJ: Int = 0
for j in i ..< (lhsWords.count + i) {
var (high, low) = rhsWords[i].multipliedFullWidth(by: lhsWords[j - i])
var isOverflow: Bool
(digit, isOverflow) = low.addingReportingOverflow(newWords[j])
if isOverflow {
high += 1
}
(digit, isOverflow) = digit.addingReportingOverflow(carry)
if isOverflow {
high += 1
}
carry = high
newWords[j] = digit
lastJ = j
}
if carry != 0 {
let isOverflow: Bool
(digit, isOverflow) = newWords[lastJ + 1].addingReportingOverflow(carry)
if isOverflow {
carry = 1
}
newWords[lastJ + 1] = digit
}
}
for i in stride(from: count - 1, through: 1, by: -1) {
if newWords[i] == 0, newWords[i - 1] <= Int.max {
newWords.removeLast()
} else {
break
}
}
return BigUInt(_uncheckedWords: newWords)
}
@inlinable
public static func *= (lhs: inout BigUInt, rhs: BigUInt) {
lhs = lhs * rhs
}
}
extension BigUInt: BinaryInteger {
public init?<T>(exactly source: T) where T: BinaryFloatingPoint {
guard source.isFinite, source == source.rounded(.towardZero) else {
return nil
}
self.init(source)
}
public init<T>(_ source: T) where T: BinaryFloatingPoint {
precondition(
source.isFinite && source >= 0.0,
"""
\(type(of: source)) value cannot be converted to BigUInt because it is \
either infinite, NaN, or negative
""")
var float = source
if let _ = UInt(exactly: T.greatestFiniteMagnitude) {
words = [UInt(float)]
} else {
var words = Words()
let radix = T(sign: .plus, exponent: T.Exponent(UInt.bitWidth), significand: 1)
repeat {
let digit = UInt(float.truncatingRemainder(dividingBy: radix))
words.append(digit)
float = (float / radix).rounded(.towardZero)
} while float != 0
if let last = words.last, last >= Int.max {
words.append(0)
}
self.words = words
}
}
public init<T>(_ source: T) where T: BinaryInteger {
if source >= 0, source < BigUInt._digits.count {
self = BigUInt._digits[Int(source)]
} else {
words = Words(source.words)
if source > 0 && source.words[source.words.endIndex - 1] > Int.max {
words.append(0)
}
// needed to handle sign-extended multi-word numbers that
// actually fit in a single word
BigUInt._dropExcessWords(words: &words)
}
}
public init<T>(clamping source: T) where T: BinaryInteger {
self.init(source)
}
public init<T>(truncatingIfNeeded source: T) where T: BinaryInteger {
words = Words(source.words)
}
public var bitWidth: Int { words.count * UInt.bitWidth }
public var trailingZeroBitCount: Int {
var totalZeros = 0
for word in words {
if word == 0 {
totalZeros += UInt.bitWidth
} else {
totalZeros += word.trailingZeroBitCount
break
}
}
return totalZeros
}
@inlinable
public static func / (lhs: BigUInt, rhs: BigUInt) -> BigUInt {
let (result, _) = _div(lhs: lhs, rhs: rhs)
return result
}
@inlinable
public static func /= (lhs: inout BigUInt, rhs: BigUInt) {
lhs = lhs / rhs
}
@inlinable
public static func % (lhs: BigUInt, rhs: BigUInt) -> BigUInt {
let (_, result) = _div(lhs: lhs, rhs: rhs)
return result
}
@inlinable
public static func %= (lhs: inout BigUInt, rhs: BigUInt) {
lhs = lhs % rhs
}
@inlinable
public static prefix func ~ (x: BigUInt) -> BigUInt {
let newWords = x.words.map { ~$0 }
return BigUInt(_uncheckedWords: Words(newWords))
}
public static func &= (lhs: inout BigUInt, rhs: BigUInt) {
var rhsWords = rhs.words
BigUInt._zeroExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
for i in 0 ..< rhsWords.count {
lhs.words[i] &= rhsWords[i]
}
BigUInt._dropExcessWords(words: &lhs.words)
}
public static func |= (lhs: inout BigUInt, rhs: BigUInt) {
var rhsWords = rhs.words
BigUInt._zeroExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
for i in 0 ..< rhsWords.count {
lhs.words[i] |= rhsWords[i]
}
BigUInt._dropExcessWords(words: &lhs.words)
}
public static func ^= (lhs: inout BigUInt, rhs: BigUInt) {
var rhsWords = rhs.words
BigUInt._zeroExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
for i in 0 ..< rhsWords.count {
lhs.words[i] &= rhsWords[i]
}
BigUInt._dropExcessWords(words: &lhs.words)
}
public static func <<= <RHS>(lhs: inout BigUInt, rhs: RHS) where RHS: BinaryInteger {
if rhs.signum() < 0 {
lhs >>= rhs.magnitude
return
}
let wordLength = UInt.bitWidth
let (fullWords, remainder) = rhs.quotientAndRemainder(dividingBy: RHS(wordLength))
lhs.words = Words(repeating: 0, count: Int(fullWords)) + lhs.words + [0]
if remainder > 0 {
var value: UInt = 0
for i in 0 ..< lhs.words.count {
let temp = lhs.words[i] >> (wordLength - Int(remainder))
lhs.words[i] <<= Int(remainder)
if i > 0 {
lhs.words[i] &= UInt.max << Int(remainder)
lhs.words[i] |= value
}
value = temp
}
}
BigUInt._dropExcessWords(words: &lhs.words)
}
public static func >>= <RHS>(lhs: inout BigUInt, rhs: RHS) where RHS: BinaryInteger {
if rhs.signum() < 0 {
lhs <<= rhs.magnitude
return
}
let wordLength = UInt.bitWidth
let (fullWords, remainder) = rhs.quotientAndRemainder(dividingBy: RHS(wordLength))
if fullWords < lhs.words.count {
lhs.words.removeFirst(Int(fullWords))
} else {
lhs = 0
return
}
if remainder > 0 {
let mask = ~(UInt.max << remainder)
var value: UInt = 0
for i in stride(from: lhs.words.count - 1, through: 0, by: -1) {
let temp = lhs.words[i] & mask
lhs.words[i] >>= remainder
lhs.words[i] |= (value << (UInt.bitWidth - Int(remainder)))
value = temp
}
}
BigUInt._dropExcessWords(words: &lhs.words)
}
@inlinable
public func quotientAndRemainder(dividingBy rhs: BigUInt) -> (quotient: BigUInt, remainder: BigUInt) {
return BigUInt._div(lhs: self, rhs: rhs)
}
}
// MARK: -
extension BigUInt {
/// See _The Art of Computer Programming_ volume 2 by Donald Knuth, Section 4.3.1: The Classical Algorithms
private static func _findQhat(
high: UInt,
low: UInt.Magnitude,
divisor: UInt,
nextVdigit: UInt,
nextUdigit: UInt
) -> UInt {
var qhat: Array<UInt>
var rhat: Array<UInt>
if high >= divisor {
let v = divisor
let u = [low, high]
var r: UInt = 0
qhat = Words(repeating: 0, count: 2)
for j in (0...1).reversed() {
let uj = u[j]
(qhat[j], r) = v.dividingFullWidth((r, uj))
}
BigUInt._dropExcessWords(words: &qhat)
rhat = [r]
} else {
let (qhatWord, rhatWord) = divisor.dividingFullWidth((high, low))
qhat = [qhatWord]
rhat = [rhatWord]
}
repeat {
var qhatTooLarge = false
if qhat.count > 1 {
qhatTooLarge = true
} else {
// All of the following is computing and checking qhat*v_n-2 > rhat*b + u_j+n-2
// from TAoCP Volume 2 Section 4.3.1, Algorithm D, step D3
let (comp_lhs_hi, comp_lhs_lo) = qhat[0].multipliedFullWidth(by: nextVdigit)
if comp_lhs_hi > rhat[0] {
qhatTooLarge = true
} else if comp_lhs_hi == rhat[0] && comp_lhs_lo > nextUdigit {
qhatTooLarge = true
}
}
// high >= divisor is standing in for the test qhat >= b from Algorithm D step D3
if qhatTooLarge {
// begin qhat -= 1
if qhat.count == 1 {
qhat[0] -= 1
} else {
let (qlow, underflow) = qhat[0].subtractingReportingOverflow(1)
qhat[0] = qlow
if qhat[1] > 0 && underflow {
qhat[1] -= 1
if qhat[1] == 0 {
qhat.remove(at: 1)
}
}
}
// end qhat -= 1
// begin rhat += divisor
let (rhatResult, overflow) : (UInt, Bool)
if rhat.count == 1 || rhat[1] == 0 {
(rhatResult, overflow) = rhat[0].addingReportingOverflow(divisor)
rhat[0] = rhatResult
if overflow {
rhat.append(1)
}
} // we don't need an else because rhat is already larger than BigInt._digitRadix
// end rhat += divisor
} else {
break
}
} while rhat.count == 1 // equivalent to rhat < b
return qhat[0]
}
/// See _The Art of Computer Programming_ volume 2 by Donald Knuth, Section 4.3.1: The Classical Algorithms
@usableFromInline
internal static func _div(lhs: BigUInt, rhs: BigUInt) -> (quotient: BigUInt, remainder: BigUInt) {
precondition(rhs != _digits[0], "Division by zero error!")
if lhs.words.count == 1, rhs.words.count == 1 {
let (quot, rem) = Int(bitPattern: lhs.words[0]).quotientAndRemainder(dividingBy: Int(bitPattern: rhs.words[0]))
return (BigUInt(_uncheckedWords: [UInt(bitPattern: quot)]), BigUInt(_uncheckedWords: [UInt(bitPattern: rem)]))
}
var lhsWords = lhs.words
var rhsWords = rhs.words
// See the answer to exercise 16 in Section 4.3.1 of TAOCP
if rhsWords.count == 1 || (rhsWords.count == 2 && rhsWords[1] == 0) {
let v = rhsWords[0]
let u = lhsWords
var r: UInt = 0
var quot = Words(repeating: 0, count: u.count)
for j in (0...(u.count - 1)).reversed() {
let uj = u[j]
(quot[j], r) = v.dividingFullWidth((r, uj))
}
if quot[u.count - 1] > UInt(Int.max) {
quot.append(0)
}
BigUInt._dropExcessWords(words: &quot)
return (quotient: BigUInt(_uncheckedWords: quot), remainder: BigUInt(r))
}
while rhsWords[rhsWords.endIndex - 1] == 0 {
rhsWords.removeLast()
}
if rhsWords.count > lhsWords.count { return (0, lhs) }
if lhsWords.count <= rhsWords.count {
for _ in 0 ... (rhsWords.count - lhsWords.count) {
lhsWords.append(0)
}
}
let m = lhsWords.count - rhsWords.count
let n = rhsWords.count
let bitWidth = UInt(UInt.bitWidth)
let s = UInt(rhsWords[n - 1].leadingZeroBitCount)
let rn = UnsafeMutablePointer<UInt>.allocate(capacity: n)
rn.initialize(repeating: 0, count: n)
defer { rn.deallocate() }
for i in (1 ... (n - 1)).reversed() {
rn[i] = (rhsWords[i] << s) | (rhsWords[i - 1] >> (bitWidth - s))
}
rn[0] = rhsWords[0] << s
let ln = UnsafeMutablePointer<UInt>.allocate(capacity: m + n + 1)
ln.initialize(repeating: 0, count: m + n + 1)
defer { ln.deallocate() }
ln[m + n] = lhsWords[m + n - 1] >> (bitWidth - s)
for i in (1 ... (m + n - 1)).reversed() {
ln[i] = (lhsWords[i] << s) | (lhsWords[i - 1] >> (bitWidth - s))
}
ln[0] = lhsWords[0] << s
let resultSize = m + 1
var quot = Words(repeating: 0, count: resultSize)
for j in (0 ... m).reversed() {
let qhat = _findQhat(
high: ln[j + n],
low: UInt.Magnitude(ln[j + n - 1]),
divisor: rn[n - 1],
nextVdigit: rn[n - 2],
nextUdigit: ln[j + n - 2])
var carry: UInt = 0
var isOverflow = false
var borrow: UInt = 0
var underflow = false
for i in 0 ..< n {
if borrow > 0 {
(ln[i + j], underflow) = ln[i + j].subtractingReportingOverflow(borrow)
borrow = underflow ? 1 : 0
}
var (pHigh, pLow) = qhat.multipliedFullWidth(by: rn[i])
(pLow, isOverflow) = pLow.addingReportingOverflow(carry)
if isOverflow {
pHigh += 1
}
(ln[i + j], underflow) = ln[i + j].subtractingReportingOverflow(pLow)
if underflow {
borrow += 1
}
carry = pHigh
}
(ln[j + n], underflow) = ln[j + n].subtractingReportingOverflow(carry + borrow)
if underflow {
let newQhat = qhat - 1
carry = 0
var total: UInt = 0
for i in 0 ..< n {
(total, isOverflow) = ln[i + j].addingReportingOverflow(carry)
carry = isOverflow ? 1 : 0
(ln[i + j], isOverflow) = total.addingReportingOverflow(rn[i])
if carry == 0 { carry = isOverflow ? 1 : 0 }
}
(ln[j + n], _) = ln[j + n].addingReportingOverflow(carry)
quot[j] = newQhat
} else {
quot[j] = qhat
}
}
var rem = Words(repeating: 0, count: n)
for i in 0 ..< (n - 1) {
rem[i] = (ln[i] >> s) | ln[i + 1] << (bitWidth - s)
}
rem[n - 1] = ln[n - 1] >> s
if rem[n - 1] > UInt(Int.max) {
rem.append(0)
}
BigUInt._dropExcessWords(words: &quot)
BigUInt._dropExcessWords(words: &rem)
return (BigUInt(_uncheckedWords: quot), BigUInt(_uncheckedWords: rem))
}
private static func _zeroExtend(lhsWords: inout Words, rhsWords: inout Words) {
if lhsWords.count > rhsWords.count {
for _ in 0 ..< (lhsWords.count - rhsWords.count) {
rhsWords.append(0)
}
} else if rhsWords.count > lhsWords.count {
for _ in 0 ..< (rhsWords.count - lhsWords.count) {
lhsWords.append(0)
}
}
}
@usableFromInline
internal static func _dropExcessWords(words: inout Words) {
while words.count > 1, words[words.endIndex - 1] == 0 {
if words[words.endIndex - 2] <= Int.max {
words.removeLast()
} else {
break
}
}
while words.count > 1, words[words.endIndex - 1] == UInt.max {
if words[words.endIndex - 2] > Int.max {
words.removeLast()
} else {
break
}
}
}
}
+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_library(BigIntModule
BigInt.swift)
set_target_properties(BigIntModule PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
_install_target(BigIntModule)
set_property(GLOBAL APPEND PROPERTY SWIFT_NUMERICS_EXPORTS BigIntModule)
+3
View File
@@ -0,0 +1,3 @@
# Arbitrary-precision integers
This module provides a `BigInt` type.
+17
View File
@@ -0,0 +1,17 @@
#[[
This source file is part of the Swift Numerics open source project
Copyright (c) 2019-2021 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(IntegerUtilities)
add_subdirectory(Numerics)
add_subdirectory(RealModule)
if(BUILD_TESTING)
add_subdirectory(_TestSupport)
endif()
-497
View File
@@ -1,497 +0,0 @@
//===--- Complex.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 Real
/// A complex number represented by real and imaginary parts.
///
/// TODO: introductory text on complex numbers
///
/// Implementation notes:
/// -
/// This type does not provide heterogeneous real/complex arithmetic,
/// not even the natural vector-space operations like real * complex.
/// There are two reasons for this choice: first, Swift broadly avoids
/// mixed-type arithmetic when the operation can be adequately expressed
/// by a conversion and homogeneous arithmetic. Second, with the current
/// typechecker rules, it would lead to undesirable ambiguity in common
/// expressions (see README.md for more details).
///
/// Unlike C's `_Complex` and C++'s `std::complex<>` types, we do not
/// attempt to make meaningful semantic distinctions between different
/// representations of infinity or NaN. Any Complex value with at least
/// one non-finite component is simply "non-finite". In as much as
/// possible, we use the semantics of the point at infinity on the
/// Riemann sphere for such values. This approach simplifies the number of
/// edge cases that need to be considered for multiplication, division, and
/// the elementary functions considerably.
///
/// `.magnitude` does not return the Euclidean norm; it uses the "infinity
/// norm" (`max(|real|,|imaginary|)`) instead. There are two reasons for this
/// choice: first, it's simply faster to compute on most hardware. Second,
/// there exist values for which the Euclidean norm cannot be represented
/// (consider a number with `.real` and `.imaginary` both equal to
/// `RealType.greatestFiniteMagnitude`; the Euclidean norm would be
/// `.sqrt(2) * .greatestFiniteMagnitude`, which overflows). Using
/// the infinity norm avoids this problem entirely without significant
/// downsides. You can access the Euclidean norm using the `length`
/// property.
@frozen
public struct Complex<RealType> where RealType: Real {
// A note on the `x` and `y` properties
//
// `x` and `y` are the names we use for the raw storage of the real and
// imaginary components of our complex number. We also provide public
// `.real` and `.imaginary` properties, which wrap this storage and
// fixup the semantics for non-finite values.
/// The real component of the value.
@usableFromInline @inline(__always)
internal var x: RealType
/// The imaginary part of the value.
@usableFromInline @inline(__always)
internal var y: RealType
/// A complex number constructed by specifying the real and imaginary parts.
@_transparent
public init(_ real: RealType, _ imaginary: RealType) {
x = real
y = imaginary
}
}
// MARK: - Basic properties
extension Complex {
/// The real part of this complex value.
///
/// If `z` is not finite, `z.real` is `.nan`.
public var real: RealType {
@_transparent
get { isFinite ? x : .nan }
@_transparent
set { x = newValue }
}
/// The imaginary part of this complex value.
///
/// If `z` is not finite, `z.imaginary` is `.nan`.
public var imaginary: RealType {
@_transparent
get { isFinite ? y : .nan }
@_transparent
set { y = newValue }
}
/// The additive identity, with real and imaginary parts both zero.
///
/// See also:
/// -
/// - .one
/// - .i
/// - .infinity
@_transparent
public static var zero: Complex {
Complex(0, 0)
}
/// The multiplicative identity, with real part one and imaginary part zero.
///
/// See also:
/// -
/// - .zero
/// - .i
/// - .infinity
@_transparent
public static var one: Complex {
Complex(1, 0)
}
/// The imaginary unit.
///
/// See also:
/// -
/// - .zero
/// - .one
/// - .infinity
@_transparent
public static var i: Complex {
Complex(0, 1)
}
/// The point at infinity.
///
/// See also:
/// -
/// - .zero
/// - .one
/// - .i
@_transparent
public static var infinity: Complex {
Complex(.infinity, 0)
}
/// The complex conjugate of this value.
@_transparent
public var conjugate: Complex {
Complex(x, -y)
}
/// True if this value is finite.
///
/// A complex value is finite if neither component is an infinity or nan.
///
/// See also:
/// -
/// - `.isNormal`
/// - `.isSubnormal`
/// - `.isZero`
@_transparent
public var isFinite: Bool {
x.isFinite && y.isFinite
}
/// True if this value is normal.
///
/// A complex number is normal if it is finite and *either* the real or imaginary component is normal.
/// A floating-point number representing one of the components is normal if its exponent allows a full-
/// precision representation.
///
/// See also:
/// -
/// - `.isFinite`
/// - `.isSubnormal`
/// - `.isZero`
@_transparent
public var isNormal: Bool {
isFinite && (x.isNormal || y.isNormal)
}
/// True if this value is subnormal.
///
/// A complex number is subnormal if it is finite, not normal, and not zero. When the result of a
/// computation is subnormal, underflow has occurred and the result generally does not have full
/// precision.
/// See also:
/// -
/// - `.isFinite`
/// - `.isNormal`
/// - `.isZero`
@_transparent
public var isSubnormal: Bool {
isFinite && !isNormal && !isZero
}
/// True if this value is zero.
///
/// A complex number is zero if *both* the real and imaginary components are zero.
///
/// See also:
/// -
/// - `.isFinite`
/// - `.isNormal`
/// - `.isSubnormal`
@_transparent
public var isZero: Bool {
x == 0 && y == 0
}
/// 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 `unsafeLengthSquared`
/// properties instead.
///
/// Edge cases:
/// -
/// - If `z` is not finite, `z.magnitude` is `.infinity`.
/// - If `z` is zero, `z.magnitude` is `0`.
/// - Otherwise, `z.magnitude` is finite and non-zero.
///
/// See also:
/// -
/// - `.length`
/// - `.unsafeLengthSquared`
@_transparent
public var magnitude: RealType {
guard isFinite else { return .infinity }
return max(abs(x), abs(y))
}
/// A "canonical" representation of the value.
///
/// For normal complex numbers with a RealType conforming to
/// BinaryFloatingPoint (the common case), the result is simply this value
/// unmodified. For zeros, the result has the representation (+0, +0). For
/// infinite values, the result has the representation (+inf, +0).
///
/// If the RealType admits non-canonical representations, the x and y
/// components are canonicalized in the result.
///
/// This is mainly useful for interoperation with other languages, where
/// you may want to reduce each equivalence class to a single representative
/// before passing across language boundaries, but it may also be useful
/// for some serialization tasks. It's also a useful implementation detail for
/// some primitive operations.
@_transparent
public var canonicalized: Self {
if isZero { return .zero }
if isFinite { return self.multiplied(by: 1) }
return .infinity
}
}
// MARK: - Additional Initializers
extension Complex {
/// The complex number with specified real part and zero imaginary part.
///
/// Equivalent to `Complex(real, 0)`.
@inlinable
public init(_ real: RealType) {
self.init(real, 0)
}
/// The complex number with specified imaginary part and zero real part.
///
/// Equivalent to `Complex(0, imaginary)`.
@inlinable
public init(imaginary: RealType) {
self.init(0, imaginary)
}
/// The complex number with specified real part and zero imaginary part.
///
/// Equivalent to `Complex(RealType(real), 0)`.
@inlinable
public init<Other: BinaryInteger>(_ real: Other) {
self.init(RealType(real), 0)
}
/// The complex number with specified real part and zero imaginary part,
/// if it can be constructed without rounding.
@inlinable
public init?<Other: BinaryInteger>(exactly real: Other) {
guard let real = RealType(exactly: real) else { return nil }
self.init(real, 0)
}
public typealias IntegerLiteralType = Int
@inlinable
public init(integerLiteral value: Int) {
self.init(RealType(value))
}
}
extension Complex where RealType: BinaryFloatingPoint {
/// `other` rounded to the nearest representable value of this type.
@inlinable
public init<Other: BinaryFloatingPoint>(_ other: Complex<Other>) {
self.init(RealType(other.x), RealType(other.y))
}
/// `other`, if it can be represented exactly in this type; otherwise `nil`.
@inlinable
public init?<Other: BinaryFloatingPoint>(exactly other: Complex<Other>) {
guard let x = RealType(exactly: other.x),
let y = RealType(exactly: other.y) else { return nil }
self.init(x, y)
}
}
// MARK: - Conformance to Hashable and Equatable
//
// The Complex type identifies all non-finite points (waving hands slightly,
// we identify all NaNs and infinites as the point at infinity on the Riemann
// sphere).
extension Complex: Hashable {
@_transparent
public static func ==(a: Complex, b: Complex) -> Bool {
// Identify all numbers with either component non-finite as a single
// "point at infinity".
guard a.isFinite || b.isFinite else { return true }
// For finite numbers, equality is defined componentwise. Cases where
// only one of a or b is infinite fall through to here as well, but this
// expression correctly returns false for them so we don't need to handle
// them explicitly.
return a.x == b.x && a.y == b.y
}
@_transparent
public func hash(into hasher: inout Hasher) {
// There are two equivalence classes to which we owe special attention:
// All zeros should hash to the same value, regardless of sign, and all
// non-finite numbers should hash to the same value, regardless of
// representation. The correct behavior for zero falls out for free from
// the hash behavior of floating-point, but we need to use a
// representative member for any non-finite values.
if isFinite {
hasher.combine(x)
hasher.combine(y)
} else {
hasher.combine(RealType.infinity)
}
}
}
// 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 { }
// MARK: - Formatting
extension Complex: CustomStringConvertible {
public var description: String {
guard isFinite else {
return "inf"
}
return "(\(x), \(y))"
}
}
extension Complex: CustomDebugStringConvertible {
public var debugDescription: String {
"Complex<\(RealType.self)>(\(String(reflecting: x)), \(String(reflecting: y)))"
}
}
// MARK: - Operations for working with polar form
extension Complex {
/// 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:
///
/// let x: Float = 3.0e+20
/// let x: Float = 4.0e+20
/// let naive = sqrt(x*x + y*y) // +Inf
/// let careful = Complex(x, y).length // 5.0e+20
///
/// Note that it *is* still possible for this property to overflow,
/// because the length can be as much as sqrt(2) times larger than
/// either component, and thus may not be representable in the real type.
///
/// For most use cases, you can use the cheaper `.magnitude`
/// property (which computes the ∞-norm) instead, which always produces
/// a representable result.
///
/// Edge cases:
/// -
/// If a complex value is not finite, its `.length` is `infinity`.
///
/// See also:
/// -
/// - `.magnitude`
/// - `.unsafeLengthSquared`
/// - `.phase`
/// - `.polar`
/// - `init(r:θ:)`
@_transparent
public var length: RealType {
let naive = unsafeLengthSquared
guard naive.isNormal else { return carefulLength }
return .sqrt(naive)
}
// Internal implementation detail of `length`, moving slow path off
// of the inline function. Note that even `carefulLength` can overflow
// for finite inputs, but only when the result is outside the range
// of representable values.
@usableFromInline
internal var carefulLength: RealType {
guard isFinite else { return .infinity }
return .hypot(x, y)
}
/// The squared length `(real*real + imaginary*imaginary)`.
///
/// This property is more efficient to compute than `length`, but is
/// highly prone to overflow or underflow; for finite values that are
/// not well-scaled, `unsafeLengthSquared` is often either zero or
/// infinity, even when `length` is a finite number. Use this property
/// only when you are certain that this value is well-scaled.
///
/// For many cases, `.magnitude` can be used instead, which is similarly
/// cheap to compute and always returns a representable value.
///
/// See also:
/// -
/// - `.length`
/// - `.magnitude`
@_transparent
public var unsafeLengthSquared: RealType {
x*x + y*y
}
/// The phase (angle, or "argument").
///
/// Returns the angle (measured above the real axis) in radians. If
/// the complex value is zero or infinity, the phase is not defined,
/// and `nan` is returned.
///
/// Edge cases:
/// -
/// If the complex value is zero or non-finite, phase is `nan`.
///
/// See also:
/// -
/// - `.length`
/// - `.polar`
/// - `init(r:θ:)`
@inlinable
public var phase: RealType {
guard isFinite && !isZero else { return .nan }
return .atan2(y: y, x: x)
}
/// The length and phase (or polar coordinates) of this value.
///
/// Edge cases:
/// -
/// If the complex value is zero or non-finite, phase is `.nan`.
/// If the complex value is non-finite, length is `.infinity`.
///
/// See also:
/// -
/// - `.length`
/// - `.phase`
/// - `init(r:θ:)`
public var polar: (length: RealType, phase: RealType) {
(length, phase)
}
/// Constructs a complex value from polar coordinates.
///
/// Edge cases:
/// -
/// If the phase is non-finite, but length is finite, this initializer
/// fails and returns nil. In all other cases, a non-nil value is constructed.
///
/// See also:
/// -
/// - `.length`
/// - `.phase`
/// - `.polar`
public init?(length: RealType, phase: RealType) {
guard phase.isFinite else {
// There's no way to make sense of finite magnitude and non-finite phase.
if length.isFinite { return nil }
// r is infinite so phase doesn't matter.
self = .infinity
return
}
self.init(length * .cos(phase), length * .sin(phase))
}
}
+29
View File
@@ -0,0 +1,29 @@
#[[
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
Complex.swift
Complex+AdditiveArithmetic.swift
Complex+AlgebraicField.swift
Complex+Codable.swift
Complex+ElementaryFunctions.swift
Complex+Hashable.swift
Complex+IntegerLiteral.swift
Complex+Numeric.swift
Complex+StringConvertible.swift
Polar.swift
Scale.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)
@@ -0,0 +1,42 @@
//===--- Complex+AdditiveArithmetic.swift ---------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2021 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import RealModule
extension Complex: AdditiveArithmetic {
/// The additive identity, with real and imaginary parts both zero.
///
/// See also: `one`, `i`, `infinity`
@_transparent
public static var zero: Complex {
Complex(0, 0)
}
@_transparent
public static func +(z: Complex, w: Complex) -> Complex {
return Complex(z.x + w.x, z.y + w.y)
}
@_transparent
public static func -(z: Complex, w: Complex) -> Complex {
return Complex(z.x - w.x, z.y - w.y)
}
@_transparent
public static func +=(z: inout Complex, w: Complex) {
z = z + w
}
@_transparent
public static func -=(z: inout Complex, w: Complex) {
z = z - w
}
}
@@ -1,71 +1,29 @@
//===--- Arithmetic.swift -------------------------------------*- swift -*-===//
//===--- Complex+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
// Copyright (c) 2019-2021 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
//
//===----------------------------------------------------------------------===//
// MARK: - Additive structure
extension Complex: AdditiveArithmetic {
@_transparent
public static func +(z: Complex, w: Complex) -> Complex {
return Complex(z.x + w.x, z.y + w.y)
}
@_transparent
public static func -(z: Complex, w: Complex) -> Complex {
return Complex(z.x - w.x, z.y - w.y)
}
@_transparent
public static func +=(z: inout Complex, w: Complex) {
z = z + w
}
@_transparent
public static func -=(z: inout Complex, w: Complex) {
z = z - w
}
}
import RealModule
// MARK: - Vector space structure
//
// Policy: deliberately not using the * and / operators for these at the
// moment, because then there's an ambiguity in expressions like 2*z; is
// that Complex(2) * z or is it RealType(2) * z? This is especially
// problematic in type inference: suppose we have:
//
// let a: RealType = 1
// let b = 2*a
//
// what is the type of b? If we don't have a type context, it's ambiguous.
// If we have a Complex type context, then b will be inferred to have type
// Complex! Obviously, that doesn't help anyone.
//
// TODO: figure out if there's some way to avoid these surprising results
// and turn these into operators if/when we have it.
// (https://github.com/apple/swift-numerics/issues/12)
extension Complex {
@usableFromInline @_transparent
internal func multiplied(by a: RealType) -> Complex {
Complex(x*a, y*a)
extension Complex: AlgebraicField {
/// The multiplicative identity `1 + 0i`.
@_transparent
public static var one: Complex {
Complex(1, 0)
}
@usableFromInline @_transparent
internal func divided(by a: RealType) -> Complex {
Complex(x/a, y/a)
}
}
// MARK: - Multiplicative structure
extension Complex: Numeric {
/// The [complex conjugate][conj] of this value.
///
/// [conj]: https://en.wikipedia.org/wiki/Complex_conjugate
@_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)
public var conjugate: Complex {
Complex(x, -y)
}
@_transparent
@@ -73,14 +31,9 @@ extension Complex: Numeric {
// Try the naive expression z/w = z*conj(w) / |w|^2; if we can compute
// this without over/underflow, everything is fine and the result is
// correct. If not, we have to rescale and do the computation carefully.
let lengthSquared = w.unsafeLengthSquared
guard lengthSquared.isNormal else { return rescaledDivide(z, w) }
return z * (w.conjugate.divided(by: lengthSquared))
}
@_transparent
public static func *=(z: inout Complex, w: Complex) {
z = z * w
let lenSq = w.lengthSquared
guard lenSq.isNormal else { return rescaledDivide(z, w) }
return z * (w.conjugate.divided(by: lenSq))
}
@_transparent
@@ -98,7 +51,7 @@ extension Complex: Numeric {
let wScale = w.magnitude
let zNorm = z.divided(by: zScale)
let wNorm = w.divided(by: wScale)
let r = (zNorm * wNorm.conjugate).divided(by: wNorm.unsafeLengthSquared)
let r = (zNorm * wNorm.conjugate).divided(by: wNorm.lengthSquared)
// At this point, the result is (r * zScale)/wScale computed without
// undue overflow or underflow. We know that r is close to unity, so
// the question is simply what order in which to do this computation
@@ -124,8 +77,8 @@ extension Complex: Numeric {
/// A normalized complex number with the same phase as this value.
///
/// If such a value cannot be produced (because the phase of zero and infinity is undefined),
/// `nil` is returned.
/// If such a value cannot be produced (because the phase of zero and
/// infinity is undefined), `nil` is returned.
@inlinable
public var normalized: Complex? {
if length.isNormal {
@@ -137,16 +90,18 @@ extension Complex: Numeric {
return self.divided(by: magnitude).normalized
}
/// The reciprocal of this value, if it can be computed without undue overflow or underflow.
/// The reciprocal of this value, if it can be computed without undue
/// overflow or underflow.
///
/// If z.reciprocal is non-nil, you can safely replace division by z with multiplication by this value. It is
/// not advantageous to do this for an isolated division, but if you are dividing many values by a single
/// If z.reciprocal is non-nil, you can safely replace division by z with
/// multiplication by this value. It is not advantageous to do this for an
/// isolated division, but if you are dividing many values by a single
/// denominator, this will often be a significant performance win.
///
/// Typical use looks like this:
/// A typical use case looks something like this:
/// ```
/// func divide<T: Real>(data: [Complex<T>], by divisor: Complex<T>) -> [Complex<T>] {
/// // If divisor is well-scaled, use multiply by reciprocal.
/// // If divisor is well-scaled, multiply by reciprocal.
/// if let recip = divisor.reciprocal {
/// return data.map { $0 * recip }
/// }
@@ -154,6 +109,12 @@ extension Complex: Numeric {
/// return data.map { $0 / divisor }
/// }
/// ```
///
/// Error Bounds:
///
/// Unlike real types, when working with complex types, multiplying by the
/// reciprocal instead of dividing cannot change the result. If the
/// reciprocal is non-nil, the two computations are always equivalent.
@inlinable
public var reciprocal: Complex? {
let recip = 1/self
@@ -162,6 +123,17 @@ extension Complex: Numeric {
}
return nil
}
@_transparent
public static func _relaxedAdd(_ a: Self, _ b: Self) -> Self {
Complex(Relaxed.sum(a.x, b.x), Relaxed.sum(a.y, b.y))
}
@_transparent
public static func _relaxedMul(_ a: Self, _ b: Self) -> Self {
Complex(
Relaxed.sum(Relaxed.product(a.x, b.x), -Relaxed.product(a.y, b.y)),
Relaxed.sum(Relaxed.product(a.x, b.y), Relaxed.product(a.y, b.x))
)
}
}
extension Complex: SignedNumeric {}
@@ -0,0 +1,30 @@
//===--- Complex+Codable.swift --------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import RealModule
// FloatingPoint does not refine Codable, so this is a conditional conformance.
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)
}
}
@@ -0,0 +1,482 @@
//===--- Complex+ElementaryFunctions.swift --------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Implementation goals, in order of priority:
//
// 1. Get the branch cuts right. We should match Kahan's /Much Ado/
// paper for finite values.
// 2. Have good relative accuracy in the complex norm.
// 3. Preserve sign symmetries where possible.
// 4. Handle the point at infinity consistently with basic operations.
// This means diverging from what C and C++ do for non-finite inputs.
// 5. Get good componentwise accuracy /when possible/. I don't know how
// to do that for all of these functions off the top of my head, and
// I don't think that other libraries have tried to do so in general,
// so this is a research project. We should not sacrifice 1-4 for it.
// Note that multiplication and division don't even provide good
// componentwise relative accuracy, so it's _totally OK_ to not get
// it for these functions too. But: it's a dynamite long-term research
// project.
// 6. Give the best performance we can. We should care about performance,
// but with lower precedence than the other considerations.
//
// Except where derivations are given, the expressions used here are all
// adapted from Kahan's 1986 paper "Branch Cuts for Complex Elementary
// Functions; or: Much Ado About Nothing's Sign Bit".
import RealModule
extension Complex: ElementaryFunctions {
// MARK: - exp-like functions
/// The complex exponential function e^z whose base `e` is the base of the
/// natural logarithm.
///
/// Mathematically, this operation can be expanded in terms of the `Real`
/// operations `exp`, `cos` and `sin` as follows:
/// ```
/// exp(x + iy) = exp(x) exp(iy)
/// = exp(x) cos(y) + i exp(x) sin(y)
/// ```
/// Note that naive evaluation of this expression in floating-point would be
/// prone to premature overflow, since `cos` and `sin` both have magnitude
/// less than 1 for most inputs (i.e. `exp(x)` may be infinity when
/// `exp(x) cos(y)` would not be).
@inlinable
public static func exp(_ z: Complex) -> Complex {
guard z.isFinite else { return z }
// If x < log(greatestFiniteMagnitude), then exp(x) does not overflow.
// To protect ourselves against sketchy log or exp implementations in
// an unknown host library, or slight rounding disagreements between
// the two, subtract one from the bound for a little safety margin.
guard z.x < RealType.log(.greatestFiniteMagnitude) - 1 else {
let halfScale = RealType.exp(z.x/2)
let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))
return phase.multiplied(by: halfScale).multiplied(by: halfScale)
}
return Complex(.cos(z.y), .sin(z.y)).multiplied(by: .exp(z.x))
}
@inlinable
public static func expMinusOne(_ z: Complex) -> Complex {
// exp(x + iy) - 1 = (exp(x) cos(y) - 1) + i exp(x) sin(y)
// -------- u --------
// Note that the imaginary part is just the usual exp(x) sin(y);
// the only trick is computing the real part ("u"):
//
// u = exp(x) cos(y) - 1
// = exp(x) cos(y) - cos(y) + cos(y) - 1
// = (exp(x) - 1) cos(y) + (cos(y) - 1)
// = expMinusOne(x) cos(y) + cosMinusOne(y)
//
// Note: most implementations of expm1 for complex (e.g. Julia's)
// factor the real part as follows instead:
//
// exp(x) cosMinuxOne(y) + expMinusOne(x)
//
// The other implementation that is sometimes seen is:
//
// expMinusOne(z) = 2*exp(z/2)*sinh(z/2)
//
// All three of these implementations provide good relative error
// bounds _in the complex norm_, but the cosineMinusOne-based
// implementation has the best _componentwise_ error characteristics,
// which is why we use it here:
//
// Implementation | Real | Imaginary |
// ---------------+--------------------+----------------+
// Ours | Hybrid bound | Relative bound |
// Standard | No bound | Relative bound |
// Half Angle | Hybrid bound | Hybrid bound |
//
// FUTURE WORK: devise an algorithm that achieves good _relative_ error
// in the real component as well. Doing this efficiently is a research
// project--exp(x) cos(y) - 1 can be very nearly zero along a curve in
// the complex plane, not only at zero. Evaluating it accurately
// _without_ depending on arbitrary-precision exp and cos is an
// interesting challenge.
guard z.isFinite else { return z }
// If exp(z) is close to the overflow boundary, we don't need to
// worry about the "MinusOne" part of this function; we're just
// computing exp(z). (Even when z.y is near a multiple of π/2,
// it can't be close enough to overcome the scaling from exp(z.x),
// so the -1 term is _always_ negligable). So we simply handle
// these cases exactly the same as exp(z).
guard z.x < RealType.log(.greatestFiniteMagnitude) - 1 else {
let halfScale = RealType.exp(z.x/2)
let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))
return phase.multiplied(by: halfScale).multiplied(by: halfScale)
}
// Special cases out of the way, evaluate as discussed above.
return Complex(
Relaxed.multiplyAdd(.cos(z.y), .expMinusOne(z.x), .cosMinusOne(z.y)),
.exp(z.x) * .sin(z.y)
)
}
// cosh(x + iy) = cosh(x) cos(y) + i sinh(x) sin(y).
//
// Like exp, cosh is entire, so we do not need to worry about where
// branch cuts fall. Also like exp, cancellation never occurs in the
// evaluation of the naive expression, so all we need to be careful
// about is the behavior near the overflow boundary.
//
// Fortunately, if |x| >= -log(ulpOfOne), cosh(x) and sinh(x) are
// both just exp(|x|)/2, and we already know how to compute that.
//
// This function and sinh should stay in sync; if you make a
// modification here, you should almost surely make a parallel
// modification to sinh below.
@inlinable
public static func cosh(_ z: Complex) -> Complex {
guard z.isFinite else { return z }
guard z.x.magnitude < -RealType.log(.ulpOfOne) else {
let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))
let firstScale = RealType.exp(z.x.magnitude/2)
let secondScale = firstScale/2
return phase.multiplied(by: firstScale).multiplied(by: secondScale)
}
// Future optimization opportunity: expm1 is faster than cosh/sinh
// on most platforms, and division is now commonly pipelined, so we
// might replace the check above with a much more conservative one,
// and then evaluate cosh(x) and sinh(x) as
//
// cosh(x) = 1 + 0.5*expm1(x)*expm1(x) / (1 + expm1(x))
// sinh(x) = expm1(x) + 0.5*expm1(x) / (1 + expm1(x))
//
// This won't be a _big_ win except on platforms with a crappy sinh
// and cosh, and for those we should probably just provide our own
// implementations of _those_, so for now let's keep it simple and
// obviously correct.
return Complex(
RealType.cosh(z.x) * RealType.cos(z.y),
RealType.sinh(z.x) * RealType.sin(z.y)
)
}
// sinh(x + iy) = sinh(x) cos(y) + i cosh(x) sin(y)
//
// See cosh above for algorithm details.
@inlinable
public static func sinh(_ z: Complex) -> Complex {
guard z.isFinite else { return z }
guard z.x.magnitude < -RealType.log(.ulpOfOne) else {
let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))
let firstScale = RealType.exp(z.x.magnitude/2)
let secondScale = RealType(signOf: z.x, magnitudeOf: firstScale/2)
return phase.multiplied(by: firstScale).multiplied(by: secondScale)
}
return Complex(
RealType.sinh(z.x) * RealType.cos(z.y),
RealType.cosh(z.x) * RealType.sin(z.y)
)
}
// tanh(z) = sinh(z) / cosh(z)
@inlinable
public static func tanh(_ z: Complex) -> Complex {
guard z.isFinite else { return z }
// Note that when |x| is larger than -log(.ulpOfOne),
// sinh(x + iy) == ±cosh(x + iy), so tanh(x + iy) is just ±1.
guard z.x.magnitude < -RealType.log(.ulpOfOne) else {
return Complex(
RealType(signOf: z.x, magnitudeOf: 1),
RealType(signOf: z.y, magnitudeOf: 0)
)
}
// Now we have z in a vertical strip where exp(x) is reasonable,
// and y is finite, so we can simply evaluate sinh(z) and cosh(z).
//
// TODO: Kahan uses a different expression for evaluation here; it
// isn't strictly necessary for numerics reasons--it's to avoid
// doing the complex division, but it probably provides better
// componentwise error bounds, and is likely more efficient (because
// it avoids the complex division, which is painful even when well-
// scaled). This suffices to get us up and running.
return sinh(z) / cosh(z)
}
// cos(z) = cosh(iz)
@inlinable
public static func cos(_ z: Complex) -> Complex {
return cosh(Complex(-z.y, z.x))
}
// sin(z) = -i*sinh(iz)
@inlinable
public static func sin(_ z: Complex) -> Complex {
let w = sinh(Complex(-z.y, z.x))
return Complex(w.y, -w.x)
}
// tan(z) = -i*tanh(iz)
@inlinable
public static func tan(_ z: Complex) -> Complex {
let w = tanh(Complex(-z.y, z.x))
return Complex(w.y, -w.x)
}
// MARK: - log-like functions
@inlinable
public static func log(_ z: Complex) -> Complex {
// If z is zero or infinite, the phase is undefined, so the result is
// the single exceptional value.
guard z.isFinite && !z.isZero else { return .infinity }
// Having eliminated non-finite values and zero, the imaginary part is
// easy; it's just the phase, which is always computed with good
// relative accuracy via atan2.
let θ = z.phase
// The real part of the result is trickier. In exact arithmetic, the
// real part is just log |z|--many implementations of complex functions
// simply use this expression as is. However, there are two problems
// lurking here:
//
// - length can overflow even when log(z) is finite.
//
// - when length is close to 1, catastrophic cancellation is hidden
// in this expression. Consider, e.g. z = 1 + δi for small δ.
//
// Because δ ≪ 1, |z| rounds to 1, and so log |z| produces zero.
// We can expand using Taylor series to see that the result should
// be:
//
// log |z| = log √(1 + δ²)
// = log(1 + δ²)/2
// = δ²/2 + O(δ⁴)
//
// So naively using log |z| results in a total loss of relative
// accuracy for this case. Note that this is _not_ constrained near
// a single point; it occurs everywhere close to the circle |z| = 1.
//
// Note that this case still _does_ deliver a result with acceptable
// relative accuracy in the complex norm, because
//
// Im(log z) ≈ δ ≫ δ²/2 ≈ Re(log z).
//
// There are a number of ways to try to tackle this problem. I'll begin
// with a simple one that solves the first issue, and _sometimes_ the
// second, then analyze when it doesn't work for the second case.
//
// To handle very large arguments without overflow, the standard
// approach is to _rescale_ the problem. We can do this by finding
// whichever of x and y has greater magnitude, and dividing through
// by it. You can think of this as changing coordinates by reflections
// so that we get a new value w = u + iv with |w| = |z| (and hence
// Re(log w) = Re(log z), and 0 ≤ u, 0 ≤ v ≤ u.
let u = max(z.x.magnitude, z.y.magnitude)
let v = min(z.x.magnitude, z.y.magnitude)
// Now expand out log |w|:
//
// log |w| = log(u² + v²)/2
// = log u + log(onePlus: (v/u)²)/2
//
// This looks promising! It handles overflow well, because log(u) is
// finite for every finite u, and we have 0 ≤ v/u ≤ 1, so the second
// term is bounded by 0 ≤ log(1 + (v/u)²)/2 ≤ (log 2)/2. It also
// handles the example I gave above well: we have u = 1, v = δ, and
//
// log(1) + log(onePlus: δ²)/2 = 0 + δ²/2
//
// as expected.
//
// Unfortunately, it does not handle all points close to the unit
// circle so well; it's easy to see why if we look at the two terms
// that contribute to the result. Cancellation occurs when the result
// is close to zero and the terms have opposing signs. By construction,
// the second term is always positive, so the easiest observation is
// that cancellation is only a problem for u < 1 (because otherwise
// log u is also positive, and there can be no cancellation).
//
// We are not trying for sub-ulp accuracy, just a good relative error
// bound, so for our purposes it suffices to have log u dominate the
// result:
if u >= 1 || u >= Relaxed.multiplyAdd(u, u, v*v) {
let r = v / u
return Complex(.log(u) + .log(onePlus: r*r)/2, θ)
}
// Here we're in the tricky case; cancellation is likely to occur.
// Instead of the factorization used above, we will want to evaluate
// log(onePlus: u² + v² - 1)/2. This all boils down to accurately
// evaluating u² + v² - 1. To begin, calculate both squared terms
// as exact head-tail products (u is guaranteed to be well scaled,
// v may underflow, but if it does it doesn't matter, the u term is
// all we need).
let (a,b) = Augmented.product(u, u)
let (c,d) = Augmented.product(v, v)
// It would be nice if we could simply use a - 1, but unfortunately
// we don't have a tight enough bound to guarantee that that expression
// is exact; a may be as small as 1/4, so we could lose a single bit
// to rounding if we did that.
var (s,e) = Augmented.sum(large: -1, small: a)
// Now we are ready to assemble the result. If cancellation happens,
// then |c| > |e| > |b|, |d|, so this assembly order is safe. It's
// also possible that |c| and |d| are small, but if that happens then
// there is no significant cancellation, and the exact assembly doesn't
// matter.
s = (s + c) + e + b + d
return Complex(.log(onePlus: s)/2, θ)
}
@inlinable
public static func log(onePlus z: Complex) -> Complex {
// If either |x| or |y| is bounded away from the origin, we don't need
// any extra precision, and can just literally compute log(1+z). Note
// that this includes part of the circle |1+z| = 1 where log(onePlus:)
// vanishes (where x <= -0.5), but on this portion of the circle 1+x
// is always exact by Sterbenz' lemma, so as long as log( ) produces
// a good result, log(1+z) will too.
guard 2*z.x.magnitude < 1 && z.y.magnitude < 1 else { return log(1+z) }
// z is in (±0.5, ±1), so we need to evaluate more carefully.
// The imaginary part is straightforward:
let θ = (1+z).phase
// For the real part, we _could_ use the same approach that we do for
// log( ), but we'd need an extra-precise (1+x)², which can potentially
// be quite painful to calculate. Instead, we can use an approach that
// NevinBR suggested on the Swift forums:
//
// Re(log(1+z)) = (log(1+z) + log(1+z̅)) / 2
// = log((1+z)(1+z̅)) / 2
// = log(1 + z + z̅ + zz̅) / 2
// = log(1 + 2x + x² + y²) / 2
// = log(onePlus: (2+x)x + y²) / 2
//
// So now we need to evaluate (2+x)x + y² accurately. To do this,
// we employ augmented arithmetic; the key observation here is that
// cancellation is only a problem when y² ≈ -(2+x)x
let xp2 = Augmented.sum(large: 2, small: z.x) // Known that 2 > |x|.
let a = Augmented.product(z.x, xp2.head)
let y² = Augmented.product(z.y, z.y)
let s = (a.head + y².head + a.tail + y².tail).addingProduct(z.x, xp2.tail)
return Complex(.log(onePlus: s)/2, θ)
}
@inlinable
public static func acos(_ z: Complex) -> Complex {
Complex(
2*RealType.atan2(y: sqrt(1-z).real, x: sqrt(1+z).real),
RealType.asinh((sqrt(1+z).conjugate * sqrt(1-z)).imaginary)
)
}
@inlinable
public static func asin(_ z: Complex) -> Complex {
Complex(
RealType.atan2(y: z.x, x: (sqrt(1-z) * sqrt(1+z)).real),
RealType.asinh((sqrt(1-z).conjugate * sqrt(1+z)).imaginary)
)
}
// atan(z) = -i*atanh(iz)
@inlinable
public static func atan(_ z: Complex) -> Complex {
let w = atanh(Complex(-z.y, z.x))
return Complex(w.y, -w.x)
}
@inlinable
public static func acosh(_ z: Complex) -> Complex {
Complex(
RealType.asinh((sqrt(z-1).conjugate * sqrt(z+1)).real),
2*RealType.atan2(y: sqrt(z-1).imaginary, x: sqrt(z+1).real)
)
}
// asinh(z) = -i*asin(iz)
@inlinable
public static func asinh(_ z: Complex) -> Complex {
let w = asin(Complex(-z.y, z.x))
return Complex(w.y, -w.x)
}
@inlinable
public static func atanh(_ z: Complex) -> Complex {
// TODO: Kahan uses a much more complicated expression here; possibly
// simply because he didn't have a complex log(1+z) with good
// characteristics. Investigate tradeoffs further.
//
// Further TODO: decide policy for point at infinity / NaN. Unlike most
// of these functions, atanh doesn't have a pole at infinity; convention
// in C-family languages is use one value in the upper half plane, and
// another in the lower. Requires some thought about the most appropriate
// way to handle this case in Swift.
(log(onePlus: z) - log(onePlus:-z))/2
}
// MARK: - pow-like functions
/// `exp(w*log(z))`
///
/// Edge cases for this function are defined according to the defining
/// expression exp(w log(z)), except that we define pow(0, w) to be 0
/// instead of infinity when w is in the (strict) right half-plane, so that
/// we agree with RealType.pow on the positive real line.
@inlinable
public static func pow(_ z: Complex, _ w: Complex) -> Complex {
if z.isZero { return w.real > 0 ? zero : infinity }
return exp(w * log(z))
}
@inlinable
public static func pow(_ z: Complex, _ n: Int) -> Complex {
if z.isZero { return n < 0 ? infinity : n == 0 ? one : zero }
// TODO: this implementation is not quite correct, because n may be
// rounded in conversion to RealType. This only effects very extreme
// cases, so we'll leave it alone for now.
//
// Note that this does not have the same problems that a similar
// implementation for a real type would have, because there's no
// parity/sign interaction in the complex plane.
return exp(log(z).multiplied(by: RealType(n)))
}
@inlinable
public static func sqrt(_ z: Complex) -> Complex {
let lengthSquared = z.lengthSquared
if lengthSquared.isNormal {
// If |z|^2 doesn't overflow, then define u and v by:
//
// u = sqrt((|z|+|x|)/2)
// v = y/2u
//
// If x is positive, the result is just w = (u, v). If x is negative,
// the result is (|v|, copysign(u, y)) instead.
let norm = RealType.sqrt(lengthSquared)
let u = RealType.sqrt((norm + abs(z.x))/2)
let v: RealType = z.y / (2*u)
if z.x.sign == .plus {
return Complex(u, v)
} else {
return Complex(abs(v), RealType(signOf: z.y, magnitudeOf: u))
}
}
// Handle edge cases:
if z.isZero { return Complex(0, z.y) }
if !z.isFinite { return z }
// z is finite but badly-scaled. Rescale and replay by factoring out
// the larger of x and y.
let scale = RealType.maximum(abs(z.x), abs(z.y))
return Complex.sqrt(z.divided(by: scale)).multiplied(by: .sqrt(scale))
}
@inlinable
public static func root(_ z: Complex, _ n: Int) -> Complex {
if z.isZero { return .zero }
// TODO: this implementation is not quite correct, because n may be
// rounded in conversion to RealType. This only effects very extreme
// cases, so we'll leave it alone for now.
//
// Note that this does not have the same problems that a similar
// implementation for a real type would have, because there's no
// parity/sign interaction in the complex plane.
return exp(log(z).divided(by: RealType(n)))
}
}
@@ -0,0 +1,42 @@
//===--- Complex+Hashable.swift -------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import RealModule
extension Complex: Hashable {
@_transparent
public static func ==(a: Complex, b: Complex) -> Bool {
// Identify all numbers with either component non-finite as a single
// "point at infinity".
guard a.isFinite || b.isFinite else { return true }
// For finite numbers, equality is defined componentwise. Cases where
// only one of a or b is infinite fall through to here as well, but this
// expression correctly returns false for them so we don't need to handle
// them explicitly.
return a.x == b.x && a.y == b.y
}
@_transparent
public func hash(into hasher: inout Hasher) {
// There are two equivalence classes to which we owe special attention:
// All zeros should hash to the same value, regardless of sign, and all
// non-finite numbers should hash to the same value, regardless of
// representation. The correct behavior for zero falls out for free from
// the hash behavior of floating-point, but we need to use a
// representative member for any non-finite values.
if isFinite {
hasher.combine(x)
hasher.combine(y)
} else {
hasher.combine(RealType.infinity)
}
}
}
@@ -0,0 +1,19 @@
//===--- Complex+IntegerLiteral.swift -------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 - 2021 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 Complex: ExpressibleByIntegerLiteral {
public typealias IntegerLiteralType = RealType.IntegerLiteralType
@inlinable
public init(integerLiteral value: IntegerLiteralType) {
self.init(RealType(integerLiteral: value))
}
}
@@ -0,0 +1,56 @@
//===--- Complex+Numeric.swift --------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 - 2021 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 Complex: Numeric {
@_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)
}
@_transparent
public static func *=(z: inout Complex, w: Complex) {
z = z * w
}
/// The complex number with specified real part and zero imaginary part.
///
/// Equivalent to `Complex(RealType(real), 0)`.
@inlinable
public init<Other: BinaryInteger>(_ real: Other) {
self.init(RealType(real), 0)
}
/// The complex number with specified real part and zero imaginary part,
/// if it can be constructed without rounding.
@inlinable
public init?<Other: BinaryInteger>(exactly real: Other) {
guard let real = RealType(exactly: real) else { return nil }
self.init(real, 0)
}
/// The ∞-norm of the value (`max(abs(real), abs(imaginary))`).
///
/// If you need the Euclidean norm (a.k.a. 2-norm) use the `length` or
/// `lengthSquared` properties instead.
///
/// Edge cases:
/// - If `z` is not finite, `z.magnitude` is `.infinity`.
/// - If `z` is zero, `z.magnitude` is `0`.
/// - Otherwise, `z.magnitude` is finite and non-zero.
///
/// See also `.length` and `.lengthSquared`.
@_transparent
public var magnitude: RealType {
guard isFinite else { return .infinity }
return max(abs(x), abs(y))
}
}
@@ -0,0 +1,23 @@
//===--- Complex+StringConvertible.swift ----------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 - 2021 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 Complex: CustomStringConvertible {
public var description: String {
guard isFinite else { return "inf" }
return "(\(x), \(y))"
}
}
extension Complex: CustomDebugStringConvertible {
public var debugDescription: String {
"Complex<\(RealType.self)>(\(String(reflecting: x)), \(String(reflecting: y)))"
}
}
+226
View File
@@ -0,0 +1,226 @@
//===--- Complex.swift ----------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import RealModule
/// A complex number represented by real and imaginary parts.
///
/// TODO: introductory text on complex numbers
///
/// Implementation notes:
///
/// This type does not provide heterogeneous real/complex arithmetic,
/// not even the natural vector-space operations like real * complex.
/// There are two reasons for this choice: first, Swift broadly avoids
/// mixed-type arithmetic when the operation can be adequately expressed
/// by a conversion and homogeneous arithmetic. Second, with the current
/// typechecker rules, it would lead to undesirable ambiguity in common
/// expressions (see README.md for more details).
///
/// Unlike C's `_Complex` and C++'s `std::complex<>` types, we do not
/// attempt to make meaningful semantic distinctions between different
/// representations of infinity or NaN. Any Complex value with at least
/// one non-finite component is simply "non-finite". In as much as
/// possible, we use the semantics of the point at infinity on the
/// Riemann sphere for such values. This approach simplifies the number of
/// edge cases that need to be considered for multiplication, division, and
/// the elementary functions considerably.
///
/// `.magnitude` does not return the Euclidean norm; it uses the "infinity
/// norm" (`max(|real|,|imaginary|)`) instead. There are two reasons for this
/// choice: first, it's simply faster to compute on most hardware. Second,
/// there exist values for which the Euclidean norm cannot be represented
/// (consider a number with `.real` and `.imaginary` both equal to
/// `RealType.greatestFiniteMagnitude`; the Euclidean norm would be
/// `.sqrt(2) * .greatestFiniteMagnitude`, which overflows). Using
/// the infinity norm avoids this problem entirely without significant
/// downsides. You can access the Euclidean norm using the `length`
/// property.
@frozen
public struct Complex<RealType> where RealType: Real {
// A note on the `x` and `y` properties
//
// `x` and `y` are the names we use for the raw storage of the real and
// imaginary components of our complex number. We also provide public
// `.real` and `.imaginary` properties, which wrap this storage and
// fixup the semantics for non-finite values.
/// The real component of the value.
@usableFromInline @inline(__always)
internal var x: RealType
/// The imaginary part of the value.
@usableFromInline @inline(__always)
internal var y: RealType
/// A complex number constructed by specifying the real and imaginary parts.
@_transparent
public init(_ real: RealType, _ imaginary: RealType) {
x = real
y = imaginary
}
}
extension Complex: Sendable where RealType: Sendable { }
// MARK: - Basic properties
extension Complex {
/// The real part of this complex value.
///
/// If `z` is not finite, `z.real` is `.nan`.
public var real: RealType {
@_transparent
get { isFinite ? x : .nan }
@_transparent
set { x = newValue }
}
/// The imaginary part of this complex value.
///
/// If `z` is not finite, `z.imaginary` is `.nan`.
public var imaginary: RealType {
@_transparent
get { isFinite ? y : .nan }
@_transparent
set { y = newValue }
}
/// The raw representation of the real part of this value.
@_transparent
public var _rawX: RealType { x }
/// The raw representation of the imaginary part of this value.
@_transparent
public var _rawY: RealType { y }
}
extension Complex {
/// The imaginary unit.
///
/// See also `.zero`, `.one` and `.infinity`.
@_transparent
public static var i: Complex {
Complex(0, 1)
}
/// The point at infinity.
///
/// See also `.zero`, `.one` and `.i`.
@_transparent
public static var infinity: Complex {
Complex(.infinity, 0)
}
/// True if this value is finite.
///
/// A complex value is finite if neither component is an infinity or nan.
///
/// See also `.isNormal`, `.isSubnormal` and `.isZero`.
@_transparent
public var isFinite: Bool {
x.isFinite && y.isFinite
}
/// True if this value is normal.
///
/// A complex number is normal if it is finite and *either* the real or
/// imaginary component is normal. A floating-point number representing
/// one of the components is normal if its exponent allows a full-precision
/// representation.
///
/// See also `.isFinite`, `.isSubnormal` and `.isZero`.
@_transparent
public var isNormal: Bool {
isFinite && (x.isNormal || y.isNormal)
}
/// True if this value is subnormal.
///
/// A complex number is subnormal if it is finite, not normal, and not zero.
/// When the result of a computation is subnormal, underflow has occurred and
/// the result generally does not have full precision.
///
/// See also `.isFinite`, `.isNormal` and `.isZero`.
@_transparent
public var isSubnormal: Bool {
isFinite && !isNormal && !isZero
}
/// True if this value is zero.
///
/// A complex number is zero if *both* the real and imaginary components
/// are zero.
///
/// See also `.isFinite`, `.isNormal` and `isSubnormal`.
@_transparent
public var isZero: Bool {
x == 0 && y == 0
}
/// A "canonical" representation of the value.
///
/// For normal complex numbers with a RealType conforming to
/// BinaryFloatingPoint (the common case), the result is simply this value
/// unmodified. For zeros, the result has the representation (+0, +0). For
/// infinite values, the result has the representation (+inf, +0).
///
/// If the RealType admits non-canonical representations, the x and y
/// components are canonicalized in the result.
///
/// This is mainly useful for interoperation with other languages, where
/// you may want to reduce each equivalence class to a single representative
/// before passing across language boundaries, but it may also be useful
/// for some serialization tasks. It's also a useful implementation detail
/// for some primitive operations.
@_transparent
public var canonicalized: Self {
if isZero { return .zero }
if isFinite { return self.multiplied(by: 1) }
return .infinity
}
}
// MARK: - Additional Initializers
extension Complex {
/// The complex number with specified real part and zero imaginary part.
///
/// Equivalent to `Complex(real, 0)`.
@inlinable
public init(_ real: RealType) {
self.init(real, 0)
}
/// The complex number with specified imaginary part and zero real part.
///
/// Equivalent to `Complex(0, imaginary)`.
@inlinable
public init(imaginary: RealType) {
self.init(0, imaginary)
}
}
extension Complex where RealType: BinaryFloatingPoint {
/// `other` rounded to the nearest representable value of this type.
@inlinable
public init<Other: BinaryFloatingPoint>(_ other: Complex<Other>) {
self.init(RealType(other.x), RealType(other.y))
}
/// `other`, if it can be represented exactly in this type; otherwise `nil`.
@inlinable
public init?<Other: BinaryFloatingPoint>(exactly other: Complex<Other>) {
guard let x = RealType(exactly: other.x),
let y = RealType(exactly: other.y) else { return nil }
self.init(x, y)
}
}
+133
View File
@@ -0,0 +1,133 @@
//===--- Polar.swift ------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import RealModule
extension Complex {
/// 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:
///
/// let x: Float = 3.0e+20
/// let x: Float = 4.0e+20
/// let naive = sqrt(x*x + y*y) // +Inf
/// let careful = Complex(x, y).length // 5.0e+20
///
/// Note that it *is* still possible for this property to overflow,
/// because the length can be as much as sqrt(2) times larger than
/// either component, and thus may not be representable in the real type.
///
/// For most use cases, you can use the cheaper `.magnitude`
/// property (which computes the ∞-norm) instead, which always produces
/// a representable result.
///
/// Edge cases:
/// - If a complex value is not finite, its `.length` is `infinity`.
///
/// See also `.magnitude`, `.lengthSquared`, `.phase`, `.polar`
/// and `init(r:θ:)`.
@_transparent
public var length: RealType {
let naive = lengthSquared
guard naive.isNormal else { return carefulLength }
return .sqrt(naive)
}
// Internal implementation detail of `length`, moving slow path off
// of the inline function. Note that even `carefulLength` can overflow
// for finite inputs, but only when the result is outside the range
// of representable values.
@usableFromInline
internal var carefulLength: RealType {
guard isFinite else { return .infinity }
return .hypot(x, y)
}
/// The squared length `(real*real + imaginary*imaginary)`.
///
/// This property is more efficient to compute than `length`, but is
/// highly prone to overflow or underflow; for finite values that are
/// not well-scaled, `lengthSquared` is often either zero or
/// infinity, even when `length` is a finite number. Use this property
/// only when you are certain that this value is well-scaled.
///
/// For many cases, `.magnitude` can be used instead, which is similarly
/// cheap to compute and always returns a representable value.
///
/// See also `.length` and `.magnitude`.
@_transparent
public var lengthSquared: RealType {
x*x + y*y
}
@available(*, unavailable, renamed: "lengthSquared")
public var unsafeLengthSquared: RealType { lengthSquared }
/// The phase (angle, or "argument").
///
/// Returns the angle (measured above the real axis) in radians. If
/// the complex value is zero or infinity, the phase is not defined,
/// and `nan` is returned.
///
/// Edge cases:
/// - If the complex value is zero or non-finite, phase is `nan`.
///
/// See also `.length`, `.polar` and `init(r:θ:)`.
@inlinable
public var phase: RealType {
guard isFinite && !isZero else { return .nan }
return .atan2(y: y, x: x)
}
/// The length and phase (or polar coordinates) of this value.
///
/// Edge cases:
/// - If the complex value is zero or non-finite, phase is `.nan`.
/// - If the complex value is non-finite, length is `.infinity`.
///
/// See also: `.length`, `.phase` and `init(r:θ:)`.
public var polar: (length: RealType, phase: RealType) {
(length, phase)
}
/// Creates a complex value specified with polar coordinates.
///
/// Edge cases:
/// - Negative lengths are interpreted as reflecting the point through the
/// origin, i.e.:
/// ```
/// Complex(length: -r, phase: θ) == -Complex(length: r, phase: θ)
/// ```
/// - For any `θ`, even `.infinity` or `.nan`:
/// ```
/// Complex(length: .zero, phase: θ) == .zero
/// ```
/// - For any `θ`, even `.infinity` or `.nan`, if `r` is infinite then:
/// ```
/// Complex(length: r, phase: θ) == .infinity
/// ```
/// - Otherwise, `θ` must be finite, or a precondition failure occurs.
///
/// See also `.length`, `.phase` and `.polar`.
@inlinable
public init(length: RealType, phase: RealType) {
if phase.isFinite {
self = Complex(.cos(phase), .sin(phase)).multiplied(by: length)
} else {
precondition(
length.isZero || length.isInfinite,
"Either phase must be finite, or length must be zero or infinite."
)
self = Complex(length)
}
}
}
@@ -2,15 +2,17 @@
This module provides a `Complex` number type generic over an underlying `RealType`:
```swift
1> import Complex
2> let z = Complex(1,1) // z = 1 + i
import Numerics
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).
This module provides approximate feature parity and memory layout compatibility with C, Fortran, and C++ complex types (although the importer does not 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`).
The `Complex` type conforms to `ElementaryFunctions`, which makes common transcendental functions like `log`, `pow`, and `sin` available (consult the documentation for `ElementaryFunctions` in the `RealModule` for a full list and more information.
### Dependencies:
- The `Real` module.
- `RealModule`.
## Design notes
@@ -36,10 +38,10 @@ They are not provided by the Complex module for two reasons:
}
}
```
This is a show-stopper for heterogeneous arithmetic operators in the short term.
This makes heterogeneous arithmetic operators a non-option in the short term.
### Infinity and nan
C and C++ attempt to define precise semantics that interpret the sign of infinity and zero.
C and C++ attempt to define semantics that interpret the signs of infinity and zero.
This is occasionally useful, but it also results in a lot of extra work.
The Swift Numerics `Complex` type does not assign any semantic meaning to the sign of zero and infinity; `(±0,±0)`, are all considered to be encodings of the value zero.
Similarly, `(±inf, y)`, `(x, ±inf)`, `(nan, y)` and `(x, nan)` are all considered to be encodings of a single exceptional value with infinite magnitude and undefined phase.
@@ -54,13 +56,14 @@ However, in practice there are good reasons to use something else instead:
- The 2-norm requires special care to avoid spurious overflow/underflow, but the naive expressions for the 1-norm ("taxicab norm") or ∞-norm ("sup norm") are always correct.
- Even when care is used, near the overflow boundary the 2-norm and the 1-norm are not representable.
As an example, consider `z = Complex(big, big)`, where `big` is `Double.greatestFiniteMagnitude`. The 1-norm and 2-norm of `z` both overflow (the 1-norm would be `2*big`, and the 2-norm would be `sqrt(2)*big`, neither of which are representable as `Double`), but the ∞-norm is always equal to either `real` or `imaginary`, so it is guaranteed to be representable.
As an example, consider `z = Complex(big, big)`, where `big` is `Double.greatestFiniteMagnitude`.
The 1-norm and 2-norm of `z` both overflow (the 1-norm would be `2*big`, and the 2-norm would be `sqrt(2)*big`, neither of which are representable as `Double`), but the ∞-norm is always equal to either `real` or `imaginary`, so it is guaranteed to be representable.
Because of this, the ∞-norm is the obvious alternative; it gives the nicest API surface.
- If we consider the magnitude of more exotic types, like operators, the 1-norm and ∞-norm are significantly easier to compute than the 2-norm (O(n) vs. "no closed form expression, but O(n^3) iterative methods"), so it is nice to establish a precedent of `.magnitude` binding one of these cheaper-to-compute norms.
- 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.
+55
View File
@@ -0,0 +1,55 @@
//===--- Scale.swift ------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2021 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
//
//===----------------------------------------------------------------------===//
// Policy: deliberately not using the * and / operators for these at the
// moment, because then there's an ambiguity in expressions like 2*z; is
// that Complex(2) * z or is it RealType(2) * z? This is especially
// problematic in type inference: suppose we have:
//
// let a: RealType = 1
// let b = 2*a
//
// what is the type of b? If we don't have a type context, it's ambiguous.
// If we have a Complex type context, then b will be inferred to have type
// Complex! Obviously, that doesn't help anyone.
//
// TODO: figure out if there's some way to avoid these surprising results
// and turn these into operators if/when we have it.
// (https://github.com/apple/swift-numerics/issues/12)
extension Complex {
/// `self` scaled by `a`.
@usableFromInline @_transparent
internal func multiplied(by a: RealType) -> Complex {
// This can be viewed in two different ways, which are mathematically
// equivalent: either we are computing `self * Complex(a)` (i.e.
// converting `a` to be a complex value, and then using the complex
// multiplication) or we are using the scalar product of the vector
// space structure: `Complex(a*real, a*imaginary)`.
//
// Although these two interpretations are _mathematically_ equivalent,
// they will generate different representations of the point at
// infinity in general. For example, suppose `self` is represented by
// `(infinity, 0)`. Then `self * Complex(1)` would evaluate as
// `(1*infinity - 0*0, 0*infinity + 1*0) = (infinity, nan)`, but
// the vector space interpretation produces `(infinity, 0)`. This does
// not matter much, because these are two representations of the same
// semantic value, but note that one requires four multiplies and two
// additions, while the one we use requires only two real multiplications.
Complex(x*a, y*a)
}
/// `self` unscaled by `a`.
@usableFromInline @_transparent
internal func divided(by a: RealType) -> Complex {
// See implementation notes for `multiplied` above.
Complex(x/a, y/a)
}
}
+21
View File
@@ -0,0 +1,21 @@
#[[
This source file is part of the Swift Numerics open source project
Copyright (c) 2019-2021 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(IntegerUtilities
DivideWithRounding.swift
GCD.swift
Rotate.swift
RoundingRule.swift
SaturatingArithmetic.swift
ShiftWithRounding.swift)
set_target_properties(IntegerUtilities PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
_install_target(IntegerUtilities)
set_property(GLOBAL APPEND PROPERTY SWIFT_NUMERICS_EXPORTS IntegerUtilities)
@@ -0,0 +1,315 @@
//===--- DivideWithRounding.swift -----------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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 BinaryInteger {
/// `self` divided by `other`, rounding the result according to `rule`.
///
/// The default rounding rule is `.down`, which _is not the same_ as the
/// behavior of the `/` operator from the Swift standard library, but is
/// chosen because it generally produces a more useful remainder. In
/// particular, when `b` is positive, the remainder is always positive.
/// To match the behavior of `/`, use the `.towardZero` rounding mode.
///
/// Note that the remainder of division is not always representable in an
/// unsigned type if a rounding rule other than `.down`, `.towardZero`, or
/// `.requireExact` is used. For example:
///
/// let a: UInt = 5
/// let b: UInt = 3
/// let q = a.divided(by: b, rounding: .up) // 2
/// let r = a - b*q // 5 - 3*2 overflows UInt.
///
/// For this reason, there is no `remainder(dividingBy:rounding:)`
/// operation defined on `BinaryInteger`. Signed integers do not have
/// this problem, so it is defined on the `SignedInteger` protocol
/// instead, as is an overload of `divided(by:rounding:)` that returns
/// both quotient and remainder.
@inlinable
public func divided(
by other: Self,
rounding rule: RoundingRule = .down
) -> Self {
// "Normal divsion" rounds toward zero, so we get self = q*other + r
// with |r| < |other| and r matching the sign of self.
let q = self / other
let r = self - q*other
// In every rounding mode, the result is the same when the result is
// exact.
if r == 0 { return q }
// From this point forward, we can assume r != 0.
//
// To get the quotient and remainder rounded as directed by rule, we
// will adjust q and r. Note that the quotient is either q-1 or q (if
// q is negative) or q or q+1 (if q is positive), because q has been
// rounded toward zero.
//
// If we subtract 1 from q, we add other to r to compensate, because:
//
// self = q*other + r
// = (q-1)*other + (r+other)
//
// Similarly, if we add 1 to q, we subtract other from r to compensate.
switch rule {
case .down:
// For rounding down, we want to have r match the sign of other
// rather than self; this means that if the signs of r and other
// disagree, we have to adjust q downward and r to match.
if other.signum() != r.signum() { return q-1 }
return q
case .up:
// For rounding up, we want to have r have the opposite sign of
// other; if not, we adjust q upward and r to match.
if other.signum() == r.signum() { return q+1 }
return q
case .towardZero:
// This is exactly what the `/` operator did for us.
return q
case .toOdd:
// If q is already odd, we're done.
if q._lowWord & 1 == 1 { return q }
// Otherwise, q is even but inexact; it was originally rounded toward
// zero, so rounding away from zero instead will make it odd.
fallthrough
case .awayFromZero:
// To round away from zero, we apply the adjustments for both down
// and up.
if other.signum() != r.signum() { return q-1 }
return q+1
case .toNearestOrAwayFromZero:
// For round to nearest or away, the condition we want to satisfy is
// |r| <= |other/2|, with sign(q) != sign(r) when equality holds.
if r.magnitude < other.magnitude.shifted(rightBy: 1, rounding: .up) {
return q
}
// The (q,r) we have does not satisfy the to nearest or away condition;
// round away from zero to choose the other representative of (q, r).
if other.signum() != r.signum() { return q-1 }
return q+1
case .toNearestOrEven:
// For round to nearest or away, the condition we want to satisfy is
// |r| <= |other/2|, with q even when equality holds.
if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||
2*r.magnitude == other.magnitude && q._lowWord & 1 == 1 {
if (other > 0) != (r > 0) { return q-1 }
return q+1
}
return q
case .stochastically:
var qhi: UInt64
var rhi: UInt64
if other.magnitude <= UInt64.max {
qhi = UInt64(other.magnitude)
rhi = UInt64(r.magnitude)
} else {
// TODO: this is untested currently.
let qmag = other.magnitude
let shift = qmag._msb - 1
qhi = UInt64(truncatingIfNeeded: qmag >> shift)
rhi = UInt64(truncatingIfNeeded: r.magnitude >> shift)
}
let (sum, car) = rhi.addingReportingOverflow(.random(in: 0 ..< qhi))
if car || sum >= qhi {
if (other > 0) != (r > 0) { return q-1 }
return q+1
}
return q
case .requireExact:
preconditionFailure("Division was not exact.")
}
}
// TODO: make this API and make it possible to implement more efficiently.
// Customization point on new/revised integer protocol? Shouldn't have to
// go through .words.
/// The index of the most-significant set bit.
///
/// - Precondition: self is assumed to be non-zero (should be changed
/// if/when this becomes API).
@usableFromInline
internal var _msb: Int {
// a == 0 is never used for division, because this is called
// on the divisor which cannot be zero as a precondition; if
// this becomes API, the behavior for this case will have to
// be defined.
assert(self != 0)
// Because self is non-zero, mswIndex is guaranteed to exist,
// hence force-unwrap is appropriate.
let mswIndex = words.lastIndex { $0 != 0 }!
let mswBits = UInt.bitWidth * words.distance(from: words.startIndex, to: mswIndex)
return mswBits + (UInt.bitWidth - words[mswIndex].leadingZeroBitCount - 1)
}
}
extension SignedInteger {
/// Divides `self` by `other`, rounding the quotient according to `rule`,
/// and returns the remainder.
///
/// The default rounding rule is `.down`, which _is not the same_ as the
/// behavior of the `%` operator from the Swift standard library, but is
/// chosen because it generally produces a more useful remainder. To
/// match the behavior of `%`, use the `.towardZero` rounding mode.
///
/// - Precondition: `other` cannot be zero.
@inlinable
public func remainder(
dividingBy other: Self,
rounding rule: RoundingRule = .down
) -> Self {
// Produce correct remainder for the .min/-1 case, rather than trapping.
if other == -1 { return 0 }
return self.divided(by: other, rounding: rule).remainder
}
/// Divides `self` by `other`, rounding the quotient according to `rule`,
/// and returns both the quotient and remainder.
///
/// The default rounding rule is `.down`, which _is not the same_ as the
/// behavior of the `/` operator from the Swift standard library, but is
/// chosen because it generally produces a more useful remainder. To
/// match the behavior of `/`, use the `.towardZero` rounding mode.
///
/// Because the default rounding mode does not match Swift's standard
/// library, this function is a disfavored overload of `divided(by:)`
/// instead of using the name `quotientAndRemainder(dividingBy:)`, which
/// would shadow the standard library operation and change the behavior
/// of any existing use sites. To call this method, you must explicitly
/// bind the result to a tuple:
///
/// // This calls BinaryInteger's method, which returns only
/// // the quotient.
/// let result = 5.divided(by: 3, rounding: .up) // 2
///
/// // This calls SignedInteger's method, which returns both
/// // the quotient and remainder.
/// let (q, r) = 5.divided(by: 3, rounding: .up) // (q = 2, r = -1)
@inlinable @inline(__always) @_disfavoredOverload
public func divided(
by other: Self,
rounding rule: RoundingRule = .down
) -> (quotient: Self, remainder: Self) {
// "Normal divsion" rounds toward zero, so we get self = q*other + r
// with |r| < |other| and r matching the sign of self.
let q = self / other
let r = self - q*other
// In every rounding mode, the result is the same when the result is
// exact.
if r == 0 { return (q, r) }
// From this point forward, we can assume r != 0.
//
// To get the quotient and remainder rounded as directed by rule, we
// will adjust q and r. Note that the quotient is either q-1 or q (if
// q is negative) or q or q+1 (if q is positive), because q has been
// rounded toward zero.
//
// If we subtract 1 from q, we add other to r to compensate, because:
//
// self = q*other + r
// = (q-1)*other + (r+other)
//
// Similarly, if we add 1 to q, we subtract other from r to compensate.
switch rule {
case .down:
// For rounding down, we want to have r match the sign of other
// rather than self; this means that if the signs of r and other
// disagree, we have to adjust q downward and r to match.
if other.signum() != r.signum() { return (q-1, r+other) }
return (q, r)
case .up:
// For rounding up, we want to have r have the opposite sign of
// other; if not, we adjust q upward and r to match.
if other.signum() == r.signum() { return (q+1, r-other) }
return (q, r)
case .towardZero:
// This is exactly what the `/` operator did for us.
return (q, r)
case .toOdd:
// If q is already odd, we're done.
if q._lowWord & 1 == 1 { return (q, r) }
// Otherwise, q is even but inexact; it was originally rounded toward
// zero, so rounding away from zero instead will make it odd.
fallthrough
case .awayFromZero:
// To round away from zero, we apply the adjustments for both down
// and up.
if other.signum() != r.signum() { return (q-1, r+other) }
return (q+1, r-other)
case .toNearestOrAwayFromZero:
// For round to nearest or away, the condition we want to satisfy is
// |r| <= |other/2|, with sign(q) != sign(r) when equality holds.
if r.magnitude < other.magnitude.shifted(rightBy: 1, rounding: .up) {
return (q, r)
}
// The (q,r) we have does not satisfy the to nearest or away condition;
// round away from zero to choose the other representative of (q, r).
if other.signum() != r.signum() { return (q-1, r+other) }
return (q+1, r-other)
case .toNearestOrEven:
// For round to nearest or away, the condition we want to satisfy is
// |r| <= |other/2|, with q even when equality holds.
if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||
2*r.magnitude == other.magnitude && q._lowWord & 1 == 1 {
if (other > 0) != (r > 0) { return (q-1, r+other) }
return (q+1, r-other)
}
return (q, r)
case .stochastically:
var qhi: UInt64
var rhi: UInt64
if other.magnitude <= UInt64.max {
qhi = UInt64(other.magnitude)
rhi = UInt64(r.magnitude)
} else {
// TODO: this is untested currently.
let qmag = other.magnitude
let shift = qmag._msb - 1
qhi = UInt64(truncatingIfNeeded: qmag >> shift)
rhi = UInt64(truncatingIfNeeded: r.magnitude >> shift)
}
let (sum, car) = rhi.addingReportingOverflow(.random(in: 0 ..< qhi))
if car || sum >= qhi {
if (other > 0) != (r > 0) { return (q-1, r+other) }
return (q+1, r-other)
}
return (q, r)
case .requireExact:
preconditionFailure("Division was not exact.")
}
}
}
/// `a = quotient*b + remainder`, with `remainder >= 0`.
///
/// When `a` and `b` are both positive, `quotient` is `a/b` and `remainder`
/// is `a%b`.
///
/// Rounding the quotient so that the remainder is non-negative is called
/// "Euclidean division". This is not a _rounding rule_, as `quotient`
/// cannot be determined from the unrounded value `a/b`; we need to also
/// know the sign of `a` or `b` or `r` to know which way to round. Because
/// of this, is not present in the `RoundingRule` enum and uses a separate
/// API from the other division operations.
///
/// - Parameters:
/// - a: The dividend
/// - b: The divisor
///
/// - Precondition: `b` must be non-zero, and the quotient `a/b` must be
/// representable. In particular, if `T` is a signed fixed-width integer
/// type, then `euclideanDivision(T.min, -1)` will trap, because `-T.min`
/// is not representable.
///
/// - Returns: `(quotient, remainder)`, with `0 <= remainder < b.magnitude`.
func euclideanDivision<T>(_ a: T, _ b: T) -> (quotient: T, remainder: T)
where T: SignedInteger
{
a.divided(by: b, rounding: a >= 0 ? .towardZero : .awayFromZero)
}
+53
View File
@@ -0,0 +1,53 @@
//===--- GCD.swift --------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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
//
//===----------------------------------------------------------------------===//
/// The greatest common divisor of `a` and `b`.
///
/// If both inputs are zero, the result is zero. If one input is zero, the
/// result is the absolute value of the other input.
///
/// The result must be representable within its type. In particular, the gcd
/// of a signed, fixed-width integer type's minimum with itself (or zero)
/// cannot be represented, and results in a trap.
///
/// gcd(Int.min, Int.min) // Overflow error
/// gcd(Int.min, 0) // Overflow error
///
/// [wiki]: https://en.wikipedia.org/wiki/Greatest_common_divisor
@inlinable
public func gcd<T: BinaryInteger>(_ a: T, _ b: T) -> T {
var x = a.magnitude
var y = b.magnitude
if x == 0 { return T(y) }
if y == 0 { return T(x) }
let xtz = x.trailingZeroBitCount
let ytz = y.trailingZeroBitCount
y >>= ytz
// The binary GCD algorithm
//
// After the right-shift in the loop, both x and y are odd. Each pass removes
// at least one low-order bit from the larger of the two, so the number of
// iterations is bounded by the sum of the bit-widths of the inputs.
//
// A tighter bound is the maximum bit-width of the inputs, which is achieved
// by odd numbers that sum to a power of 2, though the proof is more involved.
repeat {
x >>= x.trailingZeroBitCount
if x < y { swap(&x, &y) }
x -= y
} while x != 0
return T(y << min(xtz, ytz))
}
+68
View File
@@ -0,0 +1,68 @@
# Integer Utilities
_Note: This module is only present on `main`, and has not yet been stabilized and released in a tag._
## Utilities defined for `BinaryInteger`
The following API are defined for all integer types:
- The `gcd(_:_:)` free function implements the _Greatest Common Divisor_ operation.
- The `shifted(rightBy:rounding:)` method implements _bitwise shift with rounding_.
- The `divided(by:rounding:)` method implements division with specified rounding.
(See also `SignedInteger.divided(by:rounding:)`, `remainder(dividingBy:rounding:)`, and `euclideanDivision(_:_:)` below).
## Utilities defined for `SignedInteger`
The following API are defined for signed integer types:
- The `divided(by:rounding:)` method implementing division with specified rounding, returning both quotient and remainder.
This requires a signed type because the remainder is not generally representable for unsigned types.
This is a disfavored overload; by default, you will get only the quotient as the result:
```
let p = 5.divided(by: 3, rounding: .up) // p = 2
let (q, r) = 5.divided(by: 3, rounding: .up) // q = 2, r = -1
```
- The `remainder(dividingBy:rounding:)` method implementing the remainder operation; the `rounding` argument describes how to round the _quotient_, which is not returned.
(The remainder is always exact, and hence is not rounded).
- The `euclideanDivision(_:_:)` free function implements _Euclidean division_.
In this operation, the remainder is chosen to always be non-negative.
This does not correspond to any rounding rule on the quotient, which is why it uses a distinct API.
## Utilities defined for `FixedWidthInteger`
- The `rotated(right:)` and `rotated(left:)` methods implement _bitwise rotation_ for signed and unsigned integer types.
The count parameter may be any `BinaryInteger` type.
### [Saturating Arithmetic][saturating]
The following saturating operations are defined as methods on `FixedWidthInteger`:
- `addingWithSaturation(_:)`
- `subtractingWithSaturation(_:)`
- `negatedWithSaturation(_:)`
- `multipliedWithSaturation(by:)`
- `shiftedWithSaturation(leftBy:rounding:)`
These implement _saturating arithmetic_.
They are an alternative to the usual `+`, `-`, and `*` operators, which trap if the result cannot be represented in the argument type, and `&+`, `&-`, `&*`, and `<<`, which wrap out-of-range results modulo 2ⁿ for some n.
Instead these methods clamp the result to the representable range of the type:
```
let x: Int8 = 84
let y: Int8 = 100
let a = x + y // traps due to overflow
let b = x &+ y // wraps to -72
let c = x.addingWithSaturation(y) // saturates to 127
```
If you are using saturating arithmetic, you may also want to perform saturating conversions between integer types; this functionality is provided by the standard library via the [`init(clamping:)` API][clamping].
## Types
The `RoundingRule` enum is used with shift, division, and round operations to specify how to round their results to a representable value.
[saturating]: https://en.wikipedia.org/wiki/Saturation_arithmetic
[clamping]: https://developer.apple.com/documentation/swift/binaryinteger/init(clamping:)
+43
View File
@@ -0,0 +1,43 @@
//===--- Rotate.swift -----------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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 FixedWidthInteger {
@_transparent @usableFromInline
internal func rotateImplementation(right count: Int) -> Self {
// We don't have an unsigned right shift operation for signed values, so
// we need to convert to an unsigned type. The only unsigned type that's
// guaranteed to be able to represent the bit pattern of any Self value
// is Magnitude. It would be possible to have Magnitude be _wider_ than
// Self, but that's OK as long as we're careful to complement the shift
// count using Self.bitWidth and not Magnitude.bitWidth or zero.
let bitPattern = Magnitude(truncatingIfNeeded: self)
let countComplement = Self.bitWidth &- count
return Self(truncatingIfNeeded:
bitPattern &>> count | bitPattern &<< countComplement
)
}
/// `self` rotated bitwise right by `count` bits.
///
/// Equivalent to `rotated(left: 0 &- count)`.
@inlinable
public func rotated<Count: BinaryInteger>(right count: Count) -> Self {
rotateImplementation(right: Int(truncatingIfNeeded: count))
}
/// `self` rotated bitwise left by `count` bits.
///
/// Equivalent to `rotated(right: 0 &- count)`.
@inlinable
public func rotated<Count: BinaryInteger>(left count: Count) -> Self {
rotateImplementation(right: 0 &- Int(truncatingIfNeeded: count))
}
}
+187
View File
@@ -0,0 +1,187 @@
//===--- RoundingRule.swift -----------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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 rule that defines how to select one of the two representable results
/// closest to a given value.
///
/// [Wikipedia](https://en.wikipedia.org/wiki/Rounding#Rounding_to_integer)
/// provides a good overview of different rounding rules.
///
/// Examples using rounding to integer to illustrate the various options:
/// ```
/// value | down | up | towardZero | awayFromZero |
/// =======+==============+==============+==============+==============+
/// 1.5 | 1 | 2 | 1 | 2 |
/// -------+--------------+--------------+--------------+--------------+
/// -0.5 | -1 | 0 | 0 | -1 |
/// -------+--------------+--------------+--------------+--------------+
/// 0.3 | 0 | 1 | 0 | 1 |
/// -------+--------------+--------------+--------------+--------------+
/// 2 | 2 | 2 | 2 | 2 |
/// -------+--------------+--------------+--------------+--------------+
///
/// value | toOdd | toNearestOrAwayFromZero | toNearestOrEven |
/// =======+==============+=========================+==================+
/// 1.5 | 1 | 2 | 2 |
/// -------+--------------+-------------------------+------------------+
/// -0.5 | -1 | -1 | 0 |
/// -------+--------------+-------------------------+------------------+
/// 0.3 | 1 | 0 | 0 |
/// -------+--------------+-------------------------+------------------+
/// 2 | 2 | 2 | 2 |
/// -------+--------------+-------------------------+------------------+
///
/// value | stochastically | requireExact |
/// =======+=======================+================+
/// 1.5 | 50% 1, 50% 2 | trap |
/// -------+-----------------------+----------------+
/// -0.5 | 50% -1, 50% 0 | trap |
/// -------+-----------------------+----------------+
/// 0.3 | 70% 0, 30% 1 | trap |
/// -------+-----------------------+----------------+
/// 2 | 2 | 2 |
/// -------+-----------------------+----------------+
/// ```
public enum RoundingRule {
/// Produces the closest representable value that is less than or equal
/// to the value being rounded.
///
/// This is the default rounding mode for integer shifts, including the
/// shift operators defined in the standard library.
///
/// Examples:
/// - `(-4).divided(by: 3, rounding: .down)` is `-2`, because –2 is the
/// largest integer less than –4/3 = –1.3̅
/// - `5.shifted(rightBy: 1, rounding: .down)` is `2`, because 2 is the
/// largest integer less than 5/2 = 2.5.
case down
/// Produces the closest representable value that is greater than or equal
/// to the value being rounded.
///
/// Examples:
/// - `(-4).divided(by: 3, rounding: .up)` is `-1`, because –1 is the
/// smallest integer greater than –4/3 = –1.3̅
/// - `5.shifted(rightBy: 1, rounding: .up)` is `3`, because 3 is the
/// smallest integer greater than 5/2 = 2.5.
case up
/// Produces the closest representable value whose magnitude is less than
/// or equal to that of the value being rounded.
///
/// Examples:
/// - `(-4).divided(by: 3, rounding: .towardZero)` is `-1`, because –1
/// is the closest integer to –4/3 = –1.3̅ with smaller magnitude.
/// - `5.shifted(rightBy: 1, rounding: .towardZero)` is `2`, because 2
/// is the closest integer to 5/2 = 2.5 with smaller magnitude.
case towardZero
/// Produces the closest representable value whose magnitude is greater
/// than or equal to that of the value being rounded.
///
/// Examples:
/// - `(-4).divided(by: 3, rounding: .awayFromZero)` is `-2`, because –2
/// is the closest integer to –4/3 = –1.3̅ with greater magnitude.
/// - `5.shifted(rightBy: 1, rounding: .awayFromZero)` is `3`, because 3
/// is the closest integer to 5/2 = 2.5 with greater magnitude.
case awayFromZero
/// If the value being rounded is representable, that value is returned.
/// Otherwise, whichever of the two closest representable values has its
/// least significant bit set is returned.
///
/// This is also called _sticky rounding_, and it is useful as an
/// implementation detail because it has the property that if we do
/// rounding in two steps, first to intermediate precision p₁ with .toOdd,
/// then to the final precision p₂ with any other rounding mode, the result
/// we get is the same as if we rounded directly to p₂ in the desired mode
/// so long as p₂ + 1 < p₁. Other rounding modes do not have this property,
/// and admit _double roundings_ when interoperating with some modes.
///
/// Examples:
/// - `(-4).divided(by: 3, rounding: .toOdd)` is `-1`, because –4/3 = –1.3̅
/// is not an exact integer, and –1 is the closest odd integer.
/// - `4.shifted(rightBy: 1, rounding: .toOdd)` is `2`,
/// even though 2 is even, because 4/2 is exactly 2 and no rounding occurs.
case toOdd
/// Produces the representable value that is closest to the value being
/// rounded. If two values are equally close, the one that has greater
/// magnitude is returned.
///
/// Examples:
/// - `(-4).divided(by: 3, rounding: .toNearestOrAwayFromZero)`
/// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2.
///
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrAwayFromZero)` is `3`,
/// because 5/2 = 2.5 is equally close to 2 and 3, and 3 is further away
/// from zero.
case toNearestOrAwayFromZero
/// Produces the representable value that is closest to the value being
/// rounded. If two values are equally close, the one whose least
/// significant bit is not set is returned.
///
/// Examples:
/// - `(-4).divided(by: 3, rounding: .toNearestOrEven)`
/// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2.
///
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrEven)` is `2`,
/// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is even.
case toNearestOrEven
/// Adds a uniform random value from [0, d) to the value being rounded,
/// where d is the distance between the two closest representable values,
/// then rounds the sum downwards.
///
/// Unlike all the other rounding modes, this mode is _not deterministic_;
/// repeated calls to rounding operations with this mode will generally
/// produce different results. There is a tradeoff implicit in using this
/// mode: you can sacrifice _reproducible_ results to get _more accurate_
/// results in aggregate. For a contrived but illustrative example, consider
/// the following:
/// ```
/// let data = Array(repeating: 1, count: 100)
/// let result = data.reduce(0) {
/// $0 + $1.divided(by: 3, rounding: rule)
/// }
/// ```
/// because 1/3 is always the same value between 0 and 1, any
/// deterministic rounding rule must produce either 0 or 100 for
/// this computation. But rounding `stochastically` will
/// produce a value close to 33. The _error_ of the computation
/// is smaller, but the result will now change between runs of the
/// program.
///
/// For this simple case a better solution would be to add the
/// values first, and then divide. This gives a result that is both
/// reproducible _and_ accurate:
/// ```
/// let result = data.reduce(0, +)/3
/// ```
/// but this isn't always possible in more sophisticated scenarios,
/// and in those cases this rounding rule may be useful.
///
/// Examples:
/// - `(-4).divided(by: 3, rounding: .stochastically)`
/// will be –1 with probability 2/3 and –2 with probability 1/3.
/// - `5.shifted(rightBy: 1, rounding: .stochastically)`
/// will be 2 with probability 1/2 and 3 with probability 1/2.
case stochastically
/// If the value being rounded is representable, that value is returned.
/// Otherwise, a precondition failure occurs.
///
/// Examples:
/// - `(-4).divided(by: 3, rounding: .requireExact)` will trap,
/// because –4/3 = –1.3̅ is not an integer.
case requireExact
}
@@ -0,0 +1,167 @@
//===--- SaturatingArithmetic.swift ---------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2023 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 FixedWidthInteger {
/// `~0` (all-ones) if this value is negative, otherwise `0`.
///
/// Note that if `Self` is unsigned, this always returns `0`,
/// but it is useful for writing algorithms that are generic over
/// signed and unsigned integers.
@inline(__always) @usableFromInline
var signbit: Self {
return self < .zero ? ~.zero : .zero
}
/// Saturating integer addition
///
/// `self + other` clamped to the representable range of the type. e.g.:
/// ```
/// let a: Int8 = 84
/// let b: Int8 = 100
/// // 84 + 100 = 184 is not representable as
/// // Int8, so `c` is clamped to Int8.max (127).
/// let c = a.addingWithSaturation(b)
/// ```
///
/// Anytime the "normal addition" `self + other` does not trap,
/// `addingWithSaturation` produces the same result.
@inlinable
public func addingWithSaturation(_ other: Self) -> Self {
let (wrapped, overflow) = addingReportingOverflow(other)
return overflow ? Self.max &- signbit : wrapped
}
/// Saturating integer subtraction
///
/// `self - other` clamped to the representable range of the type. e.g.:
/// ```
/// let a: UInt = 37
/// let b: UInt = 42
/// // 37 - 42 = -5, which is not representable as
/// // UInt, so `c` is clamped to UInt.min (zero).
/// let c = a.subtractingWithSaturation(b)
/// ```
///
/// Note that `a.addingWithSaturation(-b)` is not always equivalent to
/// `a.subtractingWithSaturation(b)`, because `-b` is not representable
/// if `b` is the minimum value of a signed type.
///
/// Anytime the "normal subtraction" `self - other` does not trap,
/// `subtractingWithSaturation` produces the same result.
@inlinable
public func subtractingWithSaturation(_ other: Self) -> Self {
let (wrapped, overflow) = subtractingReportingOverflow(other)
if !overflow { return wrapped }
return Self.isSigned ? Self.max &- signbit : 0
}
/// Saturating integer negation
///
/// For unsigned types, the result is always zero. This is not very
/// interesting, but may occasionally be useful in generic contexts.
/// For signed types, the result is `-self` unless `self` is `.min`,
/// in which case the result is `.max`.
@inlinable
public func negatedWithSaturation() -> Self {
Self.zero.subtractingWithSaturation(self)
}
/// Saturating integer multiplication
///
/// `self * other` clamped to the representable range of the type. e.g.:
/// ```
/// let a: Int8 = -16
/// let b: Int8 = -8
/// // -16 * -8 = 128 is not representable as
/// // Int8, so `c` is clamped to Int8.max (127).
/// let c = a.multipliedWithSaturation(by: b)
/// ```
///
/// Anytime the "normal multiplication" `self * other` does not trap,
/// `multipliedWithSaturation` produces the same result.
@inlinable
public func multipliedWithSaturation(by other: Self) -> Self {
let (high, low) = multipliedFullWidth(by: other)
let wrapped = Self(truncatingIfNeeded: low)
if high == wrapped.signbit { return wrapped }
return Self.max &- high.signbit
}
/// Bitwise left with rounding and saturation.
///
/// `self` multiplied by the rational number 2^(`count`), saturated to the
/// range `Self.min ... Self.max`, and rounded according to `rule`.
///
/// See `shifted(rightBy:rounding:)` for more discussion of rounding
/// shifts with examples.
///
/// - Parameters:
/// - leftBy count: the number of bits to shift by. If positive, this is a left-shift,
/// and if negative a right shift.
/// - rounding rule: the direction in which to round if `count` is negative.
@inlinable
public func shiftedWithSaturation(
leftBy count: Int,
rounding rule: RoundingRule = .down
) -> Self {
if count == 0 { return self }
// If count is negative, negate it and do a right shift without
// saturation instead, since we already have that implemented.
guard count > 0 else {
return shifted(
rightBy: count.negatedWithSaturation(),
rounding: rule
)
}
let clamped = Self.max &- signbit
guard count < Self.bitWidth else {
// If count is bitWidth or greater, we always overflow
// unless self is zero.
return self == 0 ? 0 : clamped
}
// Now we have 0 < count < bitWidth, so we can use a nice
// straightforward implementation; a shift overflows if
// the complementary shift doesn't match sign-or-zero
// extension. E.g.:
//
// - signed 0b0010_1111 << 2 overflows, because
// 0b0010_1111 >> 5 is 0b0000_0001, which does not
// equal 0b0000_0000
//
// - unsigned 0b0010_1111 << 2 does not overflow,
// because 0b0010_0000 >> 6 is 0b0000_0000, which
// does equal 0b0000_0000.
let valueBits = Self.bitWidth &- (Self.isSigned ? 1 : 0)
let wrapped = self &<< count
let complement = valueBits &- count
return self &>> complement == signbit ? wrapped : clamped
}
/// Bitwise left with rounding and saturation.
///
/// `self` multiplied by the rational number 2^(`count`), saturated to the
/// range `Self.min ... Self.max`, and rounded according to `rule`.
///
/// See `shifted(rightBy:rounding:)` for more discussion of rounding
/// shifts with examples.
///
/// - Parameters:
/// - leftBy count: the number of bits to shift by. If positive, this is a left-shift,
/// and if negative a right shift.
/// - rounding rule: the direction in which to round if `count` is negative.
@_transparent
public func shiftedWithSaturation<Count: BinaryInteger>(
leftBy count: Count,
rounding rule: RoundingRule = .down
) -> Self {
self.shiftedWithSaturation(leftBy: Int(clamping: count), rounding: rule)
}
}
@@ -0,0 +1,197 @@
//===--- ShiftWithRounding.swift ------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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 BinaryInteger {
/// `self` divided by 2^(`count`), rounding the result according to `rule`.
///
/// The default rounding rule is `.down`, which matches the behavior of
/// the `>>` operator from the standard library.
///
/// Some examples of different rounding rules:
///
/// // 3/2 is 1.5, which rounds (down by default) to 1.
/// 3.shifted(rightBy: 1)
///
/// // 1.5 rounds up to 2.
/// 3.shifted(rightBy: 1, rounding: .up)
///
/// // The two closest values are 1 and 2, 1 is returned because it
/// // is odd.
/// 3.shifted(rightBy: 1, rounding: .toOdd)
///
/// // 7/4 = 1.75, so the result is 1 with probability 1/4, or 2
/// // with probability 3/4.
/// 7.shifted(rightBy: 2, rounding: .stochastically)
///
/// // 4/4 is exactly 1, so this does not trap.
/// 4.shifted(rightBy: 2, rounding: .requireExact)
///
/// // 5/2 is 2.5, which is not an integer, so this traps.
/// 5.shifted(rightBy: 1, rounding: .requireExact)
///
/// When `Self(1) << count` is positive, the following are equivalent:
///
/// a.shifted(rightBy: count, rounding: rule)
/// a.divided(by: 1 << count, rounding: rule)
@inlinable
public func shifted(
rightBy count: Int,
rounding rule: RoundingRule = .down
) -> Self {
// Easiest case: count is zero or negative, so shift is always exact;
// delegate to the normal >> operator.
if count <= 0 { return self >> count }
if count >= bitWidth {
// Note: what follows would cause an infinite loop if bitWidth <= 1.
// This will essentially never happen, but in the highly unlikely event
// that we encounter such a case, we promote to Int8, do the shift, and
// then convert back to the appropriate result type.
if bitWidth <= 1 {
return Self(Int8(self).shifted(rightBy: count, rounding: rule))
}
// That pathological case taken care of, we can now handle over-wide
// shifts by first shifting all but bitWidth - 1 bits with sticky
// rounding, and then shifting the remaining bitWidth - 1 bits with
// the desired rounding mode.
let count = count - (bitWidth - 1)
let floor = self >> count
let lost = self - (floor << count)
let sticky = floor | (lost == 0 ? 0 : 1)
return sticky.shifted(rightBy: bitWidth - 1, rounding: rule)
}
// Now we are in the happy case: 0 < count < bitWidth, which makes all
// the math to handle rounding simpler.
//
// TODO: If we were really, really careful about overflow, some of these
// could be made simpler. E.g. mathematically round up is implemented here
// via:
//
// floor = self >> count
// mask = 1 << count - 1
// lost = self & mask
// return floor + (lost == 0 ? 0 : 1)
//
// _if_ we didn't have to worry about intermediate overflow (either because
// self is bounded away from .max or because we don't have a fixed-width
// type), then we could use the following instead:
//
// mask = 1 << count - 1
// return (self + mask) >> count
//
// However, self + mask can overflow, e.g. if we're shifting .max by 1:
//
// mask = 1 << 1 - 1 = 1
// self + mask = .max + 1 // uh-oh
//
// This cannot occur for arbitrary-precision numbers, so we could use
// the simpler expressions for those (but those are precisely the cases
// where performance of rounding does not matter much, because shifts
// get swamped by even basic arithmetic). More interesting, we could
// promote fixed-width numbers to a wider type, preventing this
// intermediate overflow and allowing us to use the simpler expressions
// much of the time. We could also explicitly _detect_ the overflow if
// it happens and patch up the result, though this is a little bit tricky
// because addingReportingOverflow and friends do not exist on
// BinaryInteger. Hence, this is a TODO for the future.
let mask = Magnitude(1) << count - 1
let lost = Magnitude(truncatingIfNeeded: self) & mask
let floor = self >> count
let ceiling = floor + (lost == 0 ? 0 : 1)
switch rule {
case .down:
return floor
case .up:
return ceiling
case .towardZero:
return self > 0 ? floor : ceiling
case .awayFromZero:
return self < 0 ? floor : ceiling
case .toOdd:
return floor | (lost == 0 ? 0 : 1)
case .toNearestOrAwayFromZero:
let round = mask >> 1 + (self > 0 ? 1 : 0)
return floor + Self((round + lost) >> count)
case .toNearestOrEven:
let round = mask >> 1 + Magnitude(floor & 1)
return floor + Self((round + lost) >> count)
case .stochastically:
// TODO: it's unfortunate that we can't specify a custom random source
// for the stochastically rounding rule, but I don't see a nice way to
// have that share the API with the other rounding rules, because we'd
// then have to take the RNG in-out. The same problem applies to
// rounding with dithering. We should consider adding a stateful
// rounding API down the road to support those use cases.
//
// In theory, u01 should be Self.random(in: 0 ..< onesBit), but the
// random(in:) method does not exist on BinaryInteger. This is
// (arguably) good, though, because there's actually no reason to
// generate large amounts of randomness just to implement stochastic
// rounding; 32b suffices for almost all purposes, and 64b is more
// than enough.
var g = SystemRandomNumberGenerator()
let u01 = g.next()
if count < 64 {
// count is small, so mask and lost are representable as both
// UInt64 and Self, regardless of what type Self actually is.
return floor + Self(((u01 & UInt64(mask)) + UInt64(lost)) >> count)
} else {
// count is large, so lost may not be representable as UInt64; pre-
// shift by count-64 to isolate the high 64b of the fraction, then
// add u01 and carry-out to round.
let highWord = UInt64(truncatingIfNeeded: lost >> (Int(count) - 64))
let (_, carry) = highWord.addingReportingOverflow(u01)
return floor + (carry ? 1 : 0)
}
case .requireExact:
precondition(lost == 0, "shift was not exact.")
return floor
}
}
/// `self` divided by 2^(`count`), rounding the result according to `rule`.
///
/// The default rounding rule is `.down`, which matches the behavior of
/// the `>>` operator from the standard library.
///
/// Some examples of different rounding rules:
///
/// // 3/2 is 1.5, which rounds (down by default) to 1.
/// 3.shifted(rightBy: 1)
///
/// // 1.5 rounds up to 2.
/// 3.shifted(rightBy: 1, rounding: .up)
///
/// // The two closest values are 1 and 2, 1 is returned because it
/// // is odd.
/// 3.shifted(rightBy: 1, rounding: .toOdd)
///
/// // 7/4 = 1.75, so the result is 1 with probability 1/4, or 2
/// // with probability 3/4.
/// 7.shifted(rightBy: 2, rounding: .stochastically)
///
/// // 4/4 is exactly 1, so this does not trap.
/// 4.shifted(rightBy: 2, rounding: .requireExact)
///
/// // 5/2 is 2.5, which is not an integer, so this traps.
/// 5.shifted(rightBy: 1, rounding: .requireExact)
///
/// When `Self(1) << count` is positive, the following are equivalent:
///
/// a.shifted(rightBy: count, rounding: rule)
/// a.divided(by: 1 << count, rounding: rule)
@_transparent
public func shifted<Count: BinaryInteger>(
rightBy count: Count,
rounding rule: RoundingRule = .down
) -> Self {
self.shifted(rightBy: Int(clamping: count), rounding: rule)
}
}
+29
View File
@@ -0,0 +1,29 @@
#[[
This source file is part of the Swift Numerics open source project
Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
#]]
add_library(Numerics
Numerics.swift)
set_target_properties(Numerics PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
# NOTE: generate the force load symbol to ensure that the import library is
# generated on Windows for autolinking.
target_compile_options(Numerics PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:-autolink-force-load>
# SR-12254: workaround for the swift compiler not properly tracking the force
# load symbol when validating the TBD
-Xfrontend -validate-tbd-against-ir=none)
target_link_libraries(Numerics PUBLIC
BigIntModule
ComplexModule
IntegerUtilities
RealModule)
_install_target(Numerics)
set_property(GLOBAL APPEND PROPERTY SWIFT_NUMERICS_EXPORTS Numerics)
+4 -2
View File
@@ -10,5 +10,7 @@
//===----------------------------------------------------------------------===//
// A module that re-exports the complete Swift Numerics public API.
@_exported import Real
@_exported import Complex
@_exported import BigIntModule
@_exported import ComplexModule
@_exported import IntegerUtilities
@_exported import RealModule
-82
View File
@@ -1,82 +0,0 @@
//===--- Real.swift -------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A type that models the real numbers.
///
/// Types conforming to this protocol provide the arithmetic and utility operations defined by
/// the `FloatingPoint` protocol, and provide all of the math functions defined by the
/// `ElementaryFunctions` and `RealFunctions` protocols. This protocol does not
/// add any additional conformances itself, but is very useful as a protocol against which to
/// write generic code. For example, we can naturally write a generic version of the a sigmoid
/// function:
/// ```
/// func sigmoid<T: Real>(_ x: T) -> T {
/// return 1/(1 + .exp(-x))
/// }
/// ```
/// See Also:
/// -
/// - `ElementaryFunctions`
/// - `RealFunctions`
public protocol Real: FloatingPoint, RealFunctions {
}
// While `Real` does not provide any additional customization points,
// it does allow us to default the implementation of a few operations,
// and also provides `signGamma`.
extension Real {
// Most math libraries do not provide exp10, so we need a default implementation.
@_transparent
public static func exp10(_ x: Self) -> Self {
return pow(10, x)
}
#if !os(Windows)
public static func signGamma(_ x: Self) -> FloatingPointSign {
// Gamma is strictly positive for x >= 0.
if x >= 0 { return .plus }
// For negative x, we arbitrarily choose to assign a sign of .plus to the
// poles.
let trunc = x.rounded(.towardZero)
if x == trunc { return .plus }
// Otherwise, signGamma is .minus if the integral part of x is even.
return trunc.isEven ? .minus : .plus
}
// Determines if this value is even, assuming that it is an integer.
@inline(__always)
private var isEven: Bool {
if Self.radix == 2 {
// For binary types, we can just check if x/2 is an integer. This works
// because x/2 is always computed exactly.
let half = self/2
return half == half.rounded(.towardZero)
} else {
// For decimal types, it's not quite that simple, because x/2 is not
// necessarily computed exactly. As an example, suppose that we had a
// decimal type with a one digit significand, and self = 7. Then self/2
// would round to 4, and we would (wrongly) conclude that it was an
// integer, and hence that self was even.
//
// Instead, for decimal types, we check if 2*trunc(self/2) == self,
// using an FMA; this is always correct; this approach works for any
// radix, but the previous method is more efficient for radix == 2.
let half = self/2
return self.addingProduct(-2, half.rounded(.towardZero)) == 0
}
}
#endif
@_transparent
public static func sqrt(_ x: Self) -> Self {
return x.squareRoot()
}
}
-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
+131
View File
@@ -0,0 +1,131 @@
//===--- 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 distributive 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` and `AdditiveArithmetic`.
///
/// [field]: https://en.wikipedia.org/wiki/Field_(mathematics)
public protocol AlgebraicField: SignedNumeric {
/// Replaces a with the (approximate) quotient `a/b`.
static func /=(a: inout Self, b: Self)
/// The (approximate) quotient `a/b`.
static func /(a: Self, b: Self) -> Self
/// The (approximate) reciprocal (multiplicative inverse) of this number,
/// if it is representable.
///
/// If reciprocal is non-nil, you can replace division by self with
/// multiplication by reciprocal and either get exact the same result
/// (for finite fields) or approximately the same result up to a typical
/// rounding error (for floating-point formats).
///
/// If self is zero and the type has no representation for infinity (as
/// in a typical finite field implementation), or if a reciprocal would
/// overflow or underflow such that it cannot be accurately represented,
/// the result is nil.
///
/// Note that `.zero.reciprocal`, somewhat surprisingly, is *not* nil
/// for `Real` or `Complex` types, because these types have an
/// `.infinity` value that acts as the reciprocal of `.zero`.
///
/// If `b.reciprocal` is non-nil, you may be able to replace division by `b`
/// with multiplication by this value. It is not advantageous to do this
/// for an isolated division unless it is a compile-time constant visible
/// to the compiler, but if you are dividing many values by a single
/// denominator, this will often be a significant performance win.
///
/// Note that this will slightly perturb results for fields with approximate
/// arithmetic, such as real or complex types--using a normal division
/// is generally more accurate--but no catastrophic loss of accuracy will
/// result. For fields with exact arithmetic, the results are necessarily
/// identical.
///
/// A typical use case looks something like this:
/// ```
/// func divide<T: AlgebraicField>(data: [T], by divisor: T) -> [T] {
/// // If divisor is well-scaled, multiply by reciprocal.
/// if let recip = divisor.reciprocal {
/// return data.map { $0 * recip }
/// }
/// // Fallback on using division.
/// return data.map { $0 / divisor }
/// }
/// ```
var reciprocal: Self? { get }
/// a + b, with the optimizer licensed to reassociate and form FMAs.
static func _relaxedAdd(_ a: Self, _ b: Self) -> Self
/// a * b, with the optimizer licensed to reassociate and form FMAs.
static func _relaxedMul(_ a: Self, _ b: Self) -> Self
}
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.
@_transparent
public var reciprocal: Self? {
return nil
}
// It's always OK to simply fall back on normal arithmetic, and for any
// field with exact arithmetic, this is the correct definition.
@_transparent
public static func _relaxedAdd(_ a: Self, _ b: Self) -> Self {
a + b
}
// It's always OK to simply fall back on normal arithmetic, and for any
// field with exact arithmetic, this is the correct definition.
@_transparent
public static func _relaxedMul(_ a: Self, _ b: Self) -> Self {
a * b
}
}
@@ -0,0 +1,253 @@
//===--- ApproximateEquality.swift ----------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Numeric where Magnitude: FloatingPoint {
/// Test if `self` and `other` are approximately equal.
///
/// `true` if `self` and `other` are equal, or if they are finite and
/// ```
/// norm(self - other) <= relativeTolerance * scale
/// ```
/// where `scale` is
/// ```
/// max(norm(self), norm(other), .leastNormalMagnitude)
/// ```
///
/// The default value of `relativeTolerance` is `.ulpOfOne.squareRoot()`,
/// which corresponds to expecting "about half the digits" in the computed
/// results to be good. This is the usual guidance in numerical analysis,
/// if you don't know anything about the computation being performed, but
/// is not suitable for all use cases.
///
/// Mathematical Properties:
///
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _reflexive_ for
/// non-exceptional values (such as NaN).
///
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _symmetric_.
///
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is __not__
/// _transitive_. Because of this, approximately equality is __not an
/// equivalence relation__, even when restricted to non-exceptional values.
///
/// This means that you must not use approximate equality to implement
/// a conformance to Equatable, as it will violate the invariants of
/// code written against that protocol.
///
/// - For any point `a`, the set of values that compare approximately equal
/// to `a` is _convex_. (Under the assumption that the `.magnitude`
/// property implements a valid norm.)
///
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _scale invariant_,
/// so long as no underflow or overflow has occured, and no exceptional
/// value is produced by the scaling.
///
/// See also `isApproximatelyEqual(to:absoluteTolerance:[relativeTolerance:norm:])`.
///
/// - Parameters:
///
/// - other: The value to which `self` is compared.
///
/// - relativeTolerance: The tolerance to use for the comparison.
/// Defaults to `.ulpOfOne.squareRoot()`.
///
/// This value should be non-negative and less than or equal to 1.
/// This constraint on is only checked in debug builds, because a
/// mathematically well-defined result exists for any tolerance,
/// even one out of range.
///
/// - norm: The [norm] to use for the comparison.
/// Defaults to `\.magnitude`.
///
/// [norm]: https://en.wikipedia.org/wiki/Norm_(mathematics)
@inlinable @inline(__always)
public func isApproximatelyEqual(
to other: Self,
relativeTolerance: Magnitude = Magnitude.ulpOfOne.squareRoot(),
norm: (Self) -> Magnitude = \.magnitude
) -> Bool {
return isApproximatelyEqual(
to: other,
absoluteTolerance: relativeTolerance * Magnitude.leastNormalMagnitude,
relativeTolerance: relativeTolerance,
norm: norm
)
}
/// Test if `self` and `other` are approximately equal with specified tolerances.
///
/// `true` if `self` and `other` are equal, or if they are finite and either
/// ```
/// (self - other).magnitude <= absoluteTolerance
/// ```
/// or
/// ```
/// (self - other).magnitude <= relativeTolerance * scale
/// ```
/// where `scale` is `max(self.magnitude, other.magnitude)`.
///
/// Mathematical Properties:
///
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:)`
/// is _reflexive_ for non-exceptional values (such as NaN).
///
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:)`
/// is _symmetric_.
///
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is __not__
/// _transitive_. Because of this, approximately equality is __not an
/// equivalence relation__, even when restricted to non-exceptional values.
///
/// This means that you must not use approximate equality to implement
/// a conformance to Equatable, as it will violate the invariants of
/// code written against that protocol.
///
/// - For any point `a`, the set of values that compare approximately equal
/// to `a` is _convex_. (Under the assumption that `norm` implements a
/// valid norm, which cannot be checked by this function.)
///
/// See also `isApproximatelyEqual(to:[relativeTolerance:])`.
///
/// - Parameters:
///
/// - other: The value to which `self` is compared.
///
/// - absoluteTolerance: The absolute tolerance to use in the comparison.
///
/// This value should be non-negative and finite.
/// This constraint on is only checked in debug builds, because a
/// mathematically well-defined result exists for any tolerance,
/// even one out of range.
///
/// - relativeTolerance: The relative tolerance to use in the comparison.
/// Defaults to zero.
///
/// This value should be non-negative and less than or equal to 1.
/// This constraint on is only checked in debug builds, because a
/// mathematically well-defined result exists for any tolerance,
/// even one out of range.
@inlinable @inline(__always)
public func isApproximatelyEqual(
to other: Self,
absoluteTolerance: Magnitude,
relativeTolerance: Magnitude = 0
) -> Bool {
self.isApproximatelyEqual(
to: other,
absoluteTolerance: absoluteTolerance,
relativeTolerance: relativeTolerance,
norm: \.magnitude
)
}
}
extension AdditiveArithmetic {
/// Test if `self` and `other` are approximately equal with specified
/// tolerances and norm.
///
/// `true` if `self` and `other` are equal, or if they are finite and either
/// ```
/// norm(self - other) <= absoluteTolerance
/// ```
/// or
/// ```
/// norm(self - other) <= relativeTolerance * scale
/// ```
/// where `scale` is `max(norm(self), norm(other))`.
///
/// Mathematical Properties:
///
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:norm:)`
/// is _reflexive_ for non-exceptional values (such as NaN).
///
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:norm:)`
/// is _symmetric_.
///
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:norm:)`
/// is __not__ _transitive_. Because of this, approximately equality is
/// __not an equivalence relation__, even when restricted to
/// non-exceptional values.
///
/// This means that you must not use approximate equality to implement
/// a conformance to Equatable, as it will violate the invariants of
/// code written against that protocol.
///
/// - For any point `a`, the set of values that compare approximately equal
/// to `a` is _convex_ (under the assumption that `norm` implements a
/// valid norm, which cannot be checked by this function or a protocol).
///
/// See also `isApproximatelyEqual(to:[relativeTolerance:norm:])` and
/// `isApproximatelyEqual(to:absoluteTolerance:[relativeTolerance:])`.
///
/// - Parameters:
///
/// - other: The value to which `self` is compared.
///
/// - absoluteTolerance: The absolute tolerance to use in the comparison.
///
/// This value should be non-negative and finite.
/// This constraint on is only checked in debug builds, because a
/// mathematically well-defined result exists for any tolerance, even
/// one out of range.
///
/// - relativeTolerance: The relative tolerance to use in the comparison.
/// Defaults to zero.
///
/// This value should be non-negative and less than or equal to 1.
/// This constraint on is only checked in debug builds, because a
/// mathematically well-defined result exists for any tolerance,
/// even one out of range.
///
/// - norm: The norm to use for the comparison.
/// Defaults to `\.magnitude`.
///
/// For example, if we wanted to test if a complex value was inside a
/// circle of radius 0.001 centered at (1 + 0i), we could use:
/// ```
/// z.isApproximatelyEqual(
/// to: 1,
/// absoluteTolerance: 0.001,
/// norm: \.length
/// )
/// ```
/// (if we used the default norm, `.magnitude`, we would be testing if
/// `z` were inside a square region instead.)
@inlinable
public func isApproximatelyEqual<Magnitude>(
to other: Self,
absoluteTolerance: Magnitude,
relativeTolerance: Magnitude = 0,
norm: (Self) -> Magnitude
) -> Bool
// TODO: constraint should really be weaker than FloatingPoint,
// but we need to have `isFinite` for it to work correctly with
// floating-point magnitudes in generic contexts, which is the
// most common case. The fix for this is to lift the isFinite
// requirement to Numeric in the standard library, but that's
// source-breaking, so requires an ABI rumspringa.
where Magnitude: FloatingPoint {
assert(
absoluteTolerance >= 0 && absoluteTolerance.isFinite,
"absoluteTolerance should be non-negative and finite, " +
"but is \(absoluteTolerance)."
)
assert(
relativeTolerance >= 0 && relativeTolerance <= 1,
"relativeTolerance should be non-negative and <= 1, " +
"but is \(relativeTolerance)."
)
if self == other { return true }
let delta = norm(self - other)
let scale = max(norm(self), norm(other))
let bound = max(absoluteTolerance, scale*relativeTolerance)
return delta.isFinite && delta <= bound
}
}
@@ -0,0 +1,142 @@
//===--- AugmentedArithmetic.swift ----------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A namespace for "augmented arithmetic" operations for types conforming to
/// `Real`.
///
/// Augmented arithmetic refers to a family of algorithms that represent
/// the results of floating-point computations using multiple values such that
/// either the error is minimized or the result is exact.
public enum Augmented { }
extension Augmented {
/// The product `a * b` represented as an implicit sum `head + tail`.
///
/// `head` is the correctly rounded value of `a*b`. If no overflow or
/// underflow occurs, `tail` represents the rounding error incurred in
/// computing `head`, such that the exact product is the sum of `head`
/// and `tail` computed without rounding.
///
/// This operation is sometimes called "twoProd" or "twoProduct".
///
/// Edge Cases:
///
/// - `head` is always the IEEE 754 product `a * b`.
/// - If `head` is not finite, `tail` is unspecified and should not be
/// interpreted as having any meaning (it may be `NaN` or `infinity`).
/// - When `head` is close to the underflow boundary, the rounding error
/// may not be representable due to underflow, and `tail` will be rounded.
/// If `head` is very small, `tail` may even be zero, even though the
/// product is not exact.
/// - If `head` is zero, `tail` is also a zero with unspecified sign.
///
/// Postconditions:
///
/// - If `head` is normal, then `abs(tail) < head.ulp`.
/// Assuming IEEE 754 default rounding, `abs(tail) <= head.ulp/2`.
/// - If both `head` and `tail` are normal, then `a * b` is exactly
/// equal to `head + tail` when computed as real numbers.
@_transparent
public static func product<T:Real>(_ a: T, _ b: T) -> (head: T, tail: T) {
let head = a*b
// TODO: consider providing an FMA-less implementation for use when
// targeting platforms without hardware FMA support. This works everywhere,
// falling back on the C math.h fma funcions, but may be slow on older x86.
let tail = (-head).addingProduct(a, b)
return (head, tail)
}
/// The sum `a + b` represented as an implicit sum `head + tail`.
///
/// `head` is the correctly rounded value of `a + b`. `tail` is the
/// error from that computation rounded to the closest representable
/// value.
///
/// Unlike `Augmented.product(a, b)`, the rounding error of a sum can
/// never underflow.
///
/// This operation is sometimes called ["fastTwoSum"].
///
/// - Parameters:
/// - a: The summand with larger magnitude.
/// - b: The summand with smaller magnitude.
///
/// Preconditions:
///
/// - `large.magnitude` must not be smaller than `small.magnitude`.
/// They may be equal, or one or both may be `NaN`.
/// This precondition is only enforced in debug builds.
///
/// Edge Cases:
///
/// - `head` is always the IEEE 754 sum `a + b`.
/// - If `head` is not finite, `tail` is unspecified and should not be
/// interpreted as having any meaning (it may be `NaN` or `infinity`).
///
/// Postconditions:
///
/// - If `head` is normal, then `abs(tail) < head.ulp`.
/// Assuming IEEE 754 default rounding, `abs(tail) <= head.ulp/2`.
///
/// ["fastTwoSum"]: https://en.wikipedia.org/wiki/2Sum
@_transparent
public static func sum<T:Real>(large a: T, small b: T) -> (head: T, tail: T) {
assert(!(b.magnitude > a.magnitude))
let head = a + b
let tail = a - head + b
return (head, tail)
}
/// The sum `a + b` represented as an implicit sum `head + tail`.
///
/// `head` is the correctly rounded value of `a + b`. `tail` is the
/// error from that computation rounded to the closest representable
/// value.
///
/// Unlike `Augmented.sum(large: a, small: b)`, the magnitude of the summands
/// does not matter and `a.magnitude` might as well be strictly less than
/// `b.magnitude`. However, it is recommended to only use this function over
/// `Augmented.sum(large: a, small: b)` in cases where the ordering of the
/// summands magnitude is unknown at compile time. In cases where either of
/// the summands magnitude is guaranteed to be greater than or equal the
/// magnitude of the other summand, use `Augmented.sum(large: a, small: b)`
/// over this function; as it faster to calculate.
///
/// Unlike `Augmented.product(a, b)`, the rounding error of a sum can
/// never underflow.
///
/// This operation is sometimes called ["twoSum"].
///
/// - Parameters:
/// - a: One of the summand
/// - b: The other summand
///
/// Edge Cases:
///
/// - `head` is always the IEEE 754 sum `a + b`.
/// - If `head` is not finite, `tail` is unspecified and should not be
/// interpreted as having any meaning (it may be `NaN` or `infinity`).
///
/// Postconditions:
///
/// - If `head` is normal, then `abs(tail) < head.ulp`.
/// Assuming IEEE 754 default rounding, `abs(tail) <= head.ulp/2`.
///
/// ["twoSum"]: https://en.wikipedia.org/wiki/2Sum
@_transparent
public static func sum<T: Real>(_ a: T, _ b: T) -> (head: T, tail: T) {
let head = a + b
let x = head - b
let y = head - x
let tail = (a - x) + (b - y)
return (head, tail)
}
}
+29
View File
@@ -0,0 +1,29 @@
#[[
This source file is part of the Swift Numerics open source project
Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
#]]
add_library(RealModule
AlgebraicField.swift
ApproximateEquality.swift
AugmentedArithmetic.swift
Double+Real.swift
ElementaryFunctions.swift
Float+Real.swift
Float16+Real.swift
Float80+Real.swift
Real.swift
RealFunctions.swift
RelaxedArithmetic.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)
+232
View File
@@ -0,0 +1,232 @@
//===--- Double+Real.swift ------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import _NumericsShims
extension Double: Real {
@_transparent
public static func cos(_ x: Double) -> Double {
libm_cos(x)
}
@_transparent
public static func sin(_ x: Double) -> Double {
libm_sin(x)
}
@_transparent
public static func tan(_ x: Double) -> Double {
libm_tan(x)
}
@_transparent
public static func acos(_ x: Double) -> Double {
libm_acos(x)
}
@_transparent
public static func asin(_ x: Double) -> Double {
libm_asin(x)
}
@_transparent
public static func atan(_ x: Double) -> Double {
libm_atan(x)
}
@_transparent
public static func cosh(_ x: Double) -> Double {
libm_cosh(x)
}
@_transparent
public static func sinh(_ x: Double) -> Double {
libm_sinh(x)
}
@_transparent
public static func tanh(_ x: Double) -> Double {
libm_tanh(x)
}
@_transparent
public static func acosh(_ x: Double) -> Double {
libm_acosh(x)
}
@_transparent
public static func asinh(_ x: Double) -> Double {
libm_asinh(x)
}
@_transparent
public static func atanh(_ x: Double) -> Double {
libm_atanh(x)
}
@_transparent
public static func exp(_ x: Double) -> Double {
libm_exp(x)
}
@_transparent
public static func expMinusOne(_ x: Double) -> Double {
libm_expm1(x)
}
@_transparent
public static func log(_ x: Double) -> Double {
libm_log(x)
}
@_transparent
public static func log(onePlus x: Double) -> Double {
libm_log1p(x)
}
@_transparent
public static func erf(_ x: Double) -> Double {
libm_erf(x)
}
@_transparent
public static func erfc(_ x: Double) -> Double {
libm_erfc(x)
}
@_transparent
public static func exp2(_ x: Double) -> Double {
libm_exp2(x)
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
@_transparent
public static func exp10(_ x: Double) -> Double {
libm_exp10(x)
}
#endif
#if os(macOS) && arch(x86_64)
// Workaround for macOS bug (<rdar://problem/56844150>) where hypot can
// overflow for values very close to the overflow boundary of the naive
// algorithm. Since this is only for macOS, we can just unconditionally
// use Float80, which makes the implementation trivial.
public static func hypot(_ x: Double, _ y: Double) -> Double {
if x.isInfinite || y.isInfinite { return .infinity }
let x80 = Float80(x)
let y80 = Float80(y)
return Double(Float80.sqrt(x80*x80 + y80*y80))
}
#else
@_transparent
public static func hypot(_ x: Double, _ y: Double) -> Double {
libm_hypot(x, y)
}
#endif
@_transparent
public static func gamma(_ x: Double) -> Double {
libm_tgamma(x)
}
@_transparent
public static func log2(_ x: Double) -> Double {
libm_log2(x)
}
@_transparent
public static func log10(_ x: Double) -> Double {
libm_log10(x)
}
@_transparent
public static func pow(_ x: Double, _ y: Double) -> Double {
guard x >= 0 else { return .nan }
if x == 0 && y == 0 { return .nan }
return libm_pow(x, y)
}
@_transparent
public static func pow(_ x: Double, _ n: Int) -> Double {
// If n is exactly representable as Double, we can just call pow:
// Note that all calls on a 32b platform go down this path.
if let y = Double(exactly: n) { return libm_pow(x, y) }
// n is not representable in Double, so we will split it into two parts,
// low and high, such that (high + low) = n, and use the identity:
//
// x**(high + low) = x**high * x**low.
//
// We put the high-order 32 bits into high, and the remaining 32 bits
// in low.
//
// The exact split isn't important; all we need is that both pieces get
// less than 53 bits (so that they are exact) and that they both have
// the same sign as n.
//
// This second point is a little bit subtle--why is
// it necessary? Consider what would happen if we took x = 2 and
// n = Int.min + Int(UInt32.max), and simply naively split n without
// taking care with the sign. We would end up computing:
//
// 2**n = 2**Int.min * 2**UInt32.max
//
// The first exponent is negative, the second positive, so the first term
// underflows to zero, and the second overflows to infinity, so the final
// result is NaN, when it should be zero. In order to avoid this
// situation, we make sure that high contains n rounded *towards zero*,
// rather than using simple two's-complement truncation (which rounds
// down).
let mask = Int(truncatingIfNeeded: UInt32.max)
let round = n < 0 ? mask : 0
// The addition and subtraction below cannot actually overflow (proof:
// round is positive if n is negative, and zero otherwise, so n + round
// is guaranteed to be representable, and n and high have the same sign,
// so n - high is also representable), but it's hard to tell the compiler
// that, so I'm using wrapping operations instead.
let high = (n &+ round) & ~mask
let low = n &- high
return libm_pow(x, Double(low)) * libm_pow(x, Double(high))
}
@_transparent
public static func root(_ x: Double, _ n: Int) -> Double {
guard x >= 0 || n % 2 != 0 else { return .nan }
// Workaround the issue mentioned below for the specific case of n = 3
// where we can fallback on cbrt.
if n == 3 { return libm_cbrt(x) }
// TODO: this implementation is not quite correct, because either n or
// 1/n may be not be representable as Double.
return Double(signOf: x, magnitudeOf: libm_pow(x.magnitude, 1/Double(n)))
}
@_transparent
public static func atan2(y: Double, x: Double) -> Double {
libm_atan2(y, x)
}
#if !os(Windows)
@_transparent
public static func logGamma(_ x: Double) -> Double {
var dontCare: Int32 = 0
return libm_lgamma(x, &dontCare)
}
#endif
@_transparent
public static func _relaxedAdd(_ a: Double, _ b: Double) -> Double {
_numerics_relaxed_add(a, b)
}
@_transparent
public static func _relaxedMul(_ a: Double, _ b: Double) -> Double {
_numerics_relaxed_mul(a, b)
}
}
@@ -24,18 +24,21 @@
/// let y = Float.sin(x) // 0.84147096
/// ```
///
/// There are three broad families of functions defined by `ElementaryFunctions`:
/// There are three broad families of functions defined by
/// `ElementaryFunctions`:
/// - Exponential, trigonometric, and hyperbolic functions:
/// `exp`, `expMinusOne`, `cos`, `sin`, `tan`, `cosh`, `sinh`, and `tanh`.
/// - Logarithmic, inverse trigonometric, and inverse hyperbolic functions:
/// `log`, `log(onePlus:)`, `acos`, `asin`, `atan`, `acosh`, `asinh`, and `atanh`.
/// `log`, `log(onePlus:)`, `acos`, `asin`, `atan`, `acosh`, `asinh`, and
/// `atanh`.
/// - Power and root functions:
/// `pow`, `sqrt`, and `root`.
///
/// `ElementaryFunctions` conformance implies `AdditiveArithmetic`, so addition
/// and subtraction and the `.zero` property are also available.
///
/// There are two other protocols that you are more likely to want to use directly:
/// There are two other protocols that you are more likely to want to use
/// directly:
///
/// `RealFunctions` refines `ElementaryFunctions` and includes
/// additional functions specific to real number types.
@@ -44,44 +47,40 @@
/// protocol that you will want to use most often for generic code.
///
/// See Also:
/// -
///
/// - `RealFunctions`
/// - `Real`
///
/// [elfn]: http://en.wikipedia.org/wiki/Elementary_function
public protocol ElementaryFunctions: AdditiveArithmetic {
/// The [exponential function][wiki] e^x whose base `e` is the base of the natural logarithm.
/// The [exponential function][wiki] e^x whose base `e` is the base of the
/// natural logarithm.
///
/// See also:
/// -
/// - `expMinusOne()`
/// - `exp2()` (for types conforming to `RealFunctions`)
/// - `exp10()` (for types conforming to `RealFunctions`)
/// See also `expMinusOne()`, as well as `exp2()` and `exp10()`
/// defined for types conforming to `RealFunctions`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Exponential_function
static func exp(_ x: Self) -> Self
/// exp(x) - 1, computed in such a way as to maintain accuracy for small x.
///
/// When `x` is close to zero, the expression `.exp(x) - 1` suffers from catastrophic
/// cancellation and the result will not have full accuracy. The `.expMinusOne(x)` function gives
/// you a means to address this problem.
/// When `x` is close to zero, the expression `.exp(x) - 1` suffers from
/// catastrophic cancellation and the result will not have full accuracy.
/// The `.expMinusOne(x)` function gives you a means to address this problem.
///
/// As an example, consider the expression `(x + 1)*exp(x) - 1`. When `x` is smaller
/// than `.ulpOfOne`, this expression evaluates to `0.0`, when it should actually round to
/// `2*x`. We can get a full-accuracy result by using the following instead:
/// As an example, consider the expression `(x + 1)*exp(x) - 1`. When `x`
/// is smaller than `.ulpOfOne`, this expression evaluates to `0.0`, when it
/// should actually round to `2*x`. We can get a full-accuracy result by
/// using the following instead:
/// ```
/// let t = .expMinusOne(x)
/// return x*(t+1) + t // x*exp(x) + (exp(x)-1) = (x+1)*exp(x) - 1
/// ```
/// This re-written expression delivers an accurate result for all values of `x`, not just for
/// small values.
/// This re-written expression delivers an accurate result for all values
/// of `x`, not just for small values.
///
/// See also:
/// -
/// - `exp()`
/// - `exp2()` (for types conforming to `RealFunctions`)
/// - `exp10()` (for types conforming to `RealFunctions`)
/// See also `exp()`, as well as `exp2()` and `exp10()` defined for types
/// conforming to `RealFunctions`.
static func expMinusOne(_ x: Self) -> Self
/// The [hyperbolic cosine][wiki] of `x`.
@@ -91,11 +90,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// 2
/// ```
///
/// See also:
/// -
/// - `sinh()`
/// - `tanh()`
/// - `acosh()`
/// See also `sinh()`, `tanh()` and `acosh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
static func cosh(_ x: Self) -> Self
@@ -107,11 +102,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// 2
/// ```
///
/// See also:
/// -
/// - `cosh()`
/// - `tanh()`
/// - `asinh()`
/// See also `cosh()`, `tanh()` and `asinh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
static func sinh(_ x: Self) -> Self
@@ -123,11 +114,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// cosh(x)
/// ```
///
/// See also:
/// -
/// - `cosh()`
/// - `sinhh()`
/// - `atanh()`
/// See also `cosh()`, `sinh()` and `atanh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
static func tanh(_ x: Self) -> Self
@@ -136,11 +123,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
///
/// For real types, `x` may be interpreted as an angle measured in radians.
///
/// See also:
/// -
/// - `sin()`
/// - `tan()`
/// - `acos()`
/// See also `sin()`, `tan()` and `acos()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Cosine
static func cos(_ x: Self) -> Self
@@ -150,11 +133,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
///
/// For real types, `x` may be interpreted as an angle measured in radians.
///
/// See also:
/// -
/// - `cos()`
/// - `tan()`
/// - `asin()`
/// See also `cos()`, `tan()` and `asin()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Sine
static func sin(_ x: Self) -> Self
@@ -163,49 +142,31 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
///
/// For real types, `x` may be interpreted as an angle measured in radians.
///
/// See also:
/// -
/// - `cos()`
/// - `sin()`
/// - `atan()`
/// - `atan2(y:x:)` (for types conforming to `RealFunctions`)
/// ```
/// sin(x)
/// tan(x) = --------
/// cos(x)
/// ```
/// See also `cos()`, `sin()` and `atan()`, as well as `atan2(y:x:)` for
/// types that conform to `RealFunctions`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Tangent
static func tan(_ x: Self) -> Self
/// The [natural logarithm][wiki] of `x`.
///
/// See also:
/// -
/// - `log(onePlus:)`
/// - `log2()` (for types conforming to `RealFunctions`)
/// - `log10()` (for types conforming to `RealFunctions`)
/// See also `log(onePlus:)`, as well as `log2()` and `log10()` for types
/// that conform to `RealFunctions`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Logarithm
static func log(_ x: Self) -> Self
/// log(1 + x), computed in such a way as to maintain accuracy for small x.
///
/// See also:
/// -
/// - `log()`
/// - `log2()` (for types conforming to `RealFunctions`)
/// - `log10()` (for types conforming to `RealFunctions`)
/// See also `log()`, as well as `log2()` and `log10()` for types
/// that conform to `RealFunctions`.
static func log(onePlus x: Self) -> Self
/// The [inverse hyperbolic cosine][wiki] of `x`.
/// ```
/// cosh(acosh(x)) ≅ x
/// ```
/// See also:
/// -
/// - `asinh()`
/// - `atanh()`
/// - `cosh()`
/// See also `asinh()`, `atanh()` and `cosh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
static func acosh(_ x: Self) -> Self
@@ -214,11 +175,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// ```
/// sinh(asinh(x)) ≅ x
/// ```
/// See also:
/// -
/// - `acosh()`
/// - `atanh()`
/// - `sinh()`
/// See also `acosh()`, `atanh()` and `sinh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
static func asinh(_ x: Self) -> Self
@@ -227,95 +184,79 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
/// ```
/// tanh(atanh(x)) ≅ x
/// ```
/// See also:
/// -
/// - `acosh()`
/// - `asinh()`
/// - `tanh()`
/// See also `acosh()`, `asinh()` and `tanh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
static func atanh(_ x: Self) -> Self
/// The [arccosine][wiki] (inverse cosine) of `x`.
///
/// For real types, the result may be interpreted as an angle measured in radians.
/// For real types, the result may be interpreted as an angle measured in
/// radians.
/// ```
/// cos(acos(x)) ≅ x
/// ```
/// See also:
/// -
/// - `asin()`
/// - `atan()`
/// - `cos()`
/// See also `asin()`, `atan()` and `cos()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
static func acos(_ x: Self) -> Self
/// The [arcsine][wiki] (inverse sine) of `x`.
///
/// For real types, the result may be interpreted as an angle measured in radians.
/// For real types, the result may be interpreted as an angle measured in
/// radians.
/// ```
/// sin(asin(x)) ≅ x
/// ```
/// See also:
/// -
/// - `acos()`
/// - `atan()`
/// - `sin()`
/// See also `acos()`, `atan()` and `sin()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
static func asin(_ x: Self) -> Self
/// The [arctangent][wiki] (inverse tangent) of `x`.
///
/// For real types, the result may be interpreted as an angle measured in radians.
/// For real types, the result may be interpreted as an angle measured in
/// radians.
/// ```
/// tan(atan(x)) ≅ x
/// ```
/// See also:
/// -
/// - `acos()`
/// - `asin()`
/// - `atan2()` (for types conforming to `RealFunctions`)
/// - `tan()`
/// See also `acos()`, `asin()` and `tan()`, as well as `atan2(y:x:)` for
/// types that conform to `RealArithmetic`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
static func atan(_ x: Self) -> Self
/// exp(y * log(x)) computed with additional internal precision.
///
/// See also:
/// -
/// - `sqrt()`
/// - `root()`
/// The edge-cases of this function are defined based on the behavior of the
/// expression `exp(y log x)`, matching IEEE 754's `powr` operation.
/// In particular, this means that if `x` and `y` are both zero, `pow(x,y)`
/// is `nan` for real types and `infinity` for complex types, rather than 1.
///
/// There is also a `pow(_:Self,_:Int)` overload, whose behavior is defined
/// in terms of repeated multiplication, and hence returns 1 for this case.
///
/// See also `sqrt()` and `root()`.
static func pow(_ x: Self, _ y: Self) -> Self
/// `x` raised to the nth power.
///
/// See also:
/// -
/// - `sqrt()`
/// - `root()`
/// The edge-cases of this function are defined in terms of repeated
/// multiplication or division, rather than exp(n log x). In particular,
/// `Float.pow(0, 0)` is 1.
///
/// See also `sqrt()` and `root()`.
static func pow(_ x: Self, _ n: Int) -> Self
/// The [square root][wiki] of `x`.
///
/// See also:
/// -
/// - `pow()`
/// - `root()`
/// See also `pow()` and `root()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Square_root
static func sqrt(_ x: Self) -> Self
/// The nth root of `x`.
///
/// See also:
/// -
/// - `pow()`
/// - `sqrt()`
///
/// See also `pow()` and `sqrt()`.
static func root(_ x: Self, _ n: Int) -> Self
}
+205
View File
@@ -0,0 +1,205 @@
//===--- Float+Real.swift -------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import _NumericsShims
extension Float: Real {
@_transparent
public static func cos(_ x: Float) -> Float {
libm_cosf(x)
}
@_transparent
public static func sin(_ x: Float) -> Float {
libm_sinf(x)
}
@_transparent
public static func tan(_ x: Float) -> Float {
libm_tanf(x)
}
@_transparent
public static func acos(_ x: Float) -> Float {
libm_acosf(x)
}
@_transparent
public static func asin(_ x: Float) -> Float {
libm_asinf(x)
}
@_transparent
public static func atan(_ x: Float) -> Float {
libm_atanf(x)
}
@_transparent
public static func cosh(_ x: Float) -> Float {
libm_coshf(x)
}
@_transparent
public static func sinh(_ x: Float) -> Float {
libm_sinhf(x)
}
@_transparent
public static func tanh(_ x: Float) -> Float {
libm_tanhf(x)
}
@_transparent
public static func acosh(_ x: Float) -> Float {
libm_acoshf(x)
}
@_transparent
public static func asinh(_ x: Float) -> Float {
libm_asinhf(x)
}
@_transparent
public static func atanh(_ x: Float) -> Float {
libm_atanhf(x)
}
@_transparent
public static func exp(_ x: Float) -> Float {
libm_expf(x)
}
@_transparent
public static func expMinusOne(_ x: Float) -> Float {
libm_expm1f(x)
}
@_transparent
public static func log(_ x: Float) -> Float {
libm_logf(x)
}
@_transparent
public static func log(onePlus x: Float) -> Float {
libm_log1pf(x)
}
@_transparent
public static func erf(_ x: Float) -> Float {
libm_erff(x)
}
@_transparent
public static func erfc(_ x: Float) -> Float {
libm_erfcf(x)
}
@_transparent
public static func exp2(_ x: Float) -> Float {
libm_exp2f(x)
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
@_transparent
public static func exp10(_ x: Float) -> Float {
libm_exp10f(x)
}
#endif
@_transparent
public static func hypot(_ x: Float, _ y: Float) -> Float {
libm_hypotf(x, y)
}
@_transparent
public static func gamma(_ x: Float) -> Float {
libm_tgammaf(x)
}
@_transparent
public static func log2(_ x: Float) -> Float {
libm_log2f(x)
}
@_transparent
public static func log10(_ x: Float) -> Float {
libm_log10f(x)
}
@_transparent
public static func pow(_ x: Float, _ y: Float) -> Float {
guard x >= 0 else { return .nan }
if x == 0 && y == 0 { return .nan }
return libm_powf(x, y)
}
@_transparent
public static func pow(_ x: Float, _ n: Int) -> Float {
// If n is exactly representable as Float, we can just call powf:
if let y = Float(exactly: n) {
return libm_powf(x, y)
}
// Otherwise, n is too large to losslessly represent as Float.
// The range of "interesting" n is -1488522191 ... 1744361944; outside
// of this range, all x != 1 overflow or underflow, so only the parity
// of x matters. We don't really care about the specific range at all,
// only that the bounds fit exactly into two Floats.
//
// We do, however, need to be careful that high and low both have the
// same sign as n (consult the Double implementation for details of why
// this matters), so we need to be a little bit careful constructing
// them.
//
// Unlike the Double implementation, when n is very large, high will
// get rounded here; that's OK because it does not change the sign or
// parity, which are the only two bits that matter for such large
// exponents in Float.
let mask = Int(truncatingIfNeeded: 0xffffff)
let round = n < 0 ? mask : 0
let high = (n &+ round) & ~mask
let low = n &- high
return libm_powf(x, Float(low)) * libm_powf(x, Float(high))
}
@_transparent
public static func root(_ x: Float, _ n: Int) -> Float {
guard x >= 0 || n % 2 != 0 else { return .nan }
// Workaround the issue mentioned below for the specific case of n = 3
// where we can fallback on cbrt.
if n == 3 { return libm_cbrtf(x) }
// TODO: this implementation is not quite correct, because either n or
// 1/n may be not be representable as Float.
return Float(signOf: x, magnitudeOf: libm_powf(x.magnitude, 1/Float(n)))
}
@_transparent
public static func atan2(y: Float, x: Float) -> Float {
libm_atan2f(y, x)
}
#if !os(Windows)
@_transparent
public static func logGamma(_ x: Float) -> Float {
var dontCare: Int32 = 0
return libm_lgammaf(x, &dontCare)
}
#endif
@_transparent
public static func _relaxedAdd(_ a: Float, _ b: Float) -> Float {
_numerics_relaxed_addf(a, b)
}
@_transparent
public static func _relaxedMul(_ a: Float, _ b: Float) -> Float {
_numerics_relaxed_mulf(a, b)
}
}
+191
View File
@@ -0,0 +1,191 @@
//===--- Float16+Real.swift -----------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import _NumericsShims
// Float16 is only available on macOS when targeting arm64.
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
extension Float16: Real {
@_transparent
public static func cos(_ x: Float16) -> Float16 {
Float16(.cos(Float(x)))
}
@_transparent
public static func sin(_ x: Float16) -> Float16 {
Float16(.sin(Float(x)))
}
@_transparent
public static func tan(_ x: Float16) -> Float16 {
Float16(.tan(Float(x)))
}
@_transparent
public static func acos(_ x: Float16) -> Float16 {
Float16(.acos(Float(x)))
}
@_transparent
public static func asin(_ x: Float16) -> Float16 {
Float16(.asin(Float(x)))
}
@_transparent
public static func atan(_ x: Float16) -> Float16 {
Float16(.atan(Float(x)))
}
@_transparent
public static func cosh(_ x: Float16) -> Float16 {
Float16(.cosh(Float(x)))
}
@_transparent
public static func sinh(_ x: Float16) -> Float16 {
Float16(.sinh(Float(x)))
}
@_transparent
public static func tanh(_ x: Float16) -> Float16 {
Float16(.tanh(Float(x)))
}
@_transparent
public static func acosh(_ x: Float16) -> Float16 {
Float16(.acosh(Float(x)))
}
@_transparent
public static func asinh(_ x: Float16) -> Float16 {
Float16(.asinh(Float(x)))
}
@_transparent
public static func atanh(_ x: Float16) -> Float16 {
Float16(.atanh(Float(x)))
}
@_transparent
public static func exp(_ x: Float16) -> Float16 {
Float16(.exp(Float(x)))
}
@_transparent
public static func expMinusOne(_ x: Float16) -> Float16 {
Float16(.expMinusOne(Float(x)))
}
@_transparent
public static func log(_ x: Float16) -> Float16 {
Float16(.log(Float(x)))
}
@_transparent
public static func log(onePlus x: Float16) -> Float16 {
Float16(.log(onePlus: Float(x)))
}
@_transparent
public static func erf(_ x: Float16) -> Float16 {
Float16(.erf(Float(x)))
}
@_transparent
public static func erfc(_ x: Float16) -> Float16 {
Float16(.erfc(Float(x)))
}
@_transparent
public static func exp2(_ x: Float16) -> Float16 {
Float16(.exp2(Float(x)))
}
@_transparent
public static func exp10(_ x: Float16) -> Float16 {
Float16(.exp10(Float(x)))
}
@_transparent
public static func hypot(_ x: Float16, _ y: Float16) -> Float16 {
if x.isInfinite || y.isInfinite { return .infinity }
let xf = Float(x)
let yf = Float(y)
return Float16(.sqrt(xf*xf + yf*yf))
}
@_transparent
public static func gamma(_ x: Float16) -> Float16 {
Float16(.gamma(Float(x)))
}
@_transparent
public static func log2(_ x: Float16) -> Float16 {
Float16(.log2(Float(x)))
}
@_transparent
public static func log10(_ x: Float16) -> Float16 {
Float16(.log10(Float(x)))
}
@_transparent
public static func pow(_ x: Float16, _ y: Float16) -> Float16 {
Float16(.pow(Float(x), Float(y)))
}
@_transparent
public static func pow(_ x: Float16, _ n: Int) -> Float16 {
// Float16 is simpler than Float or Double, because the range of
// "interesting" exponents is pretty small; anything outside of
// -22707 ... 34061 simply overflows or underflows for every
// x that isn't zero or one. This whole range is representable
// as Float, so we can just use powf as long as we're a little
// bit (get it?) careful to preserve parity.
let clamped = min(max(n, -0x10000), 0x10000) | (n & 1)
return Float16(libm_powf(Float(x), Float(clamped)))
}
@_transparent
public static func root(_ x: Float16, _ n: Int) -> Float16 {
Float16(.root(Float(x), n))
}
@_transparent
public static func atan2(y: Float16, x: Float16) -> Float16 {
Float16(.atan2(y: Float(y), x: Float(x)))
}
#if !os(Windows)
@_transparent
public static func logGamma(_ x: Float16) -> Float16 {
Float16(.logGamma(Float(x)))
}
#endif
// TODO: once clang stabilizes the calling conventions for _Float16 on Intel,
// we can re-enable these; presently the type is disabled on the target.
#if !(arch(i386) || arch(x86_64))
@_transparent
public static func _relaxedAdd(_ a: Float16, _ b: Float16) -> Float16 {
_numerics_relaxed_addf16(a, b)
}
@_transparent
public static func _relaxedMul(_ a: Float16, _ b: Float16) -> Float16 {
_numerics_relaxed_mulf16(a, b)
}
#endif
}
#endif
+179
View File
@@ -0,0 +1,179 @@
//===--- Float80+Real.swift -----------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import _NumericsShims
// Restrict extension to platforms for which Float80 exists.
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
extension Float80: Real {
@_transparent
public static func cos(_ x: Float80) -> Float80 {
libm_cosl(x)
}
@_transparent
public static func sin(_ x: Float80) -> Float80 {
libm_sinl(x)
}
@_transparent
public static func tan(_ x: Float80) -> Float80 {
libm_tanl(x)
}
@_transparent
public static func acos(_ x: Float80) -> Float80 {
libm_acosl(x)
}
@_transparent
public static func asin(_ x: Float80) -> Float80 {
libm_asinl(x)
}
@_transparent
public static func atan(_ x: Float80) -> Float80 {
libm_atanl(x)
}
@_transparent
public static func cosh(_ x: Float80) -> Float80 {
libm_coshl(x)
}
@_transparent
public static func sinh(_ x: Float80) -> Float80 {
libm_sinhl(x)
}
@_transparent
public static func tanh(_ x: Float80) -> Float80 {
libm_tanhl(x)
}
@_transparent
public static func acosh(_ x: Float80) -> Float80 {
libm_acoshl(x)
}
@_transparent
public static func asinh(_ x: Float80) -> Float80 {
libm_asinhl(x)
}
@_transparent
public static func atanh(_ x: Float80) -> Float80 {
libm_atanhl(x)
}
@_transparent
public static func exp(_ x: Float80) -> Float80 {
libm_expl(x)
}
@_transparent
public static func expMinusOne(_ x: Float80) -> Float80 {
libm_expm1l(x)
}
@_transparent
public static func log(_ x: Float80) -> Float80 {
libm_logl(x)
}
@_transparent
public static func log(onePlus x: Float80) -> Float80 {
libm_log1pl(x)
}
@_transparent
public static func erf(_ x: Float80) -> Float80 {
libm_erfl(x)
}
@_transparent
public static func erfc(_ x: Float80) -> Float80 {
libm_erfcl(x)
}
@_transparent
public static func exp2(_ x: Float80) -> Float80 {
libm_exp2l(x)
}
@_transparent
public static func hypot(_ x: Float80, _ y: Float80) -> Float80 {
libm_hypotl(x, y)
}
@_transparent
public static func gamma(_ x: Float80) -> Float80 {
libm_tgammal(x)
}
@_transparent
public static func log2(_ x: Float80) -> Float80 {
libm_log2l(x)
}
@_transparent
public static func log10(_ x: Float80) -> Float80 {
libm_log10l(x)
}
@_transparent
public static func pow(_ x: Float80, _ y: Float80) -> Float80 {
guard x >= 0 else { return .nan }
if x == 0 && y == 0 { return .nan }
return libm_powl(x, y)
}
@_transparent
public static func pow(_ x: Float80, _ n: Int) -> Float80 {
// Every Int value is exactly representable as Float80, so we don't need
// to do anything fancy--unlike Float and Double, we can just call the
// libm pow function.
libm_powl(x, Float80(n))
}
@_transparent
public static func root(_ x: Float80, _ n: Int) -> Float80 {
guard x >= 0 || n % 2 != 0 else { return .nan }
// Workaround the issue mentioned below for the specific case of n = 3
// where we can fallback on cbrt.
if n == 3 { return libm_cbrtl(x) }
// TODO: this implementation is not quite correct, because either n or
// 1/n may be not be representable as Float80.
return Float80(signOf: x, magnitudeOf: libm_powl(x.magnitude, 1/Float80(n)))
}
@_transparent
public static func atan2(y: Float80, x: Float80) -> Float80 {
libm_atan2l(y, x)
}
@_transparent
public static func logGamma(_ x: Float80) -> Float80 {
var dontCare: Int32 = 0
return libm_lgammal(x, &dontCare)
}
@_transparent
public static func _relaxedAdd(_ a: Float80, _ b: Float80) -> Float80 {
_numerics_relaxed_addl(a, b)
}
@_transparent
public static func _relaxedMul(_ a: Float80, _ b: Float80) -> Float80 {
_numerics_relaxed_mull(a, b)
}
}
#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
+149
View File
@@ -0,0 +1,149 @@
//===--- Real.swift -------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A type that models the real numbers.
///
/// Types conforming to this protocol provide the arithmetic and utility
/// operations defined by the `FloatingPoint` protocol, and provide all of the
/// math functions defined by the `ElementaryFunctions` and `RealFunctions`
/// protocols. This protocol does not add any additional conformances itself,
/// but is very useful as a protocol against which to write generic code. For
/// example, we can naturally write a generic implementation of a sigmoid
/// function:
/// ```
/// func sigmoid<T: Real>(_ x: T) -> T {
/// return 1/(1 + .exp(-x))
/// }
/// ```
/// See also `ElementaryFunctions`, `RealFunctions` and `AlgebraicField`.
public protocol Real: FloatingPoint, RealFunctions, AlgebraicField {
}
// While `Real` does not provide any additional customization points,
// it does allow us to default the implementation of a few operations,
// and also provides `signGamma`.
extension Real {
// Most math libraries do not provide exp10, so we need a default
// implementation.
@_transparent
public static func exp10(_ x: Self) -> Self {
return pow(10, x)
}
/// cos(x) - 1, computed in such a way as to maintain accuracy for small x.
///
/// See also `ElementaryFunctions.expMinusOne()`.
@_transparent
public static func cosMinusOne(_ x: Self) -> Self {
let sinxOver2 = sin(x/2)
return -2*sinxOver2*sinxOver2
}
#if !os(Windows)
public static func signGamma(_ x: Self) -> FloatingPointSign {
// Gamma is strictly positive for x >= 0.
if x >= 0 { return .plus }
// For negative x, we arbitrarily choose to assign a sign of .plus to the
// poles.
let trunc = x.rounded(.towardZero)
if x == trunc { return .plus }
// Otherwise, signGamma is .minus if the integral part of x is even.
return trunc.isEven ? .minus : .plus
}
// Determines if this value is even, assuming that it is an integer.
@inline(__always)
private var isEven: Bool {
if Self.radix == 2 {
// For binary types, we can just check if x/2 is an integer. This works
// because x/2 is always computed exactly.
let half = self/2
return half == half.rounded(.towardZero)
} else {
// For decimal types, it's not quite that simple, because x/2 is not
// necessarily computed exactly. As an example, suppose that we had a
// decimal type with a one digit significand, and self = 7. Then self/2
// would round to 4, and we would (wrongly) conclude that it was an
// integer, and hence that self was even.
//
// Instead, for decimal types, we check if 2*trunc(self/2) == self,
// using an FMA; this is always correct; this approach works for any
// radix, but the previous method is more efficient for radix == 2.
let half = self/2
return self.addingProduct(-2, half.rounded(.towardZero)) == 0
}
}
#endif
@_transparent
public static func _mulAdd(_ a: Self, _ b: Self, _ c: Self) -> Self {
a*b + c
}
@_transparent
public static func sqrt(_ x: Self) -> Self {
return x.squareRoot()
}
/// The (approximate) reciprocal (multiplicative inverse) of this number,
/// if it is representable.
///
/// If `a` if finite and nonzero, and `1/a` overflows or underflows,
/// then `a.reciprocal` is `nil`. Otherwise, `a.reciprocal` is `1/a`.
///
/// If `b.reciprocal` is non-nil, you may be able to replace division by `b`
/// with multiplication by this value. It is not advantageous to do this
/// for an isolated division unless it is a compile-time constant visible
/// to the compiler, but if you are dividing many values by a single
/// denominator, this will often be a significant performance win.
///
/// A typical use case looks something like this:
/// ```
/// func divide<T: Real>(data: [T], by divisor: T) -> [T] {
/// // If divisor is well-scaled, multiply by reciprocal.
/// if let recip = divisor.reciprocal {
/// return data.map { $0 * recip }
/// }
/// // Fallback on using division.
/// return data.map { $0 / divisor }
/// }
/// ```
///
/// Error Bounds:
///
/// Multiplying by the reciprocal instead of dividing will slightly
/// perturb results. For example `5.0 / 3` is 1.6666666666666667, but
/// `5.0 * 3.reciprocal!` is 1.6666666666666665.
///
/// The error of a normal division is bounded by half an ulp of the
/// result; we can derive a quick error bound for multiplication by
/// the real reciprocal (when it exists) as follows (I will use circle
/// operators to denote real-number arithmetic, and normal operators
/// for floating-point arithmetic):
///
/// a * b.reciprocal! = a * (1/b)
/// = a * (1 ⊘ b)(1 + δ₁)
/// = (a ⊘ b)(1 + δ₁)(1 + δ₂)
/// = (a ⊘ b)(1 + δ₁ + δ₂ + δ₁δ₂)
///
/// where 0 < δᵢ <= ulpOfOne/2. This gives a roughly 1-ulp error,
/// about twice the error bound we get using division. For most
/// purposes this is an acceptable error, but if you need to match
/// results obtained using division, you should not use this.
@inlinable
public var reciprocal: Self? {
let recip = 1/self
if recip.isNormal || isZero || !isFinite {
return recip
}
return nil
}
}
@@ -12,76 +12,46 @@
public protocol RealFunctions: ElementaryFunctions {
/// `atan(y/x)`, with sign selected according to the quadrant of `(x, y)`.
///
/// See also:
/// -
/// - `atan()`
/// See also `atan()`.
static func atan2(y: Self, x: Self) -> Self
/// The error function evaluated at `x`.
///
/// See also:
/// -
/// - `erfc()`
/// See also `erfc()`.
static func erf(_ x: Self) -> Self
/// The complimentary error function evaluated at `x`.
///
/// See also:
/// -
/// - `erf()`
/// See also `erf()`.
static func erfc(_ x: Self) -> Self
/// 2^x
///
/// See also:
/// -
/// - `exp()`
/// - `expMinusOne()`
/// - `exp10()`
/// - `log2()`
/// - `pow()`
/// See also `exp()`, `expMinusOne()`, `exp10()`, `log2()` and `pow()`.
static func exp2(_ x: Self) -> Self
/// 10^x
///
/// See also:
/// -
/// - `exp()`
/// - `expMinusOne()`
/// - `exp2()`
/// - `log10()`
/// - `pow()`
/// See also `exp()`, `expMinusOne()`, `exp2()`, `log10()` and `pow()`.
static func exp10(_ x: Self) -> Self
/// `sqrt(x*x + y*y)`, computed in a manner that avoids spurious overflow or underflow.
/// `sqrt(x*x + y*y)`, computed in a manner that avoids spurious overflow or
/// underflow.
static func hypot(_ x: Self, _ y: Self) -> Self
/// The gamma function Γ(x).
///
/// See also:
/// -
/// - `logGamma()`
/// - `signGamma()`
/// See also `logGamma()` and `signGamma()`.
static func gamma(_ x: Self) -> Self
/// The base-2 logarithm of `x`.
///
/// See also:
/// -
/// - `exp2()`
/// - `log()`
/// - `log(onePlus:)`
/// - `log10()`
/// See also `exp2()`, `log()`, `log(onePlus:)` and `log10()`.
static func log2(_ x: Self) -> Self
/// The base-10 logarithm of `x`.
///
/// See also:
/// -
/// - `exp10()`
/// - `log()`
/// - `log(onePlus:)`
/// - `log2()`
/// See also: `exp10()`, `log()`, `log(onePlus:)` and `log2()`.
static func log10(_ x: Self) -> Self
#if !os(Windows)
@@ -89,27 +59,21 @@ public protocol RealFunctions: ElementaryFunctions {
///
/// Not available on Windows targets.
///
/// See also:
/// -
/// - `gamma()`
/// - `signGamma()`
/// See also `gamma()` and `signGamma()`.
static func logGamma(_ x: Self) -> Self
/// The sign of the gamma function, Γ(x).
///
/// For `x >= 0`, `signGamma(x)` is `.plus`. For negative `x`, `signGamma(x)` is `.plus`
/// when `x` is an integer, and otherwise it is `.minus` whenever `trunc(x)` is even, and `.plus`
/// when `trunc(x)` is odd.
/// For `x >= 0`, `signGamma(x)` is `.plus`. For negative `x`, `signGamma(x)`
/// is `.plus` when `x` is an integer, and otherwise it is `.minus` whenever
/// `trunc(x)` is even, and `.plus` when `trunc(x)` is odd.
///
/// This function is used together with `logGamma`, which computes the logarithm of the
/// absolute value of Γ(x), to recover the sign information.
/// This function is used together with `logGamma`, which computes the
/// logarithm of the absolute value of Γ(x), to recover the sign information.
///
/// Not available on Windows targets.
///
/// See also:
/// -
/// - `gamma()`
/// - `logGamma()`
/// See also `gamma()` and `logGamma()`.
static func signGamma(_ x: Self) -> FloatingPointSign
#endif
}
@@ -0,0 +1,82 @@
//===--- RelaxedArithmetic.swift ------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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
/// A namespace for "relaxed arithmetic" operations for types conforming to
/// `AlgebraicField`.
public enum Relaxed { }
extension Relaxed {
/// a+b with the optimizer licensed to reassociate expressions and form FMAs.
///
/// Floating-point addition is not an associative operation, so the Swift
/// compiler does not have any flexibility in how it evaluates an expression
/// like:
/// ```
/// func sum(array: [Float]) -> Float {
/// array.reduce(0, +)
/// }
/// ```
/// Using `Relaxed.sum` instead of `+` permits the compiler to reorder the
/// terms in the summation, which unlocks loop unrolling and vectorization.
/// In a benchmark, simply using `Relaxed.sum` provides about an 8x speedup
/// for release builds, without any unsafe flags or other optimizations.
/// Further improvement should be possible by improving LLVM optimizations
/// or adding attributes to license more aggressive unrolling and taking
/// advantage of vector ISA extensions for swift.
///
/// If you want to compute `a-b` with relaxed semantics, use
/// `Relaxed.sum(a, -b)`.
///
/// If a type or toolchain does not support reassociation for optimization
/// purposes, this operation decays to a normal addition; it is a license
/// for the compiler to optimize, not a guarantee that any change occurs.
@_transparent
public static func sum<T: AlgebraicField>(_ a: T, _ b: T) -> T {
T._relaxedAdd(a, b)
}
/// a*b with the optimizer licensed to reassociate expressions and form FMAs.
///
/// Floating-point addition and multiplication are not associative operations,
/// so the Swift compiler does not have any flexibility in how it evaluates
/// an expression like:
/// ```
/// func sumOfSquares(array: [Float]) -> Float {
/// array.reduce(0) { $0 + $1*$1 }
/// }
/// ```
/// Using `Relaxed.sum` and `Relaxed.product` instead of `+` and `*` permits
/// the compiler to reorder the terms in the summation, which unlocks loop
/// unrolling and vectorization, and form fused multiply-adds, which allows
/// us to achieve twice the throughput on some hardware.
///
/// If a type or toolchain does not support reassociation for optimization
/// purposes, this operation decays to a normal multiplication; it is a
/// license for the compiler to optimize, not a guarantee that any change
/// occurs.
@_transparent
public static func product<T: AlgebraicField>(_ a: T, _ b: T) -> T {
T._relaxedMul(a, b)
}
}
extension Relaxed {
/// a*b + c, computed _either_ with an FMA or with separate multiply and add,
/// whichever is fastest according to the optimizer's heuristics.
@_transparent
public static func multiplyAdd<T: AlgebraicField>(
_ a: T, _ b: T, _ c: T
) -> T {
T._relaxedAdd(c, T._relaxedMul(a, b))
}
}
+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_library(_NumericsShims INTERFACE)
target_include_directories(_NumericsShims INTERFACE
include)
target_link_libraries(_NumericsShims INTERFACE
$<$<PLATFORM_ID:Linux>:m>)
set_property(GLOBAL APPEND PROPERTY SWIFT_NUMERICS_EXPORTS _NumericsShims)
File renamed without changes.
@@ -16,4 +16,4 @@
// If any shims are added that are not pure header inlines, whatever runtime
// support they require can be added to this file.
#include "NumericsShims.h"
#include "_NumericsShims.h"
@@ -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,20 +382,71 @@ HEADER_SHIM long double libm_lgammal(long double x, int *signp) {
}
#endif
// MARK: - shims to import C complex operations for timing purposes
// MARK: - math inlines with relaxed semantics to support optimization.
#define CLANG_RELAX_FP _Pragma("clang fp reassociate(on) contract(fast)")
typedef struct { double real; double imag; } CComplex;
HEADER_SHIM CComplex libm_cdiv(CComplex z, CComplex w) {
double _Complex a = { z.real, z.imag };
double _Complex b = { w.real, w.imag };
double _Complex c = a/b;
return (CComplex){ __real__ c, __imag__ c };
#if !(__i386__ || __x86_64__)
/// a + b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM _Float16 _numerics_relaxed_addf16(_Float16 a, _Float16 b) {
CLANG_RELAX_FP
return a + b;
}
HEADER_SHIM CComplex libm_cmul(CComplex z, CComplex w) {
double _Complex a = { z.real, z.imag };
double _Complex b = { w.real, w.imag };
double _Complex c = a*b;
return (CComplex){ __real__ c, __imag__ c };
/// a * b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM _Float16 _numerics_relaxed_mulf16(_Float16 a, _Float16 b) {
CLANG_RELAX_FP
return a * b;
}
#endif
/// a + b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM float _numerics_relaxed_addf(float a, float b) {
CLANG_RELAX_FP
return a + b;
}
/// a * b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM float _numerics_relaxed_mulf(float a, float b) {
CLANG_RELAX_FP
return a * b;
}
/// a + b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM double _numerics_relaxed_add(double a, double b) {
CLANG_RELAX_FP
return a + b;
}
/// a * b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM double _numerics_relaxed_mul(double a, double b) {
CLANG_RELAX_FP
return a * b;
}
#if !defined _WIN32 && (defined __i386__ || defined __x86_64__)
/// a + b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM long double _numerics_relaxed_addl(long double a, long double b) {
CLANG_RELAX_FP
return a + b;
}
/// a * b with the "allow reassociation" and "allow FMA formation" flags
/// set in the IR.
HEADER_SHIM long double _numerics_relaxed_mull(long double a, long double b) {
CLANG_RELAX_FP
return a * b;
}
#endif
HEADER_SHIM void _numerics_optimization_barrier(const void *pointer) {
__asm("": :"r" (pointer));
}
#undef CLANG_RELAX_FP
@@ -0,0 +1,3 @@
module _NumericsShims {
header "_NumericsShims.h"
}
+19
View File
@@ -0,0 +1,19 @@
//===--- BlackHole.swift --------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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
@_transparent
public func blackHole<T>(_ thing: T) {
withUnsafePointer(to: thing) {
_numerics_optimization_barrier($0)
}
}
+23
View File
@@ -0,0 +1,23 @@
#[[
This source file is part of the Swift Numerics open source project
Copyright (c) 2019-2021 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
BlackHole.swift
DoubleWidth.swift
Error.swift
Interval.swift
RealTestSupport.swift)
set_target_properties(_TestSupport PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
target_link_libraries(_TestSupport PUBLIC
Numerics)
_install_target(_TestSupport)
set_property(GLOBAL APPEND PROPERTY SWIFT_NUMERICS_EXPORTS _TestSupport)
+756
View File
@@ -0,0 +1,756 @@
//===--- DoubleWidth.swift ------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2017-2021 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 fixed-width integer that has twice the bit width of its base type.
///
/// You can use the `DoubleWidth` type to continue calculations with the result
/// of a full width arithmetic operation. Normally, when you perform a full
/// width operation, the result is a tuple of the high and low parts of the
/// result.
///
/// let a = 2241543570477705381
/// let b = 186319822866995413
/// let c = a.multipliedFullWidth(by: b)
/// // c == (high: 22640526660490081, low: 7959093232766896457)
///
/// The tuple `c` can't be used in any further comparisons or calculations. To
/// use this value, create a `DoubleWidth` instance from the result. You can
/// use the `DoubleWidth` instance in the same way that you would use any other
/// integer type.
///
/// let d = DoubleWidth(a.multipliedFullWidth(by: b))
/// // d == 417644001000058515200174966092417353
///
/// // Check the calculation:
/// print(d / DoubleWidth(a) == b)
/// // Prints "true"
///
/// if d > Int.max {
/// print("Too big to be an 'Int'!")
/// } else {
/// print("Small enough to fit in an 'Int'")
/// }
/// // Prints "Too big to be an 'Int'!"
///
/// The `DoubleWidth` type is not intended as a replacement for a variable-width
/// integer type. Nesting `DoubleWidth` instances, in particular, may result in
/// undesirable performance.
public struct DoubleWidth<Base : FixedWidthInteger> {
public typealias High = Base
public typealias Low = Base.Magnitude
internal var _storage: (low: Low, high: High)
}
extension DoubleWidth {
/// The "high word" of this value.
///
/// Equivalent to `Base(self >> Base.bitWidth)`.
public var high: High {
return _storage.high
}
/// The "low word" of the value.
///
/// Equivalent to`Base.Magnitude(truncatingIfNecessary: self)`.
public var low: Low {
return _storage.low
}
/// Creates a new instance from the given tuple of high and low parts.
///
/// Equivalent to
/// ```
/// DoubleWidth<Base>(high) << Base.bitWidth + DoubleWidth<Base>(low)
/// ```
///
/// - Parameter value: The tuple to use as the source of the new instance's
/// high and low parts.
public init(_ value: (high: High, low: Low)) {
self._storage = (low: value.low, high: value.high)
}
// We expect users to invoke the public initializer above as demonstrated in
// the documentation (that is, by passing in the result of a full width
// operation).
//
// Internally, we'll need to create new instances by supplying high and low
// parts directly; ((double parentheses)) greatly impair readability,
// especially when nested:
//
// DoubleWidth<DoubleWidth>((DoubleWidth((0, 0)), DoubleWidth((0, 0))))
//
// For that reason, we'll include an internal initializer that takes two
// separate arguments.
/// Creates a new instance from the given tuple of high and low parts.
///
/// Equivalent to
/// ```
/// DoubleWidth<Base>(high) << Base.bitWidth + DoubleWidth<Base>(low)
/// ```
internal init(_ _high: High, _ low: Low) {
self.init((_high, low))
}
/// Zero.
public init() {
self.init(0, 0)
}
}
extension DoubleWidth : CustomStringConvertible {
public var description: String {
return String(self, radix: 10)
}
}
extension DoubleWidth : CustomDebugStringConvertible {
public var debugDescription: String {
return "(\(_storage.high), \(_storage.low))"
}
}
extension DoubleWidth : Equatable {
public static func ==(lhs: DoubleWidth, rhs: DoubleWidth) -> Bool {
return lhs._storage.low == rhs._storage.low
&& lhs._storage.high == rhs._storage.high
}
}
extension DoubleWidth : Comparable {
public static func <(lhs: DoubleWidth, rhs: DoubleWidth) -> Bool {
if lhs._storage.high < rhs._storage.high { return true }
else if lhs._storage.high > rhs._storage.high { return false }
else { return lhs._storage.low < rhs._storage.low }
}
}
extension DoubleWidth : Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(low)
hasher.combine(high)
}
}
extension DoubleWidth : Numeric {
public typealias Magnitude = DoubleWidth<Low>
public var magnitude: Magnitude {
let result = Magnitude(Low(truncatingIfNeeded: _storage.high), _storage.low)
if Base.isSigned && _storage.high < (0 as High) {
return ~result &+ 1
} else {
return result
}
}
internal init(_ _magnitude: Magnitude) {
self.init(High(_magnitude._storage.high), _magnitude._storage.low)
}
public init<T : BinaryInteger>(_ source: T) {
guard let result = DoubleWidth<Base>(exactly: source) else {
preconditionFailure("Value is outside the representable range")
}
self = result
}
public init?<T : BinaryInteger>(exactly source: T) {
// Can't represent a negative 'source' if Base is unsigned.
guard DoubleWidth.isSigned || source >= 0 else { return nil }
// Is 'source' entirely representable in Low?
if let low = Low(exactly: source.magnitude) {
self.init(source < (0 as T) ? (~0, ~low &+ 1) : (0, low))
} else {
// At this point we know source.bitWidth > Base.bitWidth, or else we
// would've taken the first branch.
let lowInT = source & T(~0 as Low)
let highInT = source >> Low.bitWidth
let low = Low(lowInT)
guard let high = High(exactly: highInT) else { return nil }
self.init(high, low)
}
}
}
extension DoubleWidth {
public struct Words {
public var _high: High.Words
public var _low: Low.Words
public init(_ value: DoubleWidth<Base>) {
// Multiples of word size only.
guard Base.bitWidth == Base.Magnitude.bitWidth &&
(UInt.bitWidth % Base.bitWidth == 0 ||
Base.bitWidth % UInt.bitWidth == 0) else {
fatalError("Access to words is not supported on this type")
}
self._high = value._storage.high.words
self._low = value._storage.low.words
assert(!_low.isEmpty)
}
}
}
extension DoubleWidth.Words: RandomAccessCollection {
public typealias Index = Int
public var startIndex: Index {
return 0
}
public var endIndex: Index {
return count
}
public var count: Int {
if Base.bitWidth < UInt.bitWidth { return 1 }
return _low.count + _high.count
}
public subscript(_ i: Index) -> UInt {
if Base.bitWidth < UInt.bitWidth {
precondition(i == 0, "Invalid index")
assert(2 * Base.bitWidth <= UInt.bitWidth)
return _low.first! | (_high.first! &<< Base.bitWidth._lowWord)
}
if i < _low.count {
return _low[i + _low.startIndex]
}
return _high[i - _low.count + _high.startIndex]
}
}
extension DoubleWidth : FixedWidthInteger {
public var words: Words {
return Words(self)
}
public static var isSigned: Bool {
return Base.isSigned
}
public static var max: DoubleWidth {
return self.init(High.max, Low.max)
}
public static var min: DoubleWidth {
return self.init(High.min, Low.min)
}
public static var bitWidth: Int {
return High.bitWidth + Low.bitWidth
}
public func addingReportingOverflow(_ rhs: DoubleWidth)
-> (partialValue: DoubleWidth, overflow: Bool) {
let (low, lowOverflow) =
_storage.low.addingReportingOverflow(rhs._storage.low)
let (high, highOverflow) =
_storage.high.addingReportingOverflow(rhs._storage.high)
let result = (high &+ (lowOverflow ? 1 : 0), low)
let overflow = highOverflow ||
high == Base.max && lowOverflow
return (partialValue: DoubleWidth(result), overflow: overflow)
}
public func subtractingReportingOverflow(_ rhs: DoubleWidth)
-> (partialValue: DoubleWidth, overflow: Bool) {
let (low, lowOverflow) =
_storage.low.subtractingReportingOverflow(rhs._storage.low)
let (high, highOverflow) =
_storage.high.subtractingReportingOverflow(rhs._storage.high)
let result = (high &- (lowOverflow ? 1 : 0), low)
let overflow = highOverflow ||
high == Base.min && lowOverflow
return (partialValue: DoubleWidth(result), overflow: overflow)
}
public func multipliedReportingOverflow(
by rhs: DoubleWidth
) -> (partialValue: DoubleWidth, overflow: Bool) {
let (carry, product) = multipliedFullWidth(by: rhs)
let result = DoubleWidth(truncatingIfNeeded: product)
let isNegative = DoubleWidth.isSigned &&
(self < (0 as DoubleWidth)) != (rhs < (0 as DoubleWidth))
let didCarry = isNegative
? carry != ~(0 as DoubleWidth)
: carry != (0 as DoubleWidth)
let hadPositiveOverflow =
DoubleWidth.isSigned && !isNegative && product.leadingZeroBitCount == 0
return (result, didCarry || hadPositiveOverflow)
}
public func quotientAndRemainder(
dividingBy other: DoubleWidth
) -> (quotient: DoubleWidth, remainder: DoubleWidth) {
let (quotient, remainder) =
Magnitude._divide(self.magnitude, by: other.magnitude)
guard DoubleWidth.isSigned else {
return (DoubleWidth(quotient), DoubleWidth(remainder))
}
let isNegative = (self.high < (0 as High)) != (other.high < (0 as High))
let quotient_ = isNegative
? quotient == DoubleWidth.min.magnitude
? DoubleWidth.min
: 0 - DoubleWidth(quotient)
: DoubleWidth(quotient)
let remainder_ = self.high < (0 as High)
? 0 - DoubleWidth(remainder)
: DoubleWidth(remainder)
return (quotient_, remainder_)
}
public func dividedReportingOverflow(
by other: DoubleWidth
) -> (partialValue: DoubleWidth, overflow: Bool) {
if other == (0 as DoubleWidth) { return (self, true) }
if DoubleWidth.isSigned && other == -1 && self == .min {
return (self, true)
}
return (quotientAndRemainder(dividingBy: other).quotient, false)
}
public func remainderReportingOverflow(
dividingBy other: DoubleWidth
) -> (partialValue: DoubleWidth, overflow: Bool) {
if other == (0 as DoubleWidth) { return (self, true) }
if DoubleWidth.isSigned && other == -1 && self == .min { return (0, true) }
return (quotientAndRemainder(dividingBy: other).remainder, false)
}
public func multipliedFullWidth(
by other: DoubleWidth
) -> (high: DoubleWidth, low: DoubleWidth.Magnitude) {
let isNegative = DoubleWidth.isSigned &&
(self < (0 as DoubleWidth)) != (other < (0 as DoubleWidth))
func mul(_ x: Low, _ y: Low) -> (partial: Low, carry: Low) {
let (high, low) = x.multipliedFullWidth(by: y)
return (low, high)
}
func sum(_ x: Low, _ y: Low, _ z: Low) -> (partial: Low, carry: Low) {
let (sum1, overflow1) = x.addingReportingOverflow(y)
let (sum2, overflow2) = sum1.addingReportingOverflow(z)
let carry: Low = (overflow1 ? 1 : 0) + (overflow2 ? 1 : 0)
return (sum2, carry)
}
let lhs = self.magnitude
let rhs = other.magnitude
let a = mul(rhs._storage.low, lhs._storage.low)
let b = mul(rhs._storage.low, lhs._storage.high)
let c = mul(rhs._storage.high, lhs._storage.low)
let d = mul(rhs._storage.high, lhs._storage.high)
let mid1 = sum(a.carry, b.partial, c.partial)
let mid2 = sum(b.carry, c.carry, d.partial)
let low =
DoubleWidth<Low>(mid1.partial, a.partial)
let (sum_, overflow_) =
mid1.carry.addingReportingOverflow(mid2.partial)
let high =
DoubleWidth(High(mid2.carry + d.carry + (overflow_ ? 1 : 0)), sum_)
if isNegative {
let (lowComplement, overflow) = (~low).addingReportingOverflow(1)
return (~high + (overflow ? 1 : 0 as DoubleWidth), lowComplement)
} else {
return (high, low)
}
}
public func dividingFullWidth(
_ dividend: (high: DoubleWidth, low: DoubleWidth.Magnitude)
) -> (quotient: DoubleWidth, remainder: DoubleWidth) {
let other = DoubleWidth<DoubleWidth>(dividend)
let (quotient, remainder) =
Magnitude._divide(other.magnitude, by: self.magnitude)
guard DoubleWidth.isSigned else {
return (DoubleWidth(quotient), DoubleWidth(remainder))
}
let isNegative =
(self.high < (0 as High)) != (other.high.high < (0 as High))
let quotient_ = isNegative
? quotient == DoubleWidth.min.magnitude
? DoubleWidth.min
: 0 - DoubleWidth(quotient)
: DoubleWidth(quotient)
let remainder_ = other.high.high < (0 as High)
? 0 - DoubleWidth(remainder)
: DoubleWidth(remainder)
return (quotient_, remainder_)
}
public static func &=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
lhs._storage.low &= rhs._storage.low
lhs._storage.high &= rhs._storage.high
}
public static func |=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
lhs._storage.low |= rhs._storage.low
lhs._storage.high |= rhs._storage.high
}
public static func ^=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
lhs._storage.low ^= rhs._storage.low
lhs._storage.high ^= rhs._storage.high
}
public static func <<=(lhs: inout DoubleWidth, rhs: DoubleWidth) {
if DoubleWidth.isSigned && rhs < (0 as DoubleWidth) {
lhs >>= 0 - rhs
return
}
// Shift is larger than this type's bit width.
if rhs._storage.high != (0 as High) ||
rhs._storage.low >= DoubleWidth.bitWidth
{
lhs = 0
return
}
lhs &<<= rhs
}
public static func >>=(lhs: inout DoubleWidth, rhs: DoubleWidth) {
if DoubleWidth.isSigned && rhs < (0 as DoubleWidth) {
lhs <<= 0 - rhs
return
}
// Shift is larger than this type's bit width.
if rhs._storage.high != (0 as High) ||
rhs._storage.low >= DoubleWidth.bitWidth
{
lhs = lhs < (0 as DoubleWidth) ? ~0 : 0
return
}
lhs &>>= rhs
}
/// Returns this value "masked" by its bit width.
///
/// "Masking" notionally involves repeatedly incrementing or decrementing this
/// value by `self.bitWidth` until the result is contained in the range
/// `0..<self.bitWidth`.
internal func _masked() -> DoubleWidth {
// FIXME(integers): test types with bit widths that aren't powers of 2
if DoubleWidth.bitWidth.nonzeroBitCount == 1 {
return self & DoubleWidth(DoubleWidth.bitWidth &- 1)
}
if DoubleWidth.isSigned && self._storage.high < (0 as High) {
return self % DoubleWidth(DoubleWidth.bitWidth) + self
}
return self % DoubleWidth(DoubleWidth.bitWidth)
}
public static func &<<=(lhs: inout DoubleWidth, rhs: DoubleWidth) {
let rhs = rhs._masked()
guard rhs._storage.low < Base.bitWidth else {
lhs._storage.high = High(
truncatingIfNeeded: lhs._storage.low &<<
(rhs._storage.low &- Low(Base.bitWidth)))
lhs._storage.low = 0
return
}
guard rhs._storage.low != (0 as Low) else { return }
lhs._storage.high &<<= High(rhs._storage.low)
lhs._storage.high |= High(
truncatingIfNeeded: lhs._storage.low &>>
(Low(Base.bitWidth) &- rhs._storage.low))
lhs._storage.low &<<= rhs._storage.low
}
public static func &>>=(lhs: inout DoubleWidth, rhs: DoubleWidth) {
let rhs = rhs._masked()
guard rhs._storage.low < Base.bitWidth else {
lhs._storage.low = Low(
truncatingIfNeeded: lhs._storage.high &>>
High(rhs._storage.low &- Low(Base.bitWidth)))
lhs._storage.high = lhs._storage.high < (0 as High) ? ~0 : 0
return
}
guard rhs._storage.low != (0 as Low) else { return }
lhs._storage.low &>>= rhs._storage.low
lhs._storage.low |= Low(
truncatingIfNeeded: lhs._storage.high &<<
High(Low(Base.bitWidth) &- rhs._storage.low))
lhs._storage.high &>>= High(rhs._storage.low)
}
// FIXME(integers): remove this once the operators are back to Numeric
public static func + (
lhs: DoubleWidth, rhs: DoubleWidth
) -> DoubleWidth {
var lhs = lhs
lhs += rhs
return lhs
}
public static func +=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
let (result, overflow) = lhs.addingReportingOverflow(rhs)
precondition(!overflow, "Overflow in +=")
lhs = result
}
// FIXME(integers): remove this once the operators are back to Numeric
public static func - (
lhs: DoubleWidth, rhs: DoubleWidth
) -> DoubleWidth {
var lhs = lhs
lhs -= rhs
return lhs
}
public static func -=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
let (result, overflow) = lhs.subtractingReportingOverflow(rhs)
precondition(!overflow, "Overflow in -=")
lhs = result
}
// FIXME(integers): remove this once the operators are back to Numeric
public static func * (
lhs: DoubleWidth, rhs: DoubleWidth
) -> DoubleWidth {
var lhs = lhs
lhs *= rhs
return lhs
}
public static func *=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
let (result, overflow) = lhs.multipliedReportingOverflow(by:rhs)
precondition(!overflow, "Overflow in *=")
lhs = result
}
// FIXME(integers): remove this once the operators are back to Numeric
public static func / (
lhs: DoubleWidth, rhs: DoubleWidth
) -> DoubleWidth {
var lhs = lhs
lhs /= rhs
return lhs
}
public static func /=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
let (result, overflow) = lhs.dividedReportingOverflow(by:rhs)
precondition(!overflow, "Overflow in /=")
lhs = result
}
// FIXME(integers): remove this once the operators are back to Numeric
public static func % (
lhs: DoubleWidth, rhs: DoubleWidth
) -> DoubleWidth {
var lhs = lhs
lhs %= rhs
return lhs
}
public static func %=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
let (result, overflow) = lhs.remainderReportingOverflow(dividingBy:rhs)
precondition(!overflow, "Overflow in %=")
lhs = result
}
public init(_truncatingBits bits: UInt) {
_storage.low = Low(_truncatingBits: bits)
_storage.high = High(_truncatingBits: bits >> UInt(Low.bitWidth))
}
public init(integerLiteral x: Int) {
self.init(x)
}
public var leadingZeroBitCount: Int {
return high == (0 as High)
? High.bitWidth + low.leadingZeroBitCount
: high.leadingZeroBitCount
}
public var trailingZeroBitCount: Int {
return low == (0 as Low)
? Low.bitWidth + high.trailingZeroBitCount
: low.trailingZeroBitCount
}
public var nonzeroBitCount: Int {
return high.nonzeroBitCount + low.nonzeroBitCount
}
public var byteSwapped: DoubleWidth {
return DoubleWidth(
High(truncatingIfNeeded: low.byteSwapped),
Low(truncatingIfNeeded: high.byteSwapped))
}
}
extension DoubleWidth : UnsignedInteger where Base : UnsignedInteger {
/// Returns the quotient and remainder after dividing a triple-width magnitude
/// `lhs` by a double-width magnitude `rhs`.
///
/// This operation is conceptually that described by Burnikel and Ziegler
/// (1998).
internal static func _divide(
_ lhs: (high: Low, mid: Low, low: Low), by rhs: Magnitude
) -> (quotient: Low, remainder: Magnitude) {
// The following invariants are guaranteed to hold by dividingFullWidth or
// quotientAndRemainder before this method is invoked:
assert(rhs.leadingZeroBitCount == 0)
assert(Magnitude(lhs.high, lhs.mid) < rhs)
guard lhs.high != (0 as Low) else {
let lhs_ = Magnitude(lhs.mid, lhs.low)
return lhs_ < rhs ? (0, lhs_) : (1, lhs_ &- rhs)
}
// Estimate the quotient.
var quotient = lhs.high == rhs.high
? Low.max
: rhs.high.dividingFullWidth((lhs.high, lhs.mid)).quotient
// Compute quotient * rhs.
// TODO: This could be performed more efficiently.
var product =
DoubleWidth<Magnitude>(
0, Magnitude(quotient.multipliedFullWidth(by: rhs.low)))
let (x, y) = quotient.multipliedFullWidth(by: rhs.high)
product += DoubleWidth<Magnitude>(Magnitude(0, x), Magnitude(y, 0))
// Compute the remainder after decrementing quotient as necessary.
var remainder =
DoubleWidth<Magnitude>(
Magnitude(0, lhs.high), Magnitude(lhs.mid, lhs.low))
while remainder < product {
quotient = quotient &- 1
remainder += DoubleWidth<Magnitude>(0, rhs)
}
remainder -= product
return (quotient, remainder.low)
}
/// Returns the quotient and remainder after dividing a quadruple-width
/// magnitude `lhs` by a double-width magnitude `rhs`.
internal static func _divide(
_ lhs: DoubleWidth<Magnitude>, by rhs: Magnitude
) -> (quotient: Magnitude, remainder: Magnitude) {
guard _fastPath(rhs > (0 as Magnitude)) else {
fatalError("Division by zero")
}
guard _fastPath(rhs >= lhs.high) else {
fatalError("Division results in an overflow")
}
if lhs.high == (0 as Magnitude) {
return lhs.low.quotientAndRemainder(dividingBy: rhs)
}
if rhs.high == (0 as Low) {
let a = lhs.high.high % rhs.low
let b = a == (0 as Low)
? lhs.high.low % rhs.low
: rhs.low.dividingFullWidth((a, lhs.high.low)).remainder
let (x, c) = b == (0 as Low)
? lhs.low.high.quotientAndRemainder(dividingBy: rhs.low)
: rhs.low.dividingFullWidth((b, lhs.low.high))
let (y, d) = c == (0 as Low)
? lhs.low.low.quotientAndRemainder(dividingBy: rhs.low)
: rhs.low.dividingFullWidth((c, lhs.low.low))
return (Magnitude(x, y), Magnitude(0, d))
}
// Left shift both rhs and lhs, then divide and right shift the remainder.
let shift = rhs.leadingZeroBitCount
let rhs = rhs &<< shift
let lhs = lhs &<< shift
if lhs.high.high == (0 as Low)
&& Magnitude(lhs.high.low, lhs.low.high) < rhs {
let (quotient, remainder) =
Magnitude._divide((lhs.high.low, lhs.low.high, lhs.low.low), by: rhs)
return (Magnitude(0, quotient), remainder &>> shift)
}
let (x, a) =
Magnitude._divide((lhs.high.high, lhs.high.low, lhs.low.high), by: rhs)
let (y, b) =
Magnitude._divide((a.high, a.low, lhs.low.low), by: rhs)
return (Magnitude(x, y), b &>> shift)
}
/// Returns the quotient and remainder after dividing a double-width
/// magnitude `lhs` by a double-width magnitude `rhs`.
internal static func _divide(
_ lhs: Magnitude, by rhs: Magnitude
) -> (quotient: Magnitude, remainder: Magnitude) {
guard _fastPath(rhs > (0 as Magnitude)) else {
fatalError("Division by zero")
}
guard rhs < lhs else {
if _fastPath(rhs > lhs) { return (0, lhs) }
return (1, 0)
}
if lhs.high == (0 as Low) {
let (quotient, remainder) =
lhs.low.quotientAndRemainder(dividingBy: rhs.low)
return (Magnitude(quotient), Magnitude(remainder))
}
if rhs.high == (0 as Low) {
let (x, a) = lhs.high.quotientAndRemainder(dividingBy: rhs.low)
let (y, b) = a == (0 as Low)
? lhs.low.quotientAndRemainder(dividingBy: rhs.low)
: rhs.low.dividingFullWidth((a, lhs.low))
return (Magnitude(x, y), Magnitude(0, b))
}
// Left shift both rhs and lhs, then divide and right shift the remainder.
let shift = rhs.leadingZeroBitCount
// Note the use of `>>` instead of `&>>` below,
// as `high` should be zero if `shift` is zero.
let high = (lhs >> (Magnitude.bitWidth &- shift)).low
let rhs = rhs &<< shift
let lhs = lhs &<< shift
let (quotient, remainder) =
Magnitude._divide((high, lhs.high, lhs.low), by: rhs)
return (Magnitude(0, quotient), remainder &>> shift)
}
}
extension DoubleWidth : SignedNumeric, SignedInteger
where Base : SignedInteger {}
+32
View File
@@ -0,0 +1,32 @@
//===--- Error.swift ------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import ComplexModule
import RealModule
public func relativeError(_ tst: Float, _ ref: Double) -> Double {
let scale = max(ref.magnitude, Double(Float.leastNormalMagnitude))
let error = (Double(tst) - ref).magnitude
return error / scale
}
public func componentwiseError(_ tst: Complex<Float>, _ ref: Complex<Double>) -> Double {
return max(relativeError(tst.real, ref.real),
relativeError(tst.imaginary, ref.imaginary))
}
public func relativeError(_ tst: Complex<Float>, _ ref: Complex<Double>) -> Double {
let scale = max(ref.magnitude, Double(Float.leastNormalMagnitude))
let dtst = Complex(Double(tst.real), Double(tst.imaginary))
let error = (dtst - ref).magnitude
return error / scale
}
+51
View File
@@ -0,0 +1,51 @@
//===--- Interval.swift ---------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// A not-particularly-clever floating-point iterval that is iterable for the
// purposes of testing.
public struct Interval<Element>: Sequence where Element: FloatingPoint {
let lower: Element
let upper: Element
public init(from: Element, through: Element) {
precondition(from <= through)
lower = from
upper = through
}
public init(from: Element, to: Element) {
self.init(from: from, through: to.nextDown)
}
public func makeIterator() -> Iterator {
Iterator(self)
}
public struct Iterator: IteratorProtocol {
let interval: Interval
var nextOutput: Element?
init(_ interval: Interval) {
self.interval = interval
self.nextOutput = interval.lower
}
public mutating func next() -> Element? {
let result = nextOutput
if nextOutput == interval.upper { nextOutput = nil }
else { nextOutput = nextOutput?.nextUp }
return result
}
}
}
@@ -0,0 +1,33 @@
//===--- RealTestSupport.swift --------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import RealModule
public protocol FixedWidthFloatingPoint: BinaryFloatingPoint
where Exponent: FixedWidthInteger,
RawSignificand: FixedWidthInteger { }
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
extension Float16: FixedWidthFloatingPoint { }
#endif
extension Float: FixedWidthFloatingPoint { }
extension Double: FixedWidthFloatingPoint { }
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
extension Float80: FixedWidthFloatingPoint { }
#endif
extension FloatingPointSign {
static func random<G: RandomNumberGenerator>(using g: inout G) -> FloatingPointSign {
[.plus,.minus].randomElement(using: &g)!
}
}
+460
View File
@@ -0,0 +1,460 @@
//===--- BigIntTests.swift ------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import BigIntModule
import XCTest
extension BigInt {
static func fac(_ n: BigInt) -> BigInt {
precondition(n >= 0, "Factorial of a negative integer is undefined")
return stride(from: n, to: 1, by: -1).reduce(into: 1, { $0 *= $1 })
}
// inspired by https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms
static func pow(_ lhs: BigInt, _ rhs: BigInt) -> BigInt {
let bits_of_n = {
(n: BigInt) -> [Int] in
var bits: [Int] = []
var n = n
while n != 0 {
bits.append(Int(n % 2))
n /= 2
}
return bits
}
var r: BigInt = 1
for bit in bits_of_n(rhs).reversed() {
r *= r
if bit == 1 {
r *= lhs
}
}
return r
}
}
final class BigIntTests: XCTestCase {
/// Python: `bitWidth = 1024; -(2 ** (bitWidth - 1))`
static let descriptionInt1024Min: String =
"""
-89884656743115795386465259539451236680898848947115328636715040578866337902\
750481566354238661203768010560056939935696678829394884407208311246423715319\
737062188883946712432742638151109800623047059726541476042502884419075341171\
231440736956555270413618581675255342293149119973622969239858152417678164812\
112068608
"""
/// Python: `bitWidth = 1024; (2 ** (bitWidth - 1)) - 1`
static let descriptionInt1024Max: String =
"""
89884656743115795386465259539451236680898848947115328636715040578866337902\
750481566354238661203768010560056939935696678829394884407208311246423715319\
737062188883946712432742638151109800623047059726541476042502884419075341171\
231440736956555270413618581675255342293149119973622969239858152417678164812\
112068607
"""
/// Python: `numpy.base_repr(math.factorial(512), base=36)`
static let descriptionFactorial512_radix36: String =
"""
7FA5Y7EHR9XHMQ519MBHGYOF8XDYMUX8OZHO9WF1KCM0SSPXV2V45UA73BAFRYM2PFB8CZLTODV\
OS3QWA7PYFJ7WAFBI4VF371E27N6XZ4LGWHMFDS4ZH1O3DGNFG4YABUE1G90ORGRTIOGSQVZLSQ\
4TKHKHIQ262JVQ0J6LSKAPN5I65AJD33XODVHRNWJ1VSO0Q2FBOUNCPGQG2SFQKR17XHF1OLTV2\
MVNJVTDAIYWVJ9ZH7KXT0EPS00IGIVC7MNCU25HFWE37KNMSJQUL5ALUCE5XZVPFQCQGEVEB93B\
GA8LKG67PVZ7Q9QMQKIVNIMPT2973MVDTD1D1A0A4QT6NBZYR0TGSZXBV1PD0CHW4SKZJSLBS4Z\
W5WCKDY8BCQCE17KKADVLCTVSQL1BZ2PL52DDPB8S5L0ZEG2ZAZF9V4TNJJNO1D9U9JU7B264QZ\
5GLHC3Q0Y3BTECGTI8GRENQ2FV4HSEZKPM9OG302KLSY9MBCSOO0FN229AST84TT87LYWOOS71C\
54RPJ9RTO9875Z9DE3HPH89EW5I3SV219O04UU09A4KME7DD7IH49ABO79NR4EXFX1VLL4YOHSA\
7AHD1LS5YKZ66F4UPG0RCBGG000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000000000
"""
// MARK: - Basic arithmetic
func testDivision() {
let num1 = BigInt("18446744073709551616")!
let den1 = BigInt(123)
let expected1 = BigInt(UInt64(149973529054549200))
XCTAssertEqual(num1 / den1, expected1)
let num2 = BigInt.pow(BigInt(10), 100)
let den2: BigInt = 3
let expected2: BigInt = BigInt(String(repeating: "3", count: 100))!
let actual2 = num2 / den2
XCTAssertEqual(actual2, expected2)
let num3 = BigInt.pow(BigInt(10), 97)
let den3: BigInt = BigInt("33333333333333333333")!
let expected3: BigInt = BigInt("300000000000000000003000000000000000000030000000000000000000300000000000000000")!
let actual3 = num3 / den3
XCTAssertEqual(actual3, expected3)
let foo = BigInt("12345678901234567890123456789012345678901234567890123456789012345678901234567890")!
let bar = BigInt("351235231535161613134135135135")!
let baz = foo / bar
XCTAssertEqual(baz, BigInt("35149318157164029153358504918339691272847595997760")!)
XCTAssertNotNil(BigInt(exactly: 2.4e39))
XCTAssertNotNil(BigInt(exactly: 1e38))
XCTAssertEqual(BigInt(2.4e39) / BigInt(1e38), BigInt(24))
for _ in 0 ..< 100 {
let expected = BigInt(Float64.random(in: 0x1p64 ... 0x1p255))
let divisor = BigInt(Float64.random(in: 0x1p64 ... 0x1p128))
let (quotient, remainder) = expected.quotientAndRemainder(dividingBy: divisor)
let actual = divisor * quotient + remainder
XCTAssertEqual(quotient, expected / divisor)
XCTAssertEqual(remainder, expected % divisor)
XCTAssertEqual(
actual, expected,
"""
## FAILURE ##
~~~~~~~~~~~~~
actual: \(actual)
!= expected: \(expected)
~~~~~~~~~~~~~
divisor: \(divisor)
* quotient: \(quotient)
+ remainder: \(remainder)
~~~~~~~~~~~~~
""")
}
}
func testFactorial() {
var expectedNumber: BigInt?
var actualNumber: BigInt!
var actualString: String!
measure {
expectedNumber = BigInt(Self.descriptionFactorial512_radix36, radix: 36)
actualNumber = BigInt.fac(512)
actualString = String(actualNumber, radix: 36, uppercase: true)
}
XCTAssertEqual(actualNumber, expectedNumber)
XCTAssertEqual(actualString, Self.descriptionFactorial512_radix36)
XCTAssertEqual(BigInt.fac(0), 1)
XCTAssertEqual(BigInt.fac(1), 1)
XCTAssertEqual(BigInt.fac(2), 2)
XCTAssertEqual(BigInt.fac(3), 6)
XCTAssertEqual(BigInt.fac(4), 24)
XCTAssertEqual(BigInt.fac(5), 120)
XCTAssertEqual(BigInt.fac(6), 720)
XCTAssertEqual(BigInt.fac(7), 5040)
XCTAssertEqual(BigInt.fac(8), 40320)
XCTAssertEqual(BigInt.fac(9), 362880)
}
func testMath() {
let foo = BigInt.pow(10, 20)
let bar = BigInt("1234567890123456789012345678901234567890")!
let baz = foo + bar
XCTAssertEqual(baz, BigInt("1234567890123456789112345678901234567890")!)
let fooz = foo >> BigInt(10)
XCTAssertEqual(fooz, foo / 1024)
let barz = BigInt(1) << 64
XCTAssertEqual(barz, BigInt(UInt64.max) + 1)
}
func testNegation() {
let foo = BigInt("1234567890123456789012345678901234567890")!
let bar = BigInt(0) - foo
XCTAssertEqual(-foo, bar)
var baz = foo
baz.negate()
XCTAssertEqual(baz, bar)
}
func testSignum() {
XCTAssertEqual(BigInt(-0x1p1023).signum(), -1)
XCTAssertEqual(BigInt(Int64.min).signum(), -1)
XCTAssertEqual(BigInt(Int32.min).signum(), -1)
XCTAssertEqual(BigInt(Int16.min).signum(), -1)
XCTAssertEqual(BigInt(Int8.min).signum(), -1)
XCTAssertEqual(BigInt(-1).signum(), -1)
XCTAssertEqual(BigInt(0).signum(), 0)
XCTAssertEqual(BigInt(+1).signum(), +1)
XCTAssertEqual(BigInt(Int8.max).signum(), +1)
XCTAssertEqual(BigInt(Int16.max).signum(), +1)
XCTAssertEqual(BigInt(Int32.max).signum(), +1)
XCTAssertEqual(BigInt(Int64.max).signum(), +1)
XCTAssertEqual(BigInt(+0x1p1023).signum(), +1)
}
func testTrailingZeroCount() {
let foo = BigInt(1) << 300
XCTAssertEqual(foo.trailingZeroBitCount, 300)
let bar = (BigInt(1) << 300) + 0b101000
XCTAssertEqual(bar.trailingZeroBitCount, 3)
}
// MARK: - Comparing and hashing
func testComparable() {
let foo = BigInt("1234567890123456789012345678901234567890")!
let bar = foo * foo
XCTAssertLessThan(foo, bar)
XCTAssertFalse(foo < foo)
XCTAssertFalse(bar < bar)
XCTAssertFalse(foo > foo)
XCTAssertFalse(bar > bar)
XCTAssertGreaterThan(bar, foo)
let baz = bar * -1
XCTAssertLessThan(baz, foo)
XCTAssertNotEqual(bar, baz)
XCTAssertFalse(baz < baz)
}
func testComparison() {
let foo = BigInt(-10)
let bar = BigInt(-20)
XCTAssert(foo > bar)
XCTAssert(bar < foo)
XCTAssert(foo == BigInt(-10))
let baz = BigInt.pow(foo, -bar)
XCTAssertEqual(baz, BigInt("100000000000000000000")!)
}
func testExample() {
let bar = BigInt(exactly: -100)
XCTAssertNotNil(bar)
if let bar = bar {
XCTAssertLessThan(bar, 0)
XCTAssertGreaterThan(-bar, 0)
XCTAssertEqual(-bar, BigInt(100))
}
XCTAssertEqual(-BigInt("-1234567890123456789012345678901234567890")!,
+BigInt("+1234567890123456789012345678901234567890")!)
}
func testHashable() {
let foo = BigInt("1234567890123456789012345678901234567890")!
let bar = BigInt("1234567890123456789112345678901234567890")!
let baz: BigInt = 153
let dict = [ foo: "Hello", bar: "World", baz: "!" ]
let hash = foo.hashValue
print(hash)
XCTAssertEqual(dict[foo]!, "Hello")
XCTAssertEqual(dict[bar]!, "World")
}
func testClampingConversion() {
XCTAssertEqual(BigInt(clamping: UInt64.max), BigInt(UInt64(18446744073709551615)))
}
func testUIntConversion() {
let foo = BigInt(UInt.max)
XCTAssertNotEqual(foo, BigInt(-1))
let bar = BigInt(bitPattern: UInt.max)
XCTAssertEqual(bar, BigInt(-1))
}
// MARK: - Converting to/from textual representations
func testCodable() throws {
let lowerBound = BigInt("-1234567890123456789012345678901234567890")!
let upperBound = BigInt("+1234567890123456789012345678901234567890")!
let expectedRange: Range<BigInt> = lowerBound ..< upperBound
let encoder = JSONEncoder()
let decoder = JSONDecoder()
let data = try encoder.encode(expectedRange)
let actualRange = try decoder.decode(Range<BigInt>.self, from: data)
XCTAssertEqual(actualRange, expectedRange)
}
func testCustomStringConvertible() {
XCTAssertEqual("\(BigInt(UInt64.min) - 2)", "-2")
XCTAssertEqual("\(BigInt(UInt64.min) - 1)", "-1")
XCTAssertEqual("\(BigInt(UInt64.min) + 0)", "0")
XCTAssertEqual("\(BigInt(UInt64.min) + 1)", "1")
XCTAssertEqual("\(BigInt(UInt64.min) + 2)", "2")
XCTAssertEqual("\(BigInt(UInt64.max) - 2)", "18446744073709551613")
XCTAssertEqual("\(BigInt(UInt64.max) - 1)", "18446744073709551614")
XCTAssertEqual("\(BigInt(UInt64.max) + 0)", "18446744073709551615")
XCTAssertEqual("\(BigInt(UInt64.max) + 1)", "18446744073709551616")
XCTAssertEqual("\(BigInt(UInt64.max) + 2)", "18446744073709551617")
XCTAssertEqual("\(BigInt(Int64.min) - 2)", "-9223372036854775810")
XCTAssertEqual("\(BigInt(Int64.min) - 1)", "-9223372036854775809")
XCTAssertEqual("\(BigInt(Int64.min) + 0)", "-9223372036854775808")
XCTAssertEqual("\(BigInt(Int64.min) + 1)", "-9223372036854775807")
XCTAssertEqual("\(BigInt(Int64.min) + 2)", "-9223372036854775806")
XCTAssertEqual("\(BigInt(Int64.max) - 2)", "9223372036854775805")
XCTAssertEqual("\(BigInt(Int64.max) - 1)", "9223372036854775806")
XCTAssertEqual("\(BigInt(Int64.max) + 0)", "9223372036854775807")
XCTAssertEqual("\(BigInt(Int64.max) + 1)", "9223372036854775808")
XCTAssertEqual("\(BigInt(Int64.max) + 2)", "9223372036854775809")
XCTAssertEqual("\(-(BigInt(1) << 1023))", Self.descriptionInt1024Min)
XCTAssertEqual("\(+(BigInt(1) << 1023) - 1)", Self.descriptionInt1024Max)
}
func testLosslessStringConvertible() {
XCTAssertNil(BigInt(""))
XCTAssertNil(BigInt("-"))
XCTAssertNil(BigInt("+"))
XCTAssertNil(BigInt("A"))
XCTAssertNil(BigInt(" 0"))
XCTAssertNil(BigInt("0 "))
XCTAssertEqual(BigInt(UInt64.min) - 2, BigInt("-2"))
XCTAssertEqual(BigInt(UInt64.min) - 1, BigInt("-1"))
XCTAssertEqual(BigInt(UInt64.min) + 0, BigInt("0"))
XCTAssertEqual(BigInt(UInt64.min) + 1, BigInt("1"))
XCTAssertEqual(BigInt(UInt64.min) + 2, BigInt("2"))
XCTAssertEqual(BigInt(UInt64.max) - 2, BigInt("18446744073709551613"))
XCTAssertEqual(BigInt(UInt64.max) - 1, BigInt("18446744073709551614"))
XCTAssertEqual(BigInt(UInt64.max) + 0, BigInt("18446744073709551615"))
XCTAssertEqual(BigInt(UInt64.max) + 1, BigInt("18446744073709551616"))
XCTAssertEqual(BigInt(UInt64.max) + 2, BigInt("18446744073709551617"))
XCTAssertEqual(BigInt(Int64.min) - 2, BigInt("-9223372036854775810"))
XCTAssertEqual(BigInt(Int64.min) - 1, BigInt("-9223372036854775809"))
XCTAssertEqual(BigInt(Int64.min) + 0, BigInt("-9223372036854775808"))
XCTAssertEqual(BigInt(Int64.min) + 1, BigInt("-9223372036854775807"))
XCTAssertEqual(BigInt(Int64.min) + 2, BigInt("-9223372036854775806"))
XCTAssertEqual(BigInt(Int64.max) - 2, BigInt("9223372036854775805"))
XCTAssertEqual(BigInt(Int64.max) - 1, BigInt("9223372036854775806"))
XCTAssertEqual(BigInt(Int64.max) + 0, BigInt("9223372036854775807"))
XCTAssertEqual(BigInt(Int64.max) + 1, BigInt("9223372036854775808"))
XCTAssertEqual(BigInt(Int64.max) + 2, BigInt("9223372036854775809"))
XCTAssertEqual(-(BigInt(1) << 1023), BigInt(Self.descriptionInt1024Min))
XCTAssertEqual(+(BigInt(1) << 1023) - 1, BigInt(Self.descriptionInt1024Max))
}
func testRadicesAndNumerals() {
for radix in 2 ... 36 {
for uppercase in [false, true] {
for _ in 0 ..< 100 {
let expectedNumber = BigInt(Int.random(in: .min ... .max))
let expectedString = String(expectedNumber,
radix: radix,
uppercase: uppercase)
let actualNumber = BigInt(expectedString, radix: radix)
XCTAssertEqual(actualNumber, expectedNumber)
if radix == 10 {
let actualString = expectedNumber.description
XCTAssertEqual(actualString, expectedString)
}
}
}
}
}
// MARK: - Converting from floating-point binary types
func testBinaryFloatingPoint<T>(_ type: T.Type) where T: BinaryFloatingPoint {
var expected = BigInt(T.greatestFiniteMagnitude.significandBitPattern)
expected |= BigInt(1) << T.significandBitCount
expected <<= T.greatestFiniteMagnitude.exponent
expected >>= T.significandBitCount
XCTAssertEqual(BigInt(exactly: -T.greatestFiniteMagnitude), -expected)
XCTAssertEqual(BigInt(exactly: +T.greatestFiniteMagnitude), +expected)
XCTAssertEqual(BigInt(-T.greatestFiniteMagnitude), -expected)
XCTAssertEqual(BigInt(+T.greatestFiniteMagnitude), +expected)
XCTAssertNil(BigInt(exactly: -T.infinity))
XCTAssertNil(BigInt(exactly: +T.infinity))
XCTAssertNil(BigInt(exactly: -T.leastNonzeroMagnitude))
XCTAssertNil(BigInt(exactly: +T.leastNonzeroMagnitude))
XCTAssertEqual(BigInt(-T.leastNonzeroMagnitude), 0)
XCTAssertEqual(BigInt(+T.leastNonzeroMagnitude), 0)
XCTAssertNil(BigInt(exactly: -T.leastNormalMagnitude))
XCTAssertNil(BigInt(exactly: +T.leastNormalMagnitude))
XCTAssertEqual(BigInt(-T.leastNormalMagnitude), 0)
XCTAssertEqual(BigInt(+T.leastNormalMagnitude), 0)
XCTAssertNil(BigInt(exactly: T.nan))
XCTAssertNil(BigInt(exactly: T.signalingNaN))
XCTAssertNil(BigInt(exactly: -T.pi))
XCTAssertNil(BigInt(exactly: +T.pi))
XCTAssertEqual(BigInt(-T.pi), -3)
XCTAssertEqual(BigInt(+T.pi), +3)
XCTAssertNil(BigInt(exactly: -T.ulpOfOne))
XCTAssertNil(BigInt(exactly: +T.ulpOfOne))
XCTAssertEqual(BigInt(-T.ulpOfOne), 0)
XCTAssertEqual(BigInt(+T.ulpOfOne), 0)
XCTAssertEqual(BigInt(exactly: -T.zero), 0)
XCTAssertEqual(BigInt(exactly: +T.zero), 0)
XCTAssertEqual(BigInt(-T.zero), 0)
XCTAssertEqual(BigInt(+T.zero), 0)
}
func testBinaryFloatingPoint() {
testBinaryFloatingPoint(Float32.self)
testBinaryFloatingPoint(Float64.self)
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
testBinaryFloatingPoint(Float80.self)
#endif
for _ in 0 ..< 100 {
let small = Float32.random(in: -10 ... +10)
XCTAssertEqual(BigInt(small), BigInt(Int64(small)))
let large = Float32.random(in: -0x1p23 ... +0x1p23)
XCTAssertEqual(BigInt(large), BigInt(Int64(large)))
}
for _ in 0 ..< 100 {
let small = Float64.random(in: -10 ... +10)
XCTAssertEqual(BigInt(small), BigInt(Int64(small)))
let large = Float64.random(in: -0x1p52 ... +0x1p52)
XCTAssertEqual(BigInt(large), BigInt(Int64(large)))
}
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
for _ in 0 ..< 100 {
let small = Float80.random(in: -10 ... +10)
XCTAssertEqual(BigInt(small), BigInt(Int64(small)))
let large = Float80.random(in: -0x1p63 ..< +0x1p63)
XCTAssertEqual(BigInt(large), BigInt(Int64(large)))
}
#endif
}
}
+360
View File
@@ -0,0 +1,360 @@
//===--- BigUIntTests.swift -----------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import BigIntModule
import XCTest
extension BigUInt {
static func fac(_ n: BigUInt) -> BigUInt {
return stride(from: n, to: 1, by: -1).reduce(into: 1, { $0 *= $1 })
}
// inspired by https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms
static func pow(_ lhs: BigUInt, _ rhs: BigUInt) -> BigUInt {
let bits_of_n = { (n: BigUInt) -> [Int] in
var bits: [Int] = []
var n = n
while n != 0 {
bits.append(Int(n % 2))
n /= 2
}
return bits
}
var r: BigUInt = 1
for bit in bits_of_n(rhs).reversed() {
r *= r
if bit == 1 {
r *= lhs
}
}
return r
}
}
final class BigUIntTests: XCTestCase {
/// Python: `bitWidth = 1024; -(2 ** (bitWidth - 1))`
static let descriptionInt1024Min: String =
"""
-89884656743115795386465259539451236680898848947115328636715040578866337902\
750481566354238661203768010560056939935696678829394884407208311246423715319\
737062188883946712432742638151109800623047059726541476042502884419075341171\
231440736956555270413618581675255342293149119973622969239858152417678164812\
112068608
"""
/// Python: `bitWidth = 1024; (2 ** (bitWidth - 1)) - 1`
static let descriptionInt1024Max: String =
"""
89884656743115795386465259539451236680898848947115328636715040578866337902\
750481566354238661203768010560056939935696678829394884407208311246423715319\
737062188883946712432742638151109800623047059726541476042502884419075341171\
231440736956555270413618581675255342293149119973622969239858152417678164812\
112068607
"""
/// Python: `numpy.base_repr(math.factorial(512), base=36)`
static let descriptionFactorial512_radix36: String =
"""
7FA5Y7EHR9XHMQ519MBHGYOF8XDYMUX8OZHO9WF1KCM0SSPXV2V45UA73BAFRYM2PFB8CZLTODV\
OS3QWA7PYFJ7WAFBI4VF371E27N6XZ4LGWHMFDS4ZH1O3DGNFG4YABUE1G90ORGRTIOGSQVZLSQ\
4TKHKHIQ262JVQ0J6LSKAPN5I65AJD33XODVHRNWJ1VSO0Q2FBOUNCPGQG2SFQKR17XHF1OLTV2\
MVNJVTDAIYWVJ9ZH7KXT0EPS00IGIVC7MNCU25HFWE37KNMSJQUL5ALUCE5XZVPFQCQGEVEB93B\
GA8LKG67PVZ7Q9QMQKIVNIMPT2973MVDTD1D1A0A4QT6NBZYR0TGSZXBV1PD0CHW4SKZJSLBS4Z\
W5WCKDY8BCQCE17KKADVLCTVSQL1BZ2PL52DDPB8S5L0ZEG2ZAZF9V4TNJJNO1D9U9JU7B264QZ\
5GLHC3Q0Y3BTECGTI8GRENQ2FV4HSEZKPM9OG302KLSY9MBCSOO0FN229AST84TT87LYWOOS71C\
54RPJ9RTO9875Z9DE3HPH89EW5I3SV219O04UU09A4KME7DD7IH49ABO79NR4EXFX1VLL4YOHSA\
7AHD1LS5YKZ66F4UPG0RCBGG000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000000000
"""
// MARK: - Basic arithmetic
func testDivision() {
let num1 = BigUInt("18446744073709551616")!
let den1 = BigUInt(123)
let expected1 = BigUInt(UInt64(149973529054549200))
XCTAssertEqual(num1 / den1, expected1)
let num2 = BigUInt.pow(BigUInt(10), 100)
let den2: BigUInt = 3
let expected2: BigUInt = BigUInt(String(repeating: "3", count: 100))!
let actual2 = num2 / den2
XCTAssertEqual(actual2, expected2)
let num3 = BigUInt.pow(BigUInt(10), 97)
let den3: BigUInt = BigUInt("33333333333333333333")!
let expected3: BigUInt = BigUInt("300000000000000000003000000000000000000030000000000000000000300000000000000000")!
let actual3 = num3 / den3
XCTAssertEqual(actual3, expected3)
let foo = BigUInt("12345678901234567890123456789012345678901234567890123456789012345678901234567890")!
let bar = BigUInt("351235231535161613134135135135")!
let baz = foo / bar
XCTAssertEqual(baz, BigUInt("35149318157164029153358504918339691272847595997760")!)
XCTAssertNotNil(BigUInt(exactly: 2.4e39))
XCTAssertNotNil(BigUInt(exactly: 1e38))
XCTAssertEqual(BigUInt(2.4e39) / BigUInt(1e38), BigUInt(24))
for _ in 0 ..< 100 {
let expected = BigUInt(Float64.random(in: 0x1p64 ... 0x1p255))
let divisor = BigUInt(Float64.random(in: 0x1p64 ... 0x1p128))
let (quotient, remainder) = expected.quotientAndRemainder(dividingBy: divisor)
let actual = divisor * quotient + remainder
XCTAssertEqual(quotient, expected / divisor)
XCTAssertEqual(remainder, expected % divisor)
XCTAssertEqual(
actual, expected,
"""
## FAILURE ##
~~~~~~~~~~~~~
actual: \(actual)
!= expected: \(expected)
~~~~~~~~~~~~~
divisor: \(divisor)
* quotient: \(quotient)
+ remainder: \(remainder)
~~~~~~~~~~~~~
""")
}
}
func testFactorial() {
var expectedNumber: BigUInt?
var actualNumber: BigUInt!
var actualString: String!
measure {
expectedNumber = BigUInt(Self.descriptionFactorial512_radix36, radix: 36)
actualNumber = BigUInt.fac(512)
actualString = String(actualNumber, radix: 36, uppercase: true)
}
XCTAssertEqual(actualNumber, expectedNumber)
XCTAssertEqual(actualString, Self.descriptionFactorial512_radix36)
XCTAssertEqual(BigUInt.fac(0), 1)
XCTAssertEqual(BigUInt.fac(1), 1)
XCTAssertEqual(BigUInt.fac(2), 2)
XCTAssertEqual(BigUInt.fac(3), 6)
XCTAssertEqual(BigUInt.fac(4), 24)
XCTAssertEqual(BigUInt.fac(5), 120)
XCTAssertEqual(BigUInt.fac(6), 720)
XCTAssertEqual(BigUInt.fac(7), 5040)
XCTAssertEqual(BigUInt.fac(8), 40320)
XCTAssertEqual(BigUInt.fac(9), 362880)
}
func testMath() {
let foo = BigUInt.pow(10, 20)
let bar = BigUInt("1234567890123456789012345678901234567890")!
let baz = foo + bar
XCTAssertEqual(baz, BigUInt("1234567890123456789112345678901234567890")!)
let fooz = foo >> BigUInt(10)
XCTAssertEqual(fooz, foo / 1024)
let barz = BigUInt(1) << 64
XCTAssertEqual(barz, BigUInt(UInt64.max) + 1)
}
func testTrailingZeroCount() {
let foo = BigUInt(1) << 300
XCTAssertEqual(foo.trailingZeroBitCount, 300)
let bar = (BigUInt(1) << 300) + 0b101000
XCTAssertEqual(bar.trailingZeroBitCount, 3)
}
// MARK: - Comparing and hashing
func testComparable() {
let foo = BigUInt("1234567890123456789012345678901234567890")!
let bar = foo * foo
XCTAssertLessThan(foo, bar)
XCTAssertFalse(foo < foo)
XCTAssertFalse(bar < bar)
XCTAssertFalse(foo > foo)
XCTAssertFalse(bar > bar)
XCTAssertGreaterThan(bar, foo)
}
func testHashable() {
let foo = BigInt("1234567890123456789012345678901234567890")!
let bar = BigInt("1234567890123456789112345678901234567890")!
let baz: BigInt = 153
let dict = [foo: "Hello", bar: "World", baz: "!"]
let hash = foo.hashValue
print(hash)
XCTAssertEqual(dict[foo]!, "Hello")
XCTAssertEqual(dict[bar]!, "World")
}
func testClampingConversion() {
XCTAssertEqual(BigUInt(clamping: UInt64.max), BigUInt(UInt64(18446744073709551615)))
}
// MARK: - Converting to/from textual representations
func testCodable() throws {
let lowerBound = BigUInt("0")!
let upperBound = BigUInt("+1234567890123456789012345678901234567890")!
let expectedRange: Range<BigUInt> = lowerBound ..< upperBound
let encoder = JSONEncoder()
let decoder = JSONDecoder()
let data = try encoder.encode(expectedRange)
let actualRange = try decoder.decode(Range<BigUInt>.self, from: data)
XCTAssertEqual(actualRange, expectedRange)
}
func testCustomStringConvertible() {
XCTAssertEqual("\(BigUInt(UInt64.min) + 0)", "0")
XCTAssertEqual("\(BigUInt(UInt64.min) + 1)", "1")
XCTAssertEqual("\(BigUInt(UInt64.min) + 2)", "2")
XCTAssertEqual("\(BigUInt(UInt64.max) - 2)", "18446744073709551613")
XCTAssertEqual("\(BigUInt(UInt64.max) - 1)", "18446744073709551614")
XCTAssertEqual("\(BigUInt(UInt64.max) + 0)", "18446744073709551615")
XCTAssertEqual("\(BigUInt(UInt64.max) + 1)", "18446744073709551616")
XCTAssertEqual("\(BigUInt(UInt64.max) + 2)", "18446744073709551617")
XCTAssertEqual("\(BigUInt(Int64.max) - 2)", "9223372036854775805")
XCTAssertEqual("\(BigUInt(Int64.max) - 1)", "9223372036854775806")
XCTAssertEqual("\(BigUInt(Int64.max) + 0)", "9223372036854775807")
XCTAssertEqual("\(BigUInt(Int64.max) + 1)", "9223372036854775808")
XCTAssertEqual("\(BigUInt(Int64.max) + 2)", "9223372036854775809")
XCTAssertEqual("\(+(BigUInt(1) << 1023) - 1)", Self.descriptionInt1024Max)
}
func testLosslessStringConvertible() {
XCTAssertNil(BigUInt(""))
XCTAssertNil(BigUInt("+"))
XCTAssertNil(BigUInt("A"))
XCTAssertNil(BigUInt(" 0"))
XCTAssertNil(BigUInt("0 "))
XCTAssertEqual(BigUInt(UInt64.min) + 0, BigUInt("0"))
XCTAssertEqual(BigUInt(UInt64.min) + 1, BigUInt("1"))
XCTAssertEqual(BigUInt(UInt64.min) + 2, BigUInt("2"))
XCTAssertEqual(BigUInt(UInt64.max) - 2, BigUInt("18446744073709551613"))
XCTAssertEqual(BigUInt(UInt64.max) - 1, BigUInt("18446744073709551614"))
XCTAssertEqual(BigUInt(UInt64.max) + 0, BigUInt("18446744073709551615"))
XCTAssertEqual(BigUInt(UInt64.max) + 1, BigUInt("18446744073709551616"))
XCTAssertEqual(BigUInt(UInt64.max) + 2, BigUInt("18446744073709551617"))
XCTAssertEqual(BigUInt(Int64.max) - 2, BigUInt("9223372036854775805"))
XCTAssertEqual(BigUInt(Int64.max) - 1, BigUInt("9223372036854775806"))
XCTAssertEqual(BigUInt(Int64.max) + 0, BigUInt("9223372036854775807"))
XCTAssertEqual(BigUInt(Int64.max) + 1, BigUInt("9223372036854775808"))
XCTAssertEqual(BigUInt(Int64.max) + 2, BigUInt("9223372036854775809"))
XCTAssertEqual(+(BigUInt(1) << 1023) - 1, BigUInt(Self.descriptionInt1024Max))
}
func testRadicesAndNumerals() {
for radix in 2 ... 36 {
for uppercase in [false, true] {
for _ in 0 ..< 100 {
let expectedNumber = BigUInt(UInt.random(in: .min ... .max))
let expectedString = String(expectedNumber,
radix: radix,
uppercase: uppercase)
let actualNumber = BigUInt(expectedString, radix: radix)
XCTAssertEqual(actualNumber, expectedNumber)
if radix == 10 {
let actualString = expectedNumber.description
XCTAssertEqual(actualString, expectedString)
}
}
}
}
}
// MARK: - Converting from floating-point binary types
func testBinaryFloatingPoint<T>(_ type: T.Type) where T: BinaryFloatingPoint {
var expected = BigUInt(T.greatestFiniteMagnitude.significandBitPattern)
expected |= BigUInt(1) << T.significandBitCount
expected <<= T.greatestFiniteMagnitude.exponent
expected >>= T.significandBitCount
XCTAssertEqual(BigUInt(exactly: +T.greatestFiniteMagnitude), +expected)
XCTAssertEqual(BigUInt(+T.greatestFiniteMagnitude), +expected)
XCTAssertNil(BigUInt(exactly: +T.infinity))
XCTAssertNil(BigUInt(exactly: +T.leastNonzeroMagnitude))
XCTAssertEqual(BigUInt(+T.leastNonzeroMagnitude), 0)
XCTAssertNil(BigUInt(exactly: +T.leastNormalMagnitude))
XCTAssertEqual(BigUInt(+T.leastNormalMagnitude), 0)
XCTAssertNil(BigUInt(exactly: T.nan))
XCTAssertNil(BigUInt(exactly: T.signalingNaN))
XCTAssertNil(BigUInt(exactly: +T.pi))
XCTAssertEqual(BigUInt(+T.pi), +3)
XCTAssertNil(BigUInt(exactly: +T.ulpOfOne))
XCTAssertEqual(BigUInt(+T.ulpOfOne), 0)
XCTAssertEqual(BigUInt(exactly: +T.zero), 0)
XCTAssertEqual(BigUInt(+T.zero), 0)
}
func testBinaryFloatingPoint() {
testBinaryFloatingPoint(Float32.self)
testBinaryFloatingPoint(Float64.self)
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
testBinaryFloatingPoint(Float80.self)
#endif
for _ in 0 ..< 100 {
let small = Float32.random(in: 0 ... +10)
XCTAssertEqual(BigUInt(small), BigUInt(Int64(small)))
let large = Float32.random(in: 0 ... +0x1p23)
XCTAssertEqual(BigUInt(large), BigUInt(Int64(large)))
}
for _ in 0 ..< 100 {
let small = Float64.random(in: 0 ... +10)
XCTAssertEqual(BigUInt(small), BigUInt(Int64(small)))
let large = Float64.random(in: -0x1p52 ... +0x1p52)
XCTAssertEqual(BigInt(large), BigInt(Int64(large)))
}
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
for _ in 0 ..< 100 {
let small = Float80.random(in: 0 ... +10)
XCTAssertEqual(BigUInt(small), BigUInt(Int64(small)))
let large = Float80.random(in: 0 ..< +0x1p63)
XCTAssertEqual(BigUInt(large), BigUInt(Int64(large)))
}
#endif
}
}
+26
View File
@@ -0,0 +1,26 @@
#[[
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(IntegerUtilitiesTests)
add_subdirectory(RealTests)
add_executable(SwiftNumericsTestRunner
WindowsMain.swift)
target_link_libraries(SwiftNumericsTestRunner PRIVATE
ComplexTests
IntegerUtilitiesTests
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)
}
}
+33 -14
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 {
@@ -63,6 +63,20 @@ final class ArithmeticTests: XCTestCase {
func testPolar<T>(_ type: T.Type)
where T: BinaryFloatingPoint, T: Real,
T.Exponent: FixedWidthInteger, T.RawSignificand: FixedWidthInteger {
// In order to support round-tripping from rectangular to polar coordinate
// systems, as a special case phase can be non-finite when length is
// either zero or infinity.
XCTAssertEqual(Complex<T>(length: .zero, phase: .infinity), .zero)
XCTAssertEqual(Complex<T>(length: .zero, phase:-.infinity), .zero)
XCTAssertEqual(Complex<T>(length: .zero, phase: .nan ), .zero)
XCTAssertEqual(Complex<T>(length: .infinity, phase: .infinity), .infinity)
XCTAssertEqual(Complex<T>(length: .infinity, phase:-.infinity), .infinity)
XCTAssertEqual(Complex<T>(length: .infinity, phase: .nan ), .infinity)
XCTAssertEqual(Complex<T>(length:-.infinity, phase: .infinity), .infinity)
XCTAssertEqual(Complex<T>(length:-.infinity, phase:-.infinity), .infinity)
XCTAssertEqual(Complex<T>(length:-.infinity, phase: .nan ), .infinity)
let exponentRange =
(T.leastNormalMagnitude.exponent + T.Exponent(T.significandBitCount)) ...
T.greatestFiniteMagnitude.exponent
@@ -81,7 +95,7 @@ final class ArithmeticTests: XCTestCase {
// this is good--more test coverage!--and bad, because without tight
// bounds on every platform's libm, we can't get tight bounds on the
// accuracy of these operations, so we need to relax them gradually).
let z = Complex(length: p.length, phase: p.phase)!
let z = Complex(length: p.length, phase: p.phase)
if !closeEnough(z.length, p.length, ulps: 16) {
print("p = \(p)\nz = \(z)\nz.length = \(z.length)")
XCTFail()
@@ -90,23 +104,30 @@ final class ArithmeticTests: XCTestCase {
print("p = \(p)\nz = \(z)\nz.phase = \(z.phase)")
XCTFail()
}
// if length*length is normal, it should be unsafeLengthSquared, up
// Complex(length: -r, phase: θ) = -Complex(length: r, phase: θ).
let w = Complex(length: -p.length, phase: p.phase)
if w != -z {
print("p = \(p)\nw = \(w)\nz = \(z)")
XCTFail()
}
XCTAssertEqual(w, -z)
// if length*length is normal, it should be lengthSquared, up
// to small error.
if (p.length*p.length).isNormal {
if !closeEnough(z.unsafeLengthSquared, p.length*p.length, ulps: 16) {
print("p = \(p)\nz = \(z)\nz.unsafeLengthSquared = \(z.unsafeLengthSquared)")
if !closeEnough(z.lengthSquared, p.length*p.length, ulps: 16) {
print("p = \(p)\nz = \(z)\nz.lengthSquared = \(z.lengthSquared)")
XCTFail()
}
}
// Test reciprocal and normalized:
let r = Complex(length: 1/p.length, phase: -p.phase)!
let r = Complex(length: 1/p.length, phase: -p.phase)
if r.isNormal {
if relativeError(r, z.reciprocal!) > 16 {
print("p = \(p)\nz = \(z)\nz.reciprocal = \(r)")
XCTFail()
}
} else { XCTAssertNil(z.reciprocal) }
let n = Complex(length: 1, phase: p.phase)!
let n = Complex(length: 1, phase: p.phase)
if relativeError(n, z.normalized!) > 16 {
print("p = \(p)\nz = \(z)\nz.normalized = \(n)")
XCTFail()
@@ -114,10 +135,10 @@ final class ArithmeticTests: XCTestCase {
// Now test multiplication and division using the polar inputs:
for q in inputs {
let w = Complex(length: q.length, phase: q.phase)!
let product = Complex(length: p.length * q.length, phase: p.phase + q.phase)!
let w = Complex(length: q.length, phase: q.phase)
let product = Complex(length: p.length * q.length, phase: p.phase + q.phase)
if checkMultiply(z, w, expected: product, ulps: 16) { XCTFail() }
let quotient = Complex(length: p.length / q.length, phase: p.phase - q.phase)!
let quotient = Complex(length: p.length / q.length, phase: p.phase - q.phase)
if checkDivide(z, w, expected: quotient, ulps: 16) { XCTFail() }
}
}
@@ -144,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
ElementaryFunctionTests.swift
PropertyTests.swift)
set_target_properties(ComplexTests PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
target_compile_options(ComplexTests PRIVATE
-enable-testing)
target_link_libraries(ComplexTests PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
ComplexModule
Numerics
_TestSupport
XCTest)
@@ -0,0 +1,461 @@
//===--- ElementaryFunctionTests.swift ------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import XCTest
import ComplexModule
import RealModule
import _TestSupport
final class ElementaryFunctionTests: XCTestCase {
func testExp<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
// exp(0) = 1
XCTAssertEqual(1, Complex<T>.exp(Complex( 0, 0)))
XCTAssertEqual(1, Complex<T>.exp(Complex(-0, 0)))
XCTAssertEqual(1, Complex<T>.exp(Complex(-0,-0)))
XCTAssertEqual(1, Complex<T>.exp(Complex( 0,-0)))
// In general, exp(Complex(r,0)) should be exp(r), but that breaks down
// when r is infinity or NaN, because we want all non-finite complex
// values to be semantically a single point at infinity. This is fine
// for most inputs, but exp(Complex(-.infinity, 0)) would produce
// 0 if we evaluated it in the usual way.
XCTAssertFalse(Complex<T>.exp(Complex( .infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.exp(Complex( .infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.exp(Complex( 0, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.exp(Complex(-.infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.exp(Complex(-.infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.exp(Complex(-.infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.exp(Complex( 0,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.exp(Complex( .infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.exp(Complex( .nan, .nan)).isFinite)
XCTAssertFalse(Complex<T>.exp(Complex( .infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.exp(Complex( .nan, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.exp(Complex(-.infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.exp(Complex( .nan,-.infinity)).isFinite)
// Find a value of x such that exp(x) just overflows. Then exp((x, π/4))
// should not overflow, but will do so if it is not computed carefully.
// The correct value is:
//
// exp((log(gfm) + log(9/8), π/4) = exp((log(gfm*9/8), π/4))
// = gfm*9/8 * (1/sqrt(2), 1/(sqrt(2))
let x = T.log(.greatestFiniteMagnitude) + T.log(9/8)
let huge = Complex<T>.exp(Complex(x, .pi/4))
let mag = T.greatestFiniteMagnitude/T.sqrt(2) * (9/8)
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
XCTAssert(huge.imaginary.isApproximatelyEqual(to: mag))
// For randomly-chosen well-scaled finite values, we expect to have the
// usual identities:
//
// exp(z + w) = exp(z) * exp(w)
// exp(z - w) = exp(z) / exp(w)
var g = SystemRandomNumberGenerator()
let values: [Complex<T>] = (0..<100).map { _ in
Complex(T.random(in: -1 ... 1, using: &g),
T.random(in: -.pi ... .pi, using: &g))
}
for z in values {
for w in values {
let p = Complex.exp(z) * Complex.exp(w)
let q = Complex.exp(z) / Complex.exp(w)
XCTAssert(Complex.exp(z + w).isApproximatelyEqual(to: p))
XCTAssert(Complex.exp(z - w).isApproximatelyEqual(to: q))
}
}
}
func testExpMinusOne<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
// expMinusOne(0) = 0
XCTAssertEqual(0, Complex<T>.expMinusOne(Complex( 0, 0)))
XCTAssertEqual(0, Complex<T>.expMinusOne(Complex(-0, 0)))
XCTAssertEqual(0, Complex<T>.expMinusOne(Complex(-0,-0)))
XCTAssertEqual(0, Complex<T>.expMinusOne(Complex( 0,-0)))
// In general, expMinusOne(Complex(r,0)) should be expMinusOne(r), but
// that breaks down when r is infinity or NaN, because we want all non-
// finite complex values to be semantically a single point at infinity.
// This is fine for most inputs, but expMinusOne(Complex(-.infinity, 0))
// would produce 0 if we evaluated it in the usual way.
XCTAssertFalse(Complex<T>.expMinusOne(Complex( .infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.expMinusOne(Complex( .infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.expMinusOne(Complex( 0, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.expMinusOne(Complex(-.infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.expMinusOne(Complex(-.infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.expMinusOne(Complex(-.infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.expMinusOne(Complex( 0,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.expMinusOne(Complex( .infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.expMinusOne(Complex( .nan, .nan)).isFinite)
XCTAssertFalse(Complex<T>.expMinusOne(Complex( .infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.expMinusOne(Complex( .nan, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.expMinusOne(Complex(-.infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.expMinusOne(Complex( .nan,-.infinity)).isFinite)
// Near-overflow test, same as exp() above.
let x = T.log(.greatestFiniteMagnitude) + T.log(9/8)
let huge = Complex<T>.expMinusOne(Complex(x, .pi/4))
let mag = T.greatestFiniteMagnitude/T.sqrt(2) * (9/8)
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
XCTAssert(huge.imaginary.isApproximatelyEqual(to: mag))
// For small values, expMinusOne should be approximately the identity.
var g = SystemRandomNumberGenerator()
let small = T.ulpOfOne
for _ in 0 ..< 100 {
let z = Complex<T>(T.random(in: -small ... small, using: &g),
T.random(in: -small ... small, using: &g))
XCTAssert(z.isApproximatelyEqual(to: Complex.expMinusOne(z), relativeTolerance: 16 * .ulpOfOne))
}
}
func testLogOnePlus<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
// log(onePlus: 0) = 0
XCTAssertEqual(0, Complex<T>.log(onePlus: Complex( 0, 0)))
XCTAssertEqual(0, Complex<T>.log(onePlus: Complex(-0, 0)))
XCTAssertEqual(0, Complex<T>.log(onePlus: Complex(-0,-0)))
XCTAssertEqual(0, Complex<T>.log(onePlus: Complex( 0,-0)))
// log(onePlus:) is the identity at infinity.
XCTAssertFalse(Complex<T>.log(onePlus: Complex( .infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.log(onePlus: Complex( .infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.log(onePlus: Complex( 0, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.log(onePlus: Complex(-.infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.log(onePlus: Complex(-.infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.log(onePlus: Complex(-.infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.log(onePlus: Complex( 0,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.log(onePlus: Complex( .infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.log(onePlus: Complex( .nan, .nan)).isFinite)
XCTAssertFalse(Complex<T>.log(onePlus: Complex( .infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.log(onePlus: Complex( .nan, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.log(onePlus: Complex(-.infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.log(onePlus: Complex( .nan,-.infinity)).isFinite)
// For randomly-chosen well-scaled finite values, we expect to have
// log(onePlus: expMinusOne(z)) ≈ z
var g = SystemRandomNumberGenerator()
let values: [Complex<T>] = (0..<1000).map { _ in
Complex(T.random(in: -2 ... 2, using: &g),
T.random(in: -2 ... 2, using: &g))
}
for z in values {
let w = Complex.expMinusOne(z)
let u = Complex.log(onePlus: w)
if !u.isApproximatelyEqual(to: z) {
print("log(onePlus: expMinusOne()) was not close to identity at z = \(z).")
print("expMinusOne(\(z)) = \(w).")
print("long(onePlus: \(w)) = \(u).")
XCTFail()
}
}
}
func testCosh<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
// cosh(0) = 1
XCTAssertEqual(1, Complex<T>.cosh(Complex( 0, 0)))
XCTAssertEqual(1, Complex<T>.cosh(Complex(-0, 0)))
XCTAssertEqual(1, Complex<T>.cosh(Complex(-0,-0)))
XCTAssertEqual(1, Complex<T>.cosh(Complex( 0,-0)))
// cosh is the identity at infinity.
XCTAssertFalse(Complex<T>.cosh(Complex( .infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.cosh(Complex( .infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.cosh(Complex( 0, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.cosh(Complex(-.infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.cosh(Complex(-.infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.cosh(Complex(-.infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.cosh(Complex( 0,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.cosh(Complex( .infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.cosh(Complex( .nan, .nan)).isFinite)
XCTAssertFalse(Complex<T>.cosh(Complex( .infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.cosh(Complex( .nan, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.cosh(Complex(-.infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.cosh(Complex( .nan,-.infinity)).isFinite)
// Near-overflow test, same as exp() above, but it happens later, because
// for large x, cosh(x + iy) ~ exp(x + iy)/2.
let x = T.log(.greatestFiniteMagnitude) + T.log(18/8)
let mag = T.greatestFiniteMagnitude/T.sqrt(2) * (9/8)
var huge = Complex<T>.cosh(Complex(x, .pi/4))
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
XCTAssert(huge.imaginary.isApproximatelyEqual(to: mag))
huge = Complex<T>.cosh(Complex(-x, .pi/4))
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
XCTAssert(huge.imaginary.isApproximatelyEqual(to: mag))
}
func testSinh<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
// sinh(0) = 0
XCTAssertEqual(0, Complex<T>.sinh(Complex( 0, 0)))
XCTAssertEqual(0, Complex<T>.sinh(Complex(-0, 0)))
XCTAssertEqual(0, Complex<T>.sinh(Complex(-0,-0)))
XCTAssertEqual(0, Complex<T>.sinh(Complex( 0,-0)))
// sinh is the identity at infinity.
XCTAssertFalse(Complex<T>.sinh(Complex( .infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.sinh(Complex( .infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.sinh(Complex( 0, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.sinh(Complex(-.infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.sinh(Complex(-.infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.sinh(Complex(-.infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.sinh(Complex( 0,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.sinh(Complex( .infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.sinh(Complex( .nan, .nan)).isFinite)
XCTAssertFalse(Complex<T>.sinh(Complex( .infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.sinh(Complex( .nan, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.sinh(Complex(-.infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.sinh(Complex( .nan,-.infinity)).isFinite)
// Near-overflow test, same as exp() above, but it happens later, because
// for large x, sinh(x + iy) ~ ±exp(x + iy)/2.
let x = T.log(.greatestFiniteMagnitude) + T.log(18/8)
let mag = T.greatestFiniteMagnitude/T.sqrt(2) * (9/8)
var huge = Complex<T>.sinh(Complex(x, .pi/4))
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
XCTAssert(huge.imaginary.isApproximatelyEqual(to: mag))
huge = Complex<T>.sinh(Complex(-x, .pi/4))
XCTAssert(huge.real.isApproximatelyEqual(to: -mag))
XCTAssert(huge.imaginary.isApproximatelyEqual(to: -mag))
// For randomly-chosen well-scaled finite values, we expect to have
// cosh² - sinh² ≈ 1. Note that this test would break down due to
// catastrophic cancellation as we get further away from the origin.
var g = SystemRandomNumberGenerator()
let values: [Complex<T>] = (0..<1000).map { _ in
Complex(T.random(in: -2 ... 2, using: &g),
T.random(in: -2 ... 2, using: &g))
}
for z in values {
let c = Complex.cosh(z)
let s = Complex.sinh(z)
XCTAssert((c*c - s*s).isApproximatelyEqual(to: 1))
}
}
func testAcos<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
// acos(1) = 0
XCTAssertEqual(0, Complex<T>.acos(1))
// acos(0) = π/2
XCTAssert(Complex<T>.acos(0).real.isApproximatelyEqual(to: .pi/2))
XCTAssertEqual(Complex<T>.acos(0).imaginary, 0)
// acos(-1) = π
XCTAssert(Complex<T>.acos(-1).real.isApproximatelyEqual(to: .pi))
XCTAssertEqual(Complex<T>.acos(-1).imaginary, 0)
// acos is the identity at infinity.
XCTAssertFalse(Complex<T>.acos(Complex( .infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.acos(Complex( .infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.acos(Complex( 0, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.acos(Complex(-.infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.acos(Complex(-.infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.acos(Complex(-.infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.acos(Complex( 0,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.acos(Complex( .infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.acos(Complex( .nan, .nan)).isFinite)
XCTAssertFalse(Complex<T>.acos(Complex( .infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.acos(Complex( .nan, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.acos(Complex(-.infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.acos(Complex( .nan,-.infinity)).isFinite)
// For randomly-chosen well-scaled finite values, we expect to have
// cos(acos(z)) ≈ z and acos(z) ≈ π - acos(-z)
var g = SystemRandomNumberGenerator()
let values: [Complex<T>] = (0..<1000).map { _ in
Complex(T.random(in: -2 ... 2, using: &g),
T.random(in: -2 ... 2, using: &g))
}
for z in values {
let w = Complex.acos(z)
XCTAssert(Complex.cos(w).isApproximatelyEqual(to: z))
XCTAssert(w.isApproximatelyEqual(to: Complex(.pi) - .acos(-z)))
}
}
func testAsin<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
// asin(1) = π/2
XCTAssert(Complex<T>.asin(1).real.isApproximatelyEqual(to: .pi/2))
XCTAssertEqual(Complex<T>.asin(1).imaginary, 0)
// asin(0) = 0
XCTAssertEqual(0, Complex<T>.asin(0))
// asin(-1) = -π/2
XCTAssert(Complex<T>.asin(-1).real.isApproximatelyEqual(to: -.pi/2))
XCTAssertEqual(Complex<T>.asin(-1).imaginary, 0)
// asin is the identity at infinity.
XCTAssertFalse(Complex<T>.asin(Complex( .infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.asin(Complex( .infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.asin(Complex( 0, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.asin(Complex(-.infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.asin(Complex(-.infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.asin(Complex(-.infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.asin(Complex( 0,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.asin(Complex( .infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.asin(Complex( .nan, .nan)).isFinite)
XCTAssertFalse(Complex<T>.asin(Complex( .infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.asin(Complex( .nan, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.asin(Complex(-.infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.asin(Complex( .nan,-.infinity)).isFinite)
// For randomly-chosen well-scaled finite values, we expect to have
// sin(asin(z)) ≈ z and asin(z) ≈ -asin(-z)
var g = SystemRandomNumberGenerator()
let values: [Complex<T>] = (0..<1000).map { _ in
Complex(T.random(in: -2 ... 2, using: &g),
T.random(in: -2 ... 2, using: &g))
}
for z in values {
let w = Complex.asin(z)
XCTAssert(Complex.sin(w).isApproximatelyEqual(to: z))
XCTAssert(w.isApproximatelyEqual(to: -.asin(-z)))
}
}
func testAcosh<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
// acosh(1) = 0
XCTAssertEqual(0, Complex<T>.acosh(1))
// acosh(0) = iπ/2
XCTAssert(Complex<T>.acosh(0).imaginary.isApproximatelyEqual(to: .pi/2))
XCTAssertEqual(Complex<T>.acosh(0).real, 0)
// acosh(-1) = iπ
XCTAssert(Complex<T>.acosh(-1).imaginary.isApproximatelyEqual(to: .pi))
XCTAssertEqual(Complex<T>.acosh(-1).real, 0)
// acosh is the identity at infinity.
XCTAssertFalse(Complex<T>.acosh(Complex( .infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.acosh(Complex( .infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.acosh(Complex( 0, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.acosh(Complex(-.infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.acosh(Complex(-.infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.acosh(Complex(-.infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.acosh(Complex( 0,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.acosh(Complex( .infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.acosh(Complex( .nan, .nan)).isFinite)
XCTAssertFalse(Complex<T>.acosh(Complex( .infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.acosh(Complex( .nan, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.acosh(Complex(-.infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.acosh(Complex( .nan,-.infinity)).isFinite)
// For randomly-chosen well-scaled finite values, we expect to have
// cosh(acosh(z)) ≈ z
var g = SystemRandomNumberGenerator()
let values: [Complex<T>] = (0..<1000).map { _ in
Complex(T.random(in: -2 ... 2, using: &g),
T.random(in: -2 ... 2, using: &g))
}
for z in values {
let w = Complex.acosh(z)
XCTAssert(Complex.cosh(w).isApproximatelyEqual(to: z))
}
}
func testAsinh<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
// asinh(1) = π/2
XCTAssert(Complex<T>.asin(1).real.isApproximatelyEqual(to: .pi/2))
XCTAssertEqual(Complex<T>.asin(1).imaginary, 0)
// asinh(0) = 0
XCTAssertEqual(0, Complex<T>.asin(0))
// asinh(-1) = -π/2
XCTAssert(Complex<T>.asin(-1).real.isApproximatelyEqual(to: -.pi/2))
XCTAssertEqual(Complex<T>.asin(-1).imaginary, 0)
// asinh is the identity at infinity.
XCTAssertFalse(Complex<T>.asinh(Complex( .infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.asinh(Complex( .infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.asinh(Complex( 0, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.asinh(Complex(-.infinity, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.asinh(Complex(-.infinity, 0)).isFinite)
XCTAssertFalse(Complex<T>.asinh(Complex(-.infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.asinh(Complex( 0,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.asinh(Complex( .infinity,-.infinity)).isFinite)
XCTAssertFalse(Complex<T>.asinh(Complex( .nan, .nan)).isFinite)
XCTAssertFalse(Complex<T>.asinh(Complex( .infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.asinh(Complex( .nan, .infinity)).isFinite)
XCTAssertFalse(Complex<T>.asinh(Complex(-.infinity, .nan)).isFinite)
XCTAssertFalse(Complex<T>.asinh(Complex( .nan,-.infinity)).isFinite)
// For randomly-chosen well-scaled finite values, we expect to have
// sinh(asinh(z)) ≈ z
var g = SystemRandomNumberGenerator()
let values: [Complex<T>] = (0..<1000).map { _ in
Complex(T.random(in: -2 ... 2, using: &g),
T.random(in: -2 ... 2, using: &g))
}
for z in values {
let w = Complex.asinh(z)
let u = Complex.sinh(w)
if !u.isApproximatelyEqual(to: z) {
print("sinh(asinh()) was not close to identity at z = \(z).")
print("asinh(\(z)) = \(w).")
print("sinh(\(w)) = \(u).")
XCTFail()
}
}
}
func testAtanh<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
// For randomly-chosen well-scaled finite values, we expect to have
// atanh(tanh(z)) ≈ z
var g = SystemRandomNumberGenerator()
let values: [Complex<T>] = (0..<1000).map { _ in
Complex(T.random(in: -2 ... 2, using: &g),
T.random(in: -2 ... 2, using: &g))
}
for z in values {
let w = Complex.atanh(z)
let u = Complex.tanh(w)
if !u.isApproximatelyEqual(to: z) {
print("tanh(atanh()) was not close to identity at z = \(z).")
print("atanh(\(z)) = \(w).")
print("tanh(\(w)) = \(u).")
XCTFail()
}
}
}
func testPowR<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
XCTAssertEqual(Complex<T>.pow(.zero, -.one), .infinity)
XCTAssertEqual(Complex<T>.pow(.zero, .zero), .infinity)
XCTAssertEqual(Complex<T>.pow(.zero, +.one), .zero)
}
func testPowN<T: Real & FixedWidthFloatingPoint>(_ type: T.Type) {
XCTAssertEqual(Complex<T>.pow(.zero, -1), .infinity)
XCTAssertEqual(Complex<T>.pow(.zero, 0), .one)
XCTAssertEqual(Complex<T>.pow(.zero, +1), .zero)
}
func testFloat() {
testExp(Float.self)
testExpMinusOne(Float.self)
testLogOnePlus(Float.self)
testCosh(Float.self)
testSinh(Float.self)
testAcos(Float.self)
testAsin(Float.self)
testAcosh(Float.self)
testAsinh(Float.self)
testAtanh(Float.self)
testPowR(Float.self)
testPowN(Float.self)
}
func testDouble() {
testExp(Double.self)
testExpMinusOne(Double.self)
testLogOnePlus(Float.self)
testCosh(Double.self)
testSinh(Double.self)
testAcos(Double.self)
testAsin(Double.self)
testAcosh(Double.self)
testAsinh(Double.self)
testAtanh(Double.self)
testPowR(Double.self)
testPowN(Double.self)
}
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
func testFloat80() {
testExp(Float80.self)
testExpMinusOne(Float80.self)
testLogOnePlus(Float.self)
testCosh(Float80.self)
testSinh(Float80.self)
testAcos(Float80.self)
testAsin(Float80.self)
testAcosh(Float80.self)
testAsinh(Float80.self)
testAtanh(Float80.self)
testPowR(Float80.self)
testPowN(Float80.self)
}
#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.
}
}
+108
View File
@@ -0,0 +1,108 @@
//===--- main.swift -------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Numerics
import _TestSupport
#if DEBUG
fatalError("Run this test in Release configuration")
#else
var componentError = Double(Float.ulpOfOne/2)
var complexError = Double(Float.ulpOfOne/2)
var componentMaxInput = Complex<Float>.zero
var complexMaxInput = Complex<Float>.zero
func test(_ z: Complex<Float>) {
let tst = Complex.log(z)
// TODO: we _should_ be able to say Complex<Double>(z), but that goes through
// the slow, generic path for BinaryFloatingPoint conversion; once we get
// that resolved in the standard library, we can replace the conversion on
// this and the next line. Currently it dominate testing time if we do that.
let ref = Complex.log(Complex(Double(z.real), Double(z.imaginary)))
if tst == Complex(Float(ref.real), Float(ref.imaginary)) { return }
let thisError = relativeError(tst, ref)
if thisError > complexError {
complexMaxInput = z
complexError = thisError
}
let thisComponentError = componentwiseError(tst, ref)
if thisComponentError > componentError {
componentMaxInput = z
componentError = thisComponentError
}
}
func testWithSymmetries(_ x: Float, _ y: Float) {
test(Complex( x, y))
test(Complex( y, x))
test(Complex(-y, x))
test(Complex(-x, y))
test(Complex(-x,-y))
test(Complex(-y,-x))
test(Complex( y,-x))
test(Complex( x,-y))
}
// The hardest to evaluate cases for log are those close to the unit circle,
// where log(z) is nearly zero. We want to have plausibly dense test coverage
// close to the circle.
let radii: [Float] = [0.9,
0.95,
0.99,
0.999,
0.9999,
1 - 10 * .ulpOfOne,
1,
1 + 10 * .ulpOfOne,
1.0001,
1.001,
1.01,
1.05,
1.1]
for r in radii {
for x in Interval(from: 1/Float.sqrt(2), to: r) {
// Generate the two y values that put us closest to the circle of radius r
let base = Double.sqrt(Double(r).addingProduct(Double(-x), Double(x)))
let a, b: Float
if Double(Float(base)) < base { a = Float(base); b = a.nextUp }
else { b = Float(base); a = b.nextDown }
testWithSymmetries(x, a)
testWithSymmetries(x, b)
}
}
// Away from the unit circle is "easy" but we still want to get some coverage.
// Generate 1 million uniform random points inside the circle, and then test
// both z and 1/z.
var g = SystemRandomNumberGenerator()
var count = 0
while count < 1_000_000 {
let z = Complex<Float>(.random(in: -1 ... 1, using: &g), .random(in: -1 ... 1, using: &g))
if z.length > 1 { continue }
count += 1
test(z)
test(1/z)
}
print("Worst complex norm error seen for log was \(complexError)")
print("For input \(complexMaxInput).")
print("Reference result: \(Complex.log(Complex<Double>(complexMaxInput)))")
print(" Observed result: \(Complex.log(complexMaxInput))")
print("Worst componentwise error seen for log was \(componentError)")
print("For input \(componentMaxInput).")
print("Reference result: \(Complex.log(Complex<Double>(componentMaxInput)))")
print(" Observed result: \(Complex.log(componentMaxInput))")
#endif
+108
View File
@@ -0,0 +1,108 @@
//===--- main.swift -------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Numerics
import _TestSupport
#if DEBUG
fatalError("Run this test in Release configuration")
#else
var componentError = Double(Float.ulpOfOne/2)
var complexError = Double(Float.ulpOfOne/2)
var componentMaxInput = Complex<Float>.zero
var complexMaxInput = Complex<Float>.zero
func test(_ z: Complex<Float>) {
let tst = Complex.log(onePlus: z)
// TODO: we _should_ be able to say Complex<Double>(z), but that goes through
// the slow, generic path for BinaryFloatingPoint conversion; once we get
// that resolved in the standard library, we can replace the conversion on
// this and the next line. Currently it dominate testing time if we do that.
let ref = Complex.log(onePlus: Complex(Double(z.real), Double(z.imaginary)))
if tst == Complex(Float(ref.real), Float(ref.imaginary)) { return }
let thisError = relativeError(tst, ref)
if thisError > complexError {
complexMaxInput = z
complexError = thisError
}
let thisComponentError = componentwiseError(tst, ref)
if thisComponentError > componentError {
componentMaxInput = z
componentError = thisComponentError
}
}
func testWithSymmetry(_ x: Float, _ y: Float) {
test(Complex( x-1, y))
test(Complex( y-1, x))
test(Complex(-y-1, x))
test(Complex(-x-1, y))
test(Complex(-x-1,-y))
test(Complex(-y-1,-x))
test(Complex( y-1,-x))
test(Complex( x-1,-y))
}
// The hardest to evaluate cases for log are those close to the unit circle
// centered at -1, where log(1+z) is nearly zero. We want to have plausibly
// dense test coverage close to the circle.
let radii: [Float] = [0.9,
0.95,
0.99,
0.999,
0.9999,
1 - 10 * .ulpOfOne,
1,
1 + 10 * .ulpOfOne,
1.0001,
1.001,
1.01,
1.05,
1.1]
for r in radii {
for x in Interval(from: 1/Float.sqrt(2), to: r) {
// Generate the two y values that put us closest to the circle of radius r
let base = Double.sqrt(Double(r).addingProduct(Double(-x), Double(x)))
let a, b: Float
if Double(Float(base)) < base { a = Float(base); b = a.nextUp }
else { b = Float(base); a = b.nextDown }
testWithSymmetry(x, a)
testWithSymmetry(x, b)
}
}
// Away from the unit circle is "easy" but we still want to get some coverage.
// Generate 1 million uniform random points inside the circle, and then test
// both z and 1/z.
var g = SystemRandomNumberGenerator()
var count = 0
while count < 1_000_000 {
let z = Complex<Float>(.random(in: -1 ... 1, using: &g), .random(in: -1 ... 1, using: &g))
if z.length > 1 { continue }
count += 1
test(z - 1)
test(1/z - 1)
}
print("Worst complex norm error seen for log(onePlus:) was \(complexError)")
print("For input \(complexMaxInput).")
print("Reference result: \(Complex.log(onePlus: Complex<Double>(complexMaxInput)))")
print(" Observed result: \(Complex.log(onePlus: complexMaxInput))")
print("Worst componentwise error seen for log(onePlus:) was \(componentError)")
print("For input \(componentMaxInput).")
print("Reference result: \(Complex.log(onePlus: Complex<Double>(componentMaxInput)))")
print(" Observed result: \(Complex.log(onePlus: componentMaxInput))")
#endif
@@ -0,0 +1,23 @@
#[[
This source file is part of the Swift Numerics open source project
Copyright (c) 2019-2021 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(IntegerUtilitiesTests
DivideTests.swift
DoubleWidthTests.swift
GCDTests.swift
RotateTests.swift
SaturatingArithmeticTests.swift
ShiftTests.swift)
target_compile_options(IntegerUtilitiesTests PRIVATE
-enable-testing)
target_link_libraries(IntegerUtilitiesTests PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
Numerics
_TestSupport
XCTest)
@@ -0,0 +1,354 @@
//===--- DivideTests.swift ------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 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 IntegerUtilities
import XCTest
final class IntegerUtilitiesDivideTests: XCTestCase {
func divisionRuleHolds<T: BinaryInteger>(_ a: T, _ b: T, _ q: T, _ r: T) -> Bool {
// Validate division rule holds: a = qb + r (have to be careful about
// computing qb, though, to ensure it does not overflow due to
// rounding of q; compute it in two pieces, subtracting the first from
// a to avoid intermediate overflow).
let b1 = b >> 1
let b2 = b - b1
let ref = a - q*b1 - q*b2
if r != ref {
XCTFail("""
\(a).divided(by: \(b), rounding: .down) failed the division rule.
a - qb was \(ref), but r is \(r).
""")
return false
}
if r.magnitude >= b.magnitude {
XCTFail("""
\(a).divided(by: \(b), rounding: .down) failed check on r.
|remainder| must be smaller than |divisor|, but was \(r).
""")
return false
}
return true
}
func testDivideDown<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .down)
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now validate sign(r) == sign(b).
guard r == 0 || r.signum() == b.signum() else {
XCTFail("""
\(a).divided(by: \(b), rounding: .down) failed check on r.
remainder must match sign of divisor, but was \(r).
""")
return
}
}
}
}
}
func testDivideUp<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .up)
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now validate sign(r) != sign(b).
guard r == 0 || r.signum() != b.signum() else {
XCTFail("""
\(a).divided(by: \(b), rounding: .up) failed check on r.
remainder must oppose sign of divisor, but was \(r).
""")
return
}
}
}
}
}
func testDivideTowardZero<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .towardZero)
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now validate sign(r) == sign(a).
guard r == 0 || r.signum() == a.signum() else {
XCTFail("""
\(a).divided(by: \(b), rounding: .towardZero) failed check on r.
remainder must match sign of dividend, but was \(r).
""")
return
}
}
}
}
}
func testDivideAwayFromZero<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .awayFromZero)
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now validate sign(r) != sign(a).
guard r == 0 || r.signum() != a.signum() else {
XCTFail("""
\(a).divided(by: \(b), rounding: .awayFromZero) failed check on r.
remainder must oppose sign of dividend, but was \(r).
""")
return
}
}
}
}
}
func testDivideToOdd<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .toOdd)
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now validate q is odd if r is
// non-zero.
guard r == 0 || q & 1 == 1 else {
XCTFail("""
\(a).divided(by: \(b), rounding: .toOdd) failed check:
quotient must be odd if remainder is non-zero, but quotient was \(q) and remainder was \(r).
""")
return
}
}
}
}
}
func testDivideToNearestOrAway<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .toNearestOrAwayFromZero)
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2
// with equality only if sign(r) != sign(a).
if 2*r.magnitude > b.magnitude {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrAwayFromZero) failed check:
|remainder| must be less than or equal to |divisor|/2, but remainder was \(r).
""")
return
}
if 2*r.magnitude == b.magnitude && r.signum() == a.signum() {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrAwayFromZero) failed check:
If |remainder| equals |divisor|/2, remainder must oppose sign of dividend, but was \(r).
""")
return
}
}
}
}
}
func testDivideToNearestOrEven<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .toNearestOrEven)
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2
// with equality only if sign(r) != sign(a).
if 2*r.magnitude > b.magnitude {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrEven) failed check:
|remainder| must be less than or equal to |divisor|/2, but remainder was \(r).
""")
return
}
if 2*r.magnitude == b.magnitude && q & 1 == 1 {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrEven) failed check:
If |remainder| equals |divisor|/2, quotient must be even, but quotient was \(q) and remainder was \(r).
""")
return
}
}
}
}
}
func testDivideStochastic<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .stochastically)
let _ = divisionRuleHolds(a, b, q, r)
}
}
}
func testDivideExact<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
// Skip any cases with a remainder (most of them!)
if a % b != 0 { continue }
// Test that division rule holds ignoring r for the cases that
// make it through.
let (q, _) = a.divided(by: b, rounding: .requireExact)
let _ = divisionRuleHolds(a, b, q, 0)
}
}
}
func testDivideInt8() {
let values = Array<Int8>(-128 ... 127)
testDivideDown(values)
testDivideUp(values)
testDivideTowardZero(values)
testDivideAwayFromZero(values)
testDivideToOdd(values)
testDivideToNearestOrAway(values)
testDivideToNearestOrEven(values)
testDivideStochastic(values)
testDivideExact(values)
}
func testDivideInt() {
var values = [Int](repeating: 0, count: 64)
for i in 0 ..< values.count {
while values[i] == 0 {
values[i] = .random(in: .min ... .max)
}
}
testDivideDown(values)
testDivideUp(values)
testDivideTowardZero(values)
testDivideAwayFromZero(values)
testDivideToOdd(values)
testDivideToNearestOrAway(values)
testDivideToNearestOrEven(values)
testDivideStochastic(values)
testDivideExact(values)
}
func divideUInt8(_ a: UInt8, _ b: UInt8, rounding rule: RoundingRule) {
let expected = UInt8(Int16(a).divided(by: Int16(b), rounding: rule).quotient)
let observed = a.divided(by: b, rounding: rule)
guard expected == observed else {
XCTFail("""
\(a).divided(by: \(b), rounding: \(rule)) did not match expected result:
Computed with Int16: \(expected)
Computed with UInt8: \(observed)
""")
return
}
}
func testDivideUInt8() {
let values = Array<UInt8>(0 ... 255)
for a in values {
for b in values where b != 0 {
divideUInt8(a, b, rounding: .down)
divideUInt8(a, b, rounding: .up)
divideUInt8(a, b, rounding: .towardZero)
divideUInt8(a, b, rounding: .awayFromZero)
divideUInt8(a, b, rounding: .toOdd)
divideUInt8(a, b, rounding: .toNearestOrAwayFromZero)
divideUInt8(a, b, rounding: .toNearestOrEven)
}
}
}
// stochastically rounding doesn't have a deterministic "expected" answer,
// but we know that the result must be either the floor or the ceiling.
// The above tests ensure that, but that's not a very strong guarantee;
// an implementation could just implement it as self / other and pass
// that test.
//
// Here we round the _same_ value many times, compute the average, and
// check that it is acceptably close to the exact expected value; simple
// use of any deterministic rounding rule will not achieve this.
func testStochasticDivide<T: FixedWidthInteger>(_ a: T, _ b: T) -> Bool {
let sum = (0..<1024).reduce(into: 0.0) { sum, _ in
let rounded = a.divided(by: b, rounding: .stochastically)
sum += Double(rounded)
}
let expected = 1024 * Double(a) / Double(b)
let difference = abs(sum - expected)
// Waving my hands slightly instead of giving a precise explanation
// here, the expectation is that difference should be about
// 1/2 sqrt(1024). If we're more than a couple standard deviations
// off, we should flag that. This isn't _necessarily_ a problem,
// but if you see a repeated failure, that's almost surely a real bug.
//
// TODO: precise justification of thresholds
XCTAssertLessThanOrEqual(difference, 64,
"Accumulated error (\(difference)) was unexpectedly large in \(a).divided(by: \(b))"
)
return difference > 16
}
func testDivideStochasticInt8() {
var values = [Int8](repeating: 0, count: 32)
for i in 0 ..< values.count {
while values[i] == 0 {
values[i] = .random(in: .min ... .max)
}
}
var fails = 0
for a in values {
for b in values {
if a == .min && b == -1 { continue }
fails += testStochasticDivide(a, b) ? 1 : 0
}
}
XCTAssertLessThanOrEqual(fails, 32*16)
}
func testDivideStochasticUInt32() {
var values = [UInt32](repeating: 0, count: 32)
for i in 0 ..< values.count {
while values[i] == 0 {
values[i] = .random(in: .min ... .max)
}
}
var fails = 0
for a in values {
for b in values {
fails += testStochasticDivide(a, b) ? 1 : 0
}
}
XCTAssertLessThanOrEqual(fails, 32*16)
}
func testRemainderByMinusOne() {
// These would trap if implemented as a - bq or similar, even though
// the remainder is well-defined.
XCTAssertEqual(0, Int.min.remainder(dividingBy: -1))
XCTAssertEqual(0, Int.min.remainder(dividingBy: -1, rounding: .up))
XCTAssertEqual(0, Int.min.remainder(dividingBy: -1, rounding: .stochastically))
}
}
@@ -0,0 +1,525 @@
//===--- DoubleWidthTests.swift -------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2017-2021 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 _TestSupport
import XCTest
final class DoubleWidthTests: XCTestCase {
typealias _Int16 = DoubleWidth<Int8>
typealias _Int128 = DoubleWidth<Int64>
typealias _Int256 = DoubleWidth<_Int128>
typealias _Int512 = DoubleWidth<_Int256>
typealias _Int1024 = DoubleWidth<_Int512>
typealias _UInt16 = DoubleWidth<UInt8>
typealias _UInt128 = DoubleWidth<UInt64>
typealias _UInt256 = DoubleWidth<_UInt128>
typealias _UInt512 = DoubleWidth<_UInt256>
typealias _UInt1024 = DoubleWidth<_UInt512>
// <https://bugs.swift.org/browse/SR-6947>
// Swift 4.x took over 15 minutes to compile this test code.
// Swift 5.5 takes less than one second (`-Onone` or `-O` or `-Osize`).
func testCompileTime_SR_6947() {
typealias _Int32 = DoubleWidth<DoubleWidth<Int8>>
typealias _Int64 = DoubleWidth<DoubleWidth<DoubleWidth<Int8>>>
var sum = 0
let (q, r) = (_Int128(Int64.max) * 16).quotientAndRemainder(dividingBy: 16)
sum += Int(q * r)
XCTAssertEqual(sum, 0)
let x = _Int64(Int64.max / 4)
let y = _Int32(Int32.max)
let xx = _Int1024(x)
let yy = _Int512(y)
let (q3, r3) = yy.dividingFullWidth((xx.high, xx.low))
sum -= Int(q3 - r3)
XCTAssertEqual(sum, -1)
}
func testLiterals() {
let w: _UInt16 = 100
XCTAssertTrue(w == 100 as Int)
let x: _UInt16 = 1000
XCTAssertTrue(x == 1000 as Int)
let y: _Int16 = 1000
XCTAssertTrue(y == 1000 as Int)
let z: _Int16 = -1000
XCTAssertTrue(z == -1000 as Int)
}
func testLiterals_Underflow() {
// TODO: expectCrashLater()
// _ = -1 as _UInt16
}
#if false // TODO: _ExpressibleByBuiltinIntegerLiteral
func testLiterals_LargeSigned() {
let a: _Int256 =
0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
let b: _Int256 =
-0x8000000000000000000000000000000000000000000000000000000000000000
XCTAssertEqual(a, _Int256.max)
XCTAssertEqual(b, _Int256.min)
}
func testLiterals_LargeSigned_Underflow() {
// TODO: expectCrashLater()
// _ = -0x8000000000000000000000000000000000000000000000000000000000000001
// as _Int256
}
func testLiterals_LargeSigned_Overflow() {
// TODO: expectCrashLater()
// _ = 0x8000000000000000000000000000000000000000000000000000000000000000
// as _Int256
}
func testLiterals_LargeUnsigned() {
let a: _UInt256 =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
let b: _UInt256 = 0
XCTAssertEqual(a, _UInt256.max)
XCTAssertEqual(b, _UInt256.min)
}
func testLiterals_LargeUnsigned_Underflow() {
// TODO: expectCrashLater()
// _ = -1 as _UInt256
}
func testLiterals_LargeUnsigned_Overflow() {
// TODO: expectCrashLater()
// _ = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0
// as _UInt256
}
#endif // TODO: _ExpressibleByBuiltinIntegerLiteral
func testArithmetic_Unsigned() {
let x: _UInt16 = 1000
let y: _UInt16 = 1111
XCTAssertEqual(x + 1, 1001)
XCTAssertEqual(x + x, 2000)
XCTAssertEqual(x - (1 as _UInt16), 999)
XCTAssertEqual(x - x, 0)
XCTAssertEqual(y - x, 111)
XCTAssertEqual(x * 7, 7000)
XCTAssertEqual(y * 7, 7777)
XCTAssertEqual(x / 3, 333)
XCTAssertEqual(x / x, 1)
XCTAssertEqual(x / y, 0)
XCTAssertEqual(y / x, 1)
XCTAssertEqual(x % 3, 1)
XCTAssertEqual(x % y, x)
do {
let lhs = _UInt16((high: 0b0011_0000, low: 0))
let rhs = _UInt16((high: 0b0010_0000, low: 0))
XCTAssertEqual(lhs % rhs, 4096)
}
do {
let lhs = _UInt128((high: 0xa0c7d7165cf01386, low: 0xbf3f66a93056143f))
let rhs = _UInt128((high: 0x9ac3a19b1e7d6b83, low: 0x513929792d588736))
XCTAssertEqual(String(lhs % rhs), "7997221894243298914179865336050715913")
}
do {
let lhs = _UInt128((high: 0xea8a9116b7af33b7, low: 0x3d9d6779ddd22ca3))
let rhs = _UInt128((high: 0xc3673efc7f1f37cc, low: 0x312f661057d0ba94))
XCTAssertEqual(String(lhs % rhs), "52023287460685389410162512181093036559")
}
do {
let lhs = _UInt256("2369676578372158364766242369061213561181961479062237766620")!
let rhs = _UInt256("102797312405202436815976773795958969482")!
XCTAssertEqual(String(lhs / rhs), "23051931251193218442")
}
do {
let lhs = _UInt256("96467201117289166187766181030232879447148862859323917044548749804018359008044")!
let rhs = _UInt256("4646260627574879223760172113656436161581617773435991717024")!
XCTAssertEqual(String(lhs / rhs), "20762331011904583253")
}
XCTAssertTrue((0xff01 as _UInt16).multipliedFullWidth(by: 0x101) == (high: 256, low: 1))
}
func testArithmetic_Signed() {
let x: _Int16 = 1000
let y: _Int16 = -1111
XCTAssertEqual(x + 1, 1001)
XCTAssertEqual(x + x, 2000)
XCTAssertEqual(x - (1 as _Int16), 999)
XCTAssertEqual(x - x, 0)
XCTAssertEqual(0 - x, -1000)
XCTAssertEqual(x + y, -111)
XCTAssertEqual(x - y, 2111)
XCTAssertEqual(x * 7, 7000)
XCTAssertEqual(y * 7, -7777)
XCTAssertEqual(x * -7, -7000)
XCTAssertEqual(y * -7, 7777)
XCTAssertEqual(x / 3, 333)
XCTAssertEqual(x / -3, -333)
XCTAssertEqual(x / x, 1)
XCTAssertEqual(x / y, 0)
XCTAssertEqual(y / x, -1)
XCTAssertEqual(y / y, 1)
XCTAssertEqual(x % 3, 1)
XCTAssertEqual(x % -3, 1)
XCTAssertEqual(y % 3, -1)
XCTAssertEqual(y % -3, -1)
XCTAssertEqual(-y, 1111)
XCTAssertEqual(-x, -1000)
}
func testNested() {
do {
let x = _UInt1024.max
let (y, o) = x.addingReportingOverflow(1)
XCTAssertEqual(y, 0)
XCTAssertTrue(y == (0 as Int))
XCTAssertTrue(o)
}
do {
let x = _Int1024.max
let (y, o) = x.addingReportingOverflow(1)
XCTAssertEqual(y, _Int1024.min)
XCTAssertLessThan(y, 0)
XCTAssertTrue(y < (0 as Int))
XCTAssertTrue(y < (0 as UInt))
XCTAssertTrue(o)
}
XCTAssertFalse(_UInt1024.isSigned)
XCTAssertEqual(_UInt1024.bitWidth, 1024)
XCTAssertTrue(_Int1024.isSigned)
XCTAssertEqual(_Int1024.bitWidth, 1024)
XCTAssertTrue(
_UInt1024.max.words.elementsEqual(
repeatElement(UInt.max, count: 1024 / UInt.bitWidth)
)
)
}
func testInitialization() {
XCTAssertTrue(_UInt16(UInt16.max) == UInt16.max)
XCTAssertNil(_UInt16(exactly: UInt32.max))
XCTAssertEqual(_UInt16(truncatingIfNeeded: UInt64.max), _UInt16.max)
}
func testInitialization_Overflow() {
// TODO: expectCrashLater()
// _ = _UInt16(UInt32.max)
}
func testMagnitude() {
XCTAssertTrue(_UInt16.min.magnitude == UInt16.min.magnitude)
XCTAssertTrue((42 as _UInt16).magnitude == (42 as UInt16).magnitude)
XCTAssertTrue(_UInt16.max.magnitude == UInt16.max.magnitude)
XCTAssertTrue(_Int16.min.magnitude == Int16.min.magnitude)
XCTAssertTrue((-42 as _Int16).magnitude == (-42 as Int16).magnitude)
XCTAssertTrue(_Int16().magnitude == Int16(0).magnitude) // See SR-6602.
XCTAssertTrue((42 as _Int16).magnitude == (42 as Int16).magnitude)
XCTAssertTrue(_Int16.max.magnitude == Int16.max.magnitude)
}
func testTwoWords() {
typealias DW = DoubleWidth<Int>
XCTAssertEqual(-1 as DW, DW(truncatingIfNeeded: -1 as Int8))
XCTAssertNil(Int(exactly: DW(Int.min) - 1))
XCTAssertNil(Int(exactly: DW(Int.max) + 1))
XCTAssertTrue(DW(Int.min) - 1 < Int.min)
XCTAssertTrue(DW(Int.max) + 1 > Int.max)
}
func testBitwise_LeftAndRightShifts() {
typealias _UInt64 = DoubleWidth<DoubleWidth<DoubleWidth<UInt8>>>
typealias _Int64 = DoubleWidth<DoubleWidth<DoubleWidth<Int8>>>
func f<T: FixedWidthInteger, U: FixedWidthInteger>(_ x: T, type: U.Type) {
let y = U(x)
XCTAssertEqual(T.bitWidth, U.bitWidth)
for i in -(T.bitWidth + 1)...(T.bitWidth + 1) {
XCTAssertTrue(x << i == y << i)
XCTAssertTrue(x >> i == y >> i)
XCTAssertTrue(x &<< i == y &<< i)
XCTAssertTrue(x &>> i == y &>> i)
}
}
f(1 as UInt64, type: _UInt64.self)
f(~(~0 as UInt64 >> 1), type: _UInt64.self)
f(UInt64.max, type: _UInt64.self)
// 0b01010101_10100101_11110000_10100101_11110000_10100101_11110000_10100101
f(17340530535757639845 as UInt64, type: _UInt64.self)
f(1 as Int64, type: _Int64.self)
f(Int64.min, type: _Int64.self)
f(Int64.max, type: _Int64.self)
// 0b01010101_10100101_11110000_10100101_11110000_10100101_11110000_10100101
f(6171603459878809765 as Int64, type: _Int64.self)
}
func testRemainder_ByZero() {
func f(_ x: _Int1024, _ y: _Int1024) -> _Int1024 {
return x % y
}
// TODO: expectCrashLater()
// _ = f(42, 0)
}
func testRemainder_ByMinusOne() {
func f(_ x: _Int256, _ y: _Int256) -> _Int256 {
return x.remainderReportingOverflow(dividingBy: y).partialValue
}
XCTAssertEqual(f(.max, -1), 0)
XCTAssertEqual(f(.min, -1), 0)
}
func testDivision_ByZero() {
func f(_ x: _Int1024, _ y: _Int1024) -> _Int1024 {
return x / y
}
// TODO: expectCrashLater()
// _ = f(42, 0)
}
func testDivision_ByMinusOne() {
func f(_ x: _Int1024) -> _Int1024 {
return x / -1
}
// TODO: expectCrashLater()
// _ = f(_Int1024.min)
}
func testMultipleOf() {
func isMultipleTest<T: FixedWidthInteger>(type: T.Type) {
XCTAssertTrue(T.min.isMultiple(of: 2))
XCTAssertFalse(T.max.isMultiple(of: 10))
// Test that these do not crash.
XCTAssertTrue((0 as T).isMultiple(of: 0))
XCTAssertFalse((1 as T).isMultiple(of: 0))
XCTAssertTrue(T.min.isMultiple(of: 0 &- 1))
}
isMultipleTest(type: _Int128.self)
isMultipleTest(type: _UInt128.self)
}
func testMultiplication_ByMinusOne() {
func f(_ x: _Int1024) -> _Int1024 {
return x * -1
}
// TODO: expectCrashLater()
// _ = f(_Int1024.min)
}
func testConversions() {
XCTAssertTrue(_Int16(1 << 15 - 1) == Int(1 << 15 - 1))
XCTAssertTrue(_Int16(-1 << 15) == Int(-1 << 15))
XCTAssertTrue(_UInt16(1 << 16 - 1) == Int(1 << 16 - 1))
XCTAssertTrue(_UInt16(0) == Int(0))
XCTAssertTrue(_Int16(Double(1 << 15 - 1)) == Int(1 << 15 - 1))
XCTAssertTrue(_Int16(Double(-1 << 15)) == Int(-1 << 15))
XCTAssertTrue(_UInt16(Double(1 << 16 - 1)) == Int(1 << 16 - 1))
XCTAssertTrue(_UInt16(Double(0)) == Int(0))
XCTAssertTrue(_Int16(Double(1 << 15 - 1) + 0.9) == Int(1 << 15 - 1))
XCTAssertTrue(_Int16(Double(-1 << 15) - 0.9) == Int(-1 << 15))
XCTAssertTrue(_UInt16(Double(1 << 16 - 1) + 0.9) == Int(1 << 16 - 1))
XCTAssertTrue(_UInt16(Double(0) - 0.9) == Int(0))
XCTAssertEqual(_Int16(0.00001), 0)
XCTAssertEqual(_UInt16(0.00001), 0)
}
func testConversions_Exact() {
XCTAssertEqual(
_Int16(Double(1 << 15 - 1)),
_Int16(exactly: Double(1 << 15 - 1))
)
XCTAssertEqual(
_Int16(Double(-1 << 15)),
_Int16(exactly: Double(-1 << 15))
)
XCTAssertEqual(
_UInt16(Double(1 << 16 - 1)),
_UInt16(exactly: Double(1 << 16 - 1))
)
XCTAssertEqual(
_UInt16(Double(0)),
_UInt16(exactly: Double(0))
)
XCTAssertNil(_Int16(exactly: Double(1 << 15 - 1) + 0.9))
XCTAssertNil(_Int16(exactly: Double(-1 << 15) - 0.9))
XCTAssertNil(_UInt16(exactly: Double(1 << 16 - 1) + 0.9))
XCTAssertNil(_UInt16(exactly: Double(0) - 0.9))
XCTAssertNil(_Int16(exactly: Double(1 << 15)))
XCTAssertNil(_Int16(exactly: Double(-1 << 15) - 1))
XCTAssertNil(_UInt16(exactly: Double(1 << 16)))
XCTAssertNil(_UInt16(exactly: Double(-1)))
XCTAssertNil(_Int16(exactly: 0.00001))
XCTAssertNil(_UInt16(exactly: 0.00001))
XCTAssertNil(_UInt16(exactly: Double.nan))
XCTAssertNil(_UInt16(exactly: Float.nan))
XCTAssertNil(_UInt16(exactly: Double.infinity))
XCTAssertNil(_UInt16(exactly: Float.infinity))
}
func testConversions_SignedMax() {
// TODO: expectCrashLater()
// _ = _Int16(1 << 15)
}
func testConversions_SignedMin() {
// TODO: expectCrashLater()
// _ = _Int16(-1 << 15 - 1)
}
func testConversions_UnsignedMax() {
// TODO: expectCrashLater()
// _ = _UInt16(1 << 16)
}
func testConversions_UnsignedMin() {
// TODO: expectCrashLater()
// _ = _UInt16(-1)
}
func testConversions_ToAndFromString<Number: FixedWidthInteger>(
_ expectedNumber: Number,
_ expectedString: String,
radix: Int,
file: StaticString = #filePath,
line: UInt = #line
) {
let actualString = String(expectedNumber, radix: radix)
XCTAssertEqual(expectedString, actualString, file: file, line: line)
let actualNumber = Number(expectedString, radix: radix)
XCTAssertEqual(expectedNumber, actualNumber, file: file, line: line)
}
func testConversions_ToAndFromString_Binary() {
testConversions_ToAndFromString(
_Int128.max,
"""
111111111111111111111111111111111111111111111111111111111111111\
1111111111111111111111111111111111111111111111111111111111111111
""",
radix: 2
)
testConversions_ToAndFromString(
_Int128.min,
"""
-1000000000000000000000000000000000000000000000000000000000000000\
0000000000000000000000000000000000000000000000000000000000000000
""",
radix: 2
)
}
func testConversions_ToAndFromString_Decimal() {
testConversions_ToAndFromString(
_Int256.max,
"""
5789604461865809771178549250434395392663\
4992332820282019728792003956564819967
""",
radix: 10
)
testConversions_ToAndFromString(
_Int256.min,
"""
-5789604461865809771178549250434395392663\
4992332820282019728792003956564819968
""",
radix: 10
)
}
func testConversions_ToAndFromString_Hexadecimal() {
testConversions_ToAndFromString(
_Int512.max,
"""
7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
""",
radix: 16
)
testConversions_ToAndFromString(
_Int512.min,
"""
-8000000000000000000000000000000000000000000000000000000000000000\
0000000000000000000000000000000000000000000000000000000000000000
""",
radix: 16
)
}
func testWords() {
XCTAssertTrue(_Int16(0).words.elementsEqual([0]))
XCTAssertTrue(_Int16(1).words.elementsEqual([1]))
XCTAssertTrue(_Int16(-1).words.elementsEqual([UInt.max]))
XCTAssertTrue(_Int16(256).words.elementsEqual([256]))
XCTAssertTrue(_Int16(-256).words.elementsEqual([UInt.max - 255]))
XCTAssertTrue(_Int16.max.words.elementsEqual([32767]))
XCTAssertTrue(_Int16.min.words.elementsEqual([UInt.max - 32767]))
XCTAssertTrue(
(0 as _Int1024).words.elementsEqual(
repeatElement(0 as UInt, count: 1024 / UInt.bitWidth)
)
)
XCTAssertTrue(
(-1 as _Int1024).words.elementsEqual(
repeatElement(UInt.max, count: 1024 / UInt.bitWidth)
)
)
XCTAssertTrue(
(1 as _Int1024).words.elementsEqual(
[1] + Array(repeating: 0, count: 1024 / UInt.bitWidth - 1)
)
)
}
func testConditionalConformance() {
func checkSignedIntegerConformance<T: SignedInteger>(_: T) {}
func checkUnsignedIntegerConformance<T: UnsignedInteger>(_: T) {}
checkSignedIntegerConformance(0 as _Int128)
checkSignedIntegerConformance(0 as _Int1024)
checkUnsignedIntegerConformance(0 as _UInt128)
checkUnsignedIntegerConformance(0 as _UInt1024)
}
}
@@ -0,0 +1,44 @@
//===--- GCDTests.swift ---------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 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 IntegerUtilities
import XCTest
final class IntegerUtilitiesGCDTests: XCTestCase {
func testGCDInt() {
XCTAssertEqual(gcd(0, 0), 0)
XCTAssertEqual(gcd(0, 1), 1)
XCTAssertEqual(gcd(1, 0), 1)
XCTAssertEqual(gcd(0, -1), 1)
XCTAssertEqual(gcd(1, 1), 1)
XCTAssertEqual(gcd(1, 2), 1)
XCTAssertEqual(gcd(2, 2), 2)
XCTAssertEqual(gcd(4, 2), 2)
XCTAssertEqual(gcd(6, 8), 2)
XCTAssertEqual(gcd(77, 91), 7)
XCTAssertEqual(gcd(24, -36), 12)
XCTAssertEqual(gcd(-24, -36), 12)
XCTAssertEqual(gcd(51, 34), 17)
XCTAssertEqual(gcd(64, 96), 32)
XCTAssertEqual(gcd(-64, 96), 32)
XCTAssertEqual(gcd(4*7*19, 27*25), 1)
XCTAssertEqual(gcd(16*315, 11*315), 315)
XCTAssertEqual(gcd(97*67*53*27*8, 83*67*53*9*32), 67*53*9*8)
XCTAssertEqual(gcd(Int.min, 2), 2)
// TODO: Enable these when version compatibility allows.
//
// XCTExpectFailure{ gcd(0, Int.min) }
// XCTExpectFailure{ gcd(Int.min, 0) }
// XCTExpectFailure{ gcd(Int.min, Int.min) }
}
}
@@ -0,0 +1,74 @@
//===--- RotateTests.swift ------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 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 IntegerUtilities
import XCTest
final class IntegerUtilitiesRotateTests: XCTestCase {
func testRotateUInt8() {
let x: UInt8 = 0b10011100
XCTAssertEqual(0b01001110, x.rotated(right:-7))
XCTAssertEqual(0b00100111, x.rotated(right:-6))
XCTAssertEqual(0b10010011, x.rotated(right:-5))
XCTAssertEqual(0b11001001, x.rotated(right:-4))
XCTAssertEqual(0b11100100, x.rotated(right:-3))
XCTAssertEqual(0b01110010, x.rotated(right:-2))
XCTAssertEqual(0b00111001, x.rotated(right:-1))
XCTAssertEqual(0b10011100, x.rotated(right: 0))
XCTAssertEqual(0b01001110, x.rotated(right: 1))
XCTAssertEqual(0b00100111, x.rotated(right: 2))
XCTAssertEqual(0b10010011, x.rotated(right: 3))
XCTAssertEqual(0b11001001, x.rotated(right: 4))
XCTAssertEqual(0b11100100, x.rotated(right: 5))
XCTAssertEqual(0b01110010, x.rotated(right: 6))
XCTAssertEqual(0b00111001, x.rotated(right: 7))
XCTAssertEqual(0b10011100, x.rotated(right: 8))
}
func testRotateInt16() {
let x = Int16(bitPattern: 0b1001110000111110)
XCTAssertEqual(Int16(bitPattern: 0b1001110000111110), x.rotated(left:-16))
XCTAssertEqual(Int16(bitPattern: 0b0011100001111101), x.rotated(left:-15))
XCTAssertEqual(Int16(bitPattern: 0b0111000011111010), x.rotated(left:-14))
XCTAssertEqual(Int16(bitPattern: 0b1110000111110100), x.rotated(left:-13))
XCTAssertEqual(Int16(bitPattern: 0b1100001111101001), x.rotated(left:-12))
XCTAssertEqual(Int16(bitPattern: 0b1000011111010011), x.rotated(left:-11))
XCTAssertEqual(Int16(bitPattern: 0b0000111110100111), x.rotated(left:-10))
XCTAssertEqual(Int16(bitPattern: 0b0001111101001110), x.rotated(left:-9))
XCTAssertEqual(Int16(bitPattern: 0b0011111010011100), x.rotated(left:-8))
XCTAssertEqual(Int16(bitPattern: 0b0111110100111000), x.rotated(left:-7))
XCTAssertEqual(Int16(bitPattern: 0b1111101001110000), x.rotated(left:-6))
XCTAssertEqual(Int16(bitPattern: 0b1111010011100001), x.rotated(left:-5))
XCTAssertEqual(Int16(bitPattern: 0b1110100111000011), x.rotated(left:-4))
XCTAssertEqual(Int16(bitPattern: 0b1101001110000111), x.rotated(left:-3))
XCTAssertEqual(Int16(bitPattern: 0b1010011100001111), x.rotated(left:-2))
XCTAssertEqual(Int16(bitPattern: 0b0100111000011111), x.rotated(left:-1))
XCTAssertEqual(Int16(bitPattern: 0b1001110000111110), x.rotated(left: 0))
XCTAssertEqual(Int16(bitPattern: 0b0011100001111101), x.rotated(left: 1))
XCTAssertEqual(Int16(bitPattern: 0b0111000011111010), x.rotated(left: 2))
XCTAssertEqual(Int16(bitPattern: 0b1110000111110100), x.rotated(left: 3))
XCTAssertEqual(Int16(bitPattern: 0b1100001111101001), x.rotated(left: 4))
XCTAssertEqual(Int16(bitPattern: 0b1000011111010011), x.rotated(left: 5))
XCTAssertEqual(Int16(bitPattern: 0b0000111110100111), x.rotated(left: 6))
XCTAssertEqual(Int16(bitPattern: 0b0001111101001110), x.rotated(left: 7))
XCTAssertEqual(Int16(bitPattern: 0b0011111010011100), x.rotated(left: 8))
XCTAssertEqual(Int16(bitPattern: 0b0111110100111000), x.rotated(left: 9))
XCTAssertEqual(Int16(bitPattern: 0b1111101001110000), x.rotated(left: 10))
XCTAssertEqual(Int16(bitPattern: 0b1111010011100001), x.rotated(left: 11))
XCTAssertEqual(Int16(bitPattern: 0b1110100111000011), x.rotated(left: 12))
XCTAssertEqual(Int16(bitPattern: 0b1101001110000111), x.rotated(left: 13))
XCTAssertEqual(Int16(bitPattern: 0b1010011100001111), x.rotated(left: 14))
XCTAssertEqual(Int16(bitPattern: 0b0100111000011111), x.rotated(left: 15))
XCTAssertEqual(Int16(bitPattern: 0b1001110000111110), x.rotated(left: 16))
}
}
@@ -0,0 +1,192 @@
//===--- SaturatingArithmeticTests.swift ----------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2023 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 IntegerUtilities
import XCTest
import _TestSupport
final class IntegerUtilitiesSaturatingTests: XCTestCase {
func testSaturatingAddSigned() {
for a in Int8.min ... Int8.max {
for b in Int8.min ... Int8.max {
let expected = Int8(clamping: Int16(a) + Int16(b))
let observed = a.addingWithSaturation(b)
if expected != observed {
print("Error found in (\(a)).addingWithSaturation(\(b)).")
print("Expected: \(String(expected, radix: 16))")
print("Observed: \(String(observed, radix: 16))")
XCTFail()
return
}
}
}
}
func testSaturatingSubSigned() {
for a in Int8.min ... Int8.max {
for b in Int8.min ... Int8.max {
let expected = Int8(clamping: Int16(a) - Int16(b))
let observed = a.subtractingWithSaturation(b)
if expected != observed {
print("Error found in (\(a)).subtractingWithSaturation(\(b)).")
print("Expected: \(String(expected, radix: 16))")
print("Observed: \(String(observed, radix: 16))")
XCTFail()
return
}
}
}
}
func testSaturatingNegSigned() {
for a in Int8.min ... Int8.max {
let expected = Int8(clamping: 0 - Int16(a))
let observed = a.negatedWithSaturation()
if expected != observed {
print("Error found in (\(a)).negatedWithSaturation().")
print("Expected: \(String(expected, radix: 16))")
print("Observed: \(String(observed, radix: 16))")
XCTFail()
return
}
}
}
func testSaturatingMulSigned() {
for a in Int8.min ... Int8.max {
for b in Int8.min ... Int8.max {
let expected = Int8(clamping: Int16(a) * Int16(b))
let observed = a.multipliedWithSaturation(by: b)
if expected != observed {
print("Error found in (\(a)).multipliedWithSaturation(by: \(b)).")
print("Expected: \(String(expected, radix: 16))")
print("Observed: \(String(observed, radix: 16))")
XCTFail()
return
}
}
}
}
func testSaturatingAddUnsigned() {
for a in UInt8.min ... UInt8.max {
for b in UInt8.min ... UInt8.max {
let expected = UInt8(clamping: UInt16(a) + UInt16(b))
let observed = a.addingWithSaturation(b)
if expected != observed {
print("Error found in (\(a)).addingWithSaturation(\(b)).")
print("Expected: \(String(expected, radix: 16))")
print("Observed: \(String(observed, radix: 16))")
XCTFail()
return
}
}
}
}
func testSaturatingSubUnsigned() {
for a in UInt8.min ... UInt8.max {
for b in UInt8.min ... UInt8.max {
let expected = UInt8(clamping: Int16(a) - Int16(b))
let observed = a.subtractingWithSaturation(b)
if expected != observed {
print("Error found in (\(a)).subtractingWithSaturation(\(b)).")
print("Expected: \(String(expected, radix: 16))")
print("Observed: \(String(observed, radix: 16))")
XCTFail()
return
}
}
}
}
func testSaturatingNegUnsigned() {
for a in UInt8.min ... UInt8.max {
let observed = a.negatedWithSaturation()
if 0 != observed {
print("Error found in (\(a)).negatedWithSaturation().")
print("Expected: zero")
print("Observed: \(String(observed, radix: 16))")
XCTFail()
return
}
}
}
func testSaturatingMulUnsigned() {
for a in UInt8.min ... UInt8.max {
for b in UInt8.min ... UInt8.max {
let expected = UInt8(clamping: UInt16(a) * UInt16(b))
let observed = a.multipliedWithSaturation(by: b)
if expected != observed {
print("Error found in (\(a)).multipliedWithSaturation(by: \(b)).")
print("Expected: \(String(expected, radix: 16))")
print("Observed: \(String(observed, radix: 16))")
XCTFail()
}
}
}
}
func testSaturatingShift<T, C>(
_ value: T, _ count: C, rounding rule: RoundingRule
) where T: FixedWidthInteger, C: FixedWidthInteger {
let observed = value.shiftedWithSaturation(leftBy: count, rounding: rule)
var expected: T = 0
if count <= 0 {
expected = value.shifted(rightBy: -Int64(count), rounding: rule)
} else {
let multiplier: T = 1 << count
if multiplier <= 0 {
expected = value == 0 ? 0 :
value < 0 ? .min : .max
} else {
expected = value.multipliedWithSaturation(by: multiplier)
}
}
if observed != expected {
print("Error found in \(T.self).shiftedWithSaturation(leftBy: \(count), rounding: \(rule)).")
print(" Value: \(String(value, radix: 16))")
print("Expected: \(String(expected, radix: 16))")
print("Observed: \(String(observed, radix: 16))")
XCTFail()
return
}
}
func testSaturatingShift<T: FixedWidthInteger>(
_ type: T.Type, rounding rule: RoundingRule
) {
for count in Int8.min ... .max {
testSaturatingShift(0, count, rounding: rule)
for bits in 0 ..< T.bitWidth {
let msb: T.Magnitude = 1 << bits
let value = T(truncatingIfNeeded: msb) | .random(in: 0 ... T(msb-1))
testSaturatingShift(value, count, rounding: rule)
testSaturatingShift(0 &- value, count, rounding: rule)
}
}
}
func testSaturatingShifts() {
testSaturatingShift(Int8.self, rounding: .toOdd)
testSaturatingShift(UInt8.self, rounding: .toOdd)
testSaturatingShift(Int.self, rounding: .toOdd)
testSaturatingShift(UInt.self, rounding: .toOdd)
}
func testEdgeCaseForNegativeCount() {
XCTAssertEqual(1.shiftedWithSaturation(leftBy: Int.min), 0)
}
}
@@ -0,0 +1,197 @@
//===--- ShiftTests.swift -------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 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 IntegerUtilities
import XCTest
import _TestSupport
final class IntegerUtilitiesShiftTests: XCTestCase {
func testRoundingShift<T, C>(
_ value: T, _ count: C, rounding rule: RoundingRule
) where T: FixedWidthInteger, C: BinaryInteger {
let floor = value >> count
let lost = value &- floor << count
let exact = count <= 0 || lost == 0
let ceiling = exact ? floor : floor &+ 1
let expected: T
switch rule {
case .down:
expected = floor
case .up:
expected = ceiling
case .towardZero:
expected = value < 0 ? ceiling : floor
case .awayFromZero:
expected = value > 0 ? ceiling : floor
case .toOdd:
expected = floor | (exact ? 0 : 1)
case .toNearestOrAwayFromZero:
if exact { expected = floor }
else {
let step = value.shifted(rightBy: count - 2, rounding: .toOdd)
switch step & 0b11 {
case 0b01: expected = floor
case 0b10: expected = value > 0 ? ceiling : floor
case 0b11: expected = ceiling
default: preconditionFailure()
}
}
case .toNearestOrEven:
if exact { expected = floor }
else {
let step = value.shifted(rightBy: count - 2, rounding: .toOdd)
switch step & 0b11 {
case 0b01: expected = floor
case 0b10: expected = floor & 1 == 0 ? floor : ceiling
case 0b11: expected = ceiling
default: preconditionFailure()
}
}
case .stochastically:
// Just test that it's floor if exact, otherwise either floor
// or ceiling.
if exact { expected = floor }
else {
let observed = value.shifted(rightBy: count, rounding: rule)
if observed != floor && observed != ceiling {
print("Error found in \(T.self).shifted(rightBy: \(count), rounding: \(rule)).")
print(" Value: \(String(value, radix: 16))")
print("Expected: \(String(floor, radix: 16)) or \(String(ceiling, radix: 16))")
print("Observed: \(String(observed, radix: 16))")
XCTFail()
}
return
}
case .requireExact:
preconditionFailure()
}
let observed = value.shifted(rightBy: count, rounding: rule)
if observed != expected {
print("Error found in \(T.self).shifted(rightBy: \(count), rounding: \(rule)).")
print(" Value: \(String(value, radix: 16))")
print("Expected: \(String(expected, radix: 16))")
print("Observed: \(String(observed, radix: 16))")
XCTFail()
}
}
func testRoundingShift<T: FixedWidthInteger>(
_ type: T.Type, rounding rule: RoundingRule
) {
for count in -2*T.bitWidth ... 2*T.bitWidth {
// zero shifted by anything is always zero
XCTAssertEqual(0, (0 as T).shifted(rightBy: count, rounding: rule))
for _ in 0 ..< 100 {
testRoundingShift(T.random(in: .min ... .max), count, rounding: rule)
}
}
for count in Int8.min ... .max {
testRoundingShift(T.random(in: .min ... .max), count, rounding: rule)
}
}
func testRoundingShifts() {
testRoundingShift(Int8.self, rounding: .down)
testRoundingShift(Int8.self, rounding: .up)
testRoundingShift(Int8.self, rounding: .towardZero)
testRoundingShift(Int8.self, rounding: .awayFromZero)
testRoundingShift(Int8.self, rounding: .toOdd)
testRoundingShift(Int8.self, rounding: .toNearestOrAwayFromZero)
testRoundingShift(Int8.self, rounding: .toNearestOrEven)
testRoundingShift(Int8.self, rounding: .stochastically)
testRoundingShift(UInt8.self, rounding: .down)
testRoundingShift(UInt8.self, rounding: .up)
testRoundingShift(UInt8.self, rounding: .towardZero)
testRoundingShift(UInt8.self, rounding: .awayFromZero)
testRoundingShift(UInt8.self, rounding: .toOdd)
testRoundingShift(UInt8.self, rounding: .toNearestOrAwayFromZero)
testRoundingShift(UInt8.self, rounding: .toNearestOrEven)
testRoundingShift(UInt8.self, rounding: .stochastically)
testRoundingShift(Int.self, rounding: .down)
testRoundingShift(Int.self, rounding: .up)
testRoundingShift(Int.self, rounding: .towardZero)
testRoundingShift(Int.self, rounding: .awayFromZero)
testRoundingShift(Int.self, rounding: .toOdd)
testRoundingShift(Int.self, rounding: .toNearestOrAwayFromZero)
testRoundingShift(Int.self, rounding: .toNearestOrEven)
testRoundingShift(Int.self, rounding: .stochastically)
testRoundingShift(UInt.self, rounding: .down)
testRoundingShift(UInt.self, rounding: .up)
testRoundingShift(UInt.self, rounding: .towardZero)
testRoundingShift(UInt.self, rounding: .awayFromZero)
testRoundingShift(UInt.self, rounding: .toOdd)
testRoundingShift(UInt.self, rounding: .toNearestOrAwayFromZero)
testRoundingShift(UInt.self, rounding: .toNearestOrEven)
testRoundingShift(UInt.self, rounding: .stochastically)
}
// Stochastic rounding doesn't have a deterministic "expected" answer,
// but we know that the result must be either the floor or the ceiling.
// The above tests ensure that, but that's not a very strong guarantee;
// an implementation could just implement it as self >> count and pass
// that test.
//
// Here we round the _same_ value many times, compute the average, and
// check that it is acceptably close to the exact expected value; simple
// use of any deterministic rounding rule will not achieve this.
func testStochasticAverage<T: FixedWidthInteger>(_ value: T) {
var fails = 0
for count in 1 ... T.bitWidth {
let sum = (0..<256).reduce(into: DoubleWidth<T>.zero) { sum, _ in
let rounded = value.shifted(rightBy: count, rounding: .stochastically)
sum += DoubleWidth(rounded)
}
let expected = DoubleWidth<T>(value) << (8 - count)
let difference = sum >= expected ? sum - expected : expected - sum
// Waving my hands slightly instead of giving a precise explanation
// here, the expectation is that difference should be about
// 1/2 sqrt(256). If it's repeatedly bigger than that, we _may_
// have a problem, but it's OK for this to fail occasionally.
//
// TODO: precise justification of thresholds
if difference > 8 { fails += 1 }
// On the other hand, if we're more than a couple standard deviations
// off, we should flag that. This still isn't _necessarily_ a problem,
// but if you see a repeated failure for a given shift count, that's
// almost surely a real bug.
XCTAssertLessThanOrEqual(difference, 32,
"Accumulated error (\(difference)) was unexpectedly large in \(value).shifted(rightBy: \(count))"
)
}
// Threshold chosen so that this is expected to _usually_ pass, but
// it will fail sporadically even with a correct implementation. This is
// not a great fit for CI workflows, sorry. Basically ignore one-off
// failures, but a repeated failure here is an indication that a bug
// exists.
XCTAssertLessThanOrEqual(fails, T.bitWidth/2,
"Accumulated error was large more often than expected for \(value).shifted(rightBy:)"
)
}
func testStochasticShifts() {
testStochasticAverage(Int8.random(in: .min ... .max))
testStochasticAverage(Int16.random(in: .min ... .max))
testStochasticAverage(Int32.random(in: .min ... .max))
testStochasticAverage(UInt8.random(in: .min ... .max))
testStochasticAverage(UInt16.random(in: .min ... .max))
testStochasticAverage(UInt32.random(in: .min ... .max))
testStochasticAverage(Int64.random(in: .min ... .max))
testStochasticAverage(UInt64.random(in: .min ... .max))
testStochasticAverage(DoubleWidth<Int64>.random(in: .min ... .max))
testStochasticAverage(DoubleWidth<UInt64>.random(in: .min ... .max))
}
}
@@ -0,0 +1,145 @@
//===--- ApproximateEqualityTests.swift -----------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import RealModule
import XCTest
import _TestSupport
final class ApproximateEqualityTests: XCTestCase {
func testSpecials<T: Real>(absolute tol: T) {
let zero = T.zero
let gfm = T.greatestFiniteMagnitude
let inf = T.infinity
let nan = T.nan
XCTAssertTrue(zero.isApproximatelyEqual(to: zero, absoluteTolerance: tol))
XCTAssertTrue(zero.isApproximatelyEqual(to:-zero, absoluteTolerance: tol))
XCTAssertFalse(inf.isApproximatelyEqual(to: gfm, absoluteTolerance: tol))
XCTAssertFalse(gfm.isApproximatelyEqual(to: inf, absoluteTolerance: tol))
XCTAssertTrue(inf.isApproximatelyEqual(to: inf, absoluteTolerance: tol))
XCTAssertTrue(inf.isApproximatelyEqual(to: inf, absoluteTolerance: tol))
XCTAssertFalse(nan.isApproximatelyEqual(to: nan, absoluteTolerance: tol))
}
func testSpecials<T: Real>(relative tol: T) {
let zero = T.zero
let gfm = T.greatestFiniteMagnitude
let inf = T.infinity
let nan = T.nan
XCTAssertTrue(zero.isApproximatelyEqual(to: zero, relativeTolerance: tol))
XCTAssertTrue(zero.isApproximatelyEqual(to:-zero, relativeTolerance: tol))
XCTAssertFalse(inf.isApproximatelyEqual(to: gfm, relativeTolerance: tol))
XCTAssertFalse(gfm.isApproximatelyEqual(to: inf, relativeTolerance: tol))
XCTAssertTrue(inf.isApproximatelyEqual(to: inf, relativeTolerance: tol))
XCTAssertTrue(inf.isApproximatelyEqual(to: inf, relativeTolerance: tol))
XCTAssertFalse(nan.isApproximatelyEqual(to: nan, relativeTolerance: tol))
}
func testSpecials<T: Real>(_ type: T.Type) {
XCTAssertTrue(T.zero.isApproximatelyEqual(to: .zero))
XCTAssertTrue(T.zero.isApproximatelyEqual(to:-.zero))
testSpecials(absolute: T.zero)
testSpecials(absolute: T.leastNormalMagnitude)
testSpecials(absolute: T.greatestFiniteMagnitude)
testSpecials(relative: T.zero)
testSpecials(relative: T.ulpOfOne)
testSpecials(relative: T(1).nextDown)
testSpecials(relative: T(1))
}
func testDefaults<T: Real>(_ type: T.Type) {
let e = T.ulpOfOne.squareRoot()
XCTAssertTrue(T(1).isApproximatelyEqual(to: 1 + e))
XCTAssertTrue(T(1).isApproximatelyEqual(to: 1 - e/2))
XCTAssertFalse(T(1).isApproximatelyEqual(to: 1 + 2*e))
XCTAssertFalse(T(1).isApproximatelyEqual(to: 1 - 3*e/2))
}
func testRandom<T>(_ type: T.Type) where T: FixedWidthFloatingPoint & Real {
var g = SystemRandomNumberGenerator()
// Generate a bunch of random values in a small interval and a tolerance
// and use them to check that various properties that we would like to
// hold actually do.
var x = [1] + (0 ..< 64).map {
_ in T.random(in: 1 ..< 2, using: &g)
} + [2]
x.sort()
// We have 66 values in 1 ... 2, so if we use a tolerance of around 1/64,
// at least some of the pairs will compare equal with tolerance.
let tol = T.random(in: 1/64 ... 1/32, using: &g)
// We're going to walk the values in order, validating that some common-
// sense properties hold.
for i in x.indices {
// reflexivity
XCTAssertTrue(x[i].isApproximatelyEqual(to: x[i]))
XCTAssertTrue(x[i].isApproximatelyEqual(to: x[i], relativeTolerance: tol))
XCTAssertTrue(x[i].isApproximatelyEqual(to: x[i], absoluteTolerance: tol))
for j in i ..< x.endIndex {
// commutativity
XCTAssertTrue(
x[i].isApproximatelyEqual(to: x[j], relativeTolerance: tol) ==
x[j].isApproximatelyEqual(to: x[i], relativeTolerance: tol)
)
XCTAssertTrue(
x[i].isApproximatelyEqual(to: x[j], absoluteTolerance: tol) ==
x[j].isApproximatelyEqual(to: x[i], absoluteTolerance: tol)
)
// scale invariance for relative comparisons
let scale = T(
sign:.plus,
exponent: T.Exponent.random(in: T.leastNormalMagnitude.exponent ..< T.greatestFiniteMagnitude.exponent),
significand: 1
)
XCTAssertTrue(
x[i].isApproximatelyEqual(to: x[j], relativeTolerance: tol) ==
(scale*x[i]).isApproximatelyEqual(to: scale*x[j], relativeTolerance: tol)
)
}
// if a ≤ b ≤ c, and a ≈ c, then a ≈ b and b ≈ c (relative tolerance)
var left = x.firstIndex { x[i].isApproximatelyEqual(to: $0, relativeTolerance: tol) }
var right = x.lastIndex { x[i].isApproximatelyEqual(to: $0, relativeTolerance: tol) }
if let l = left, let r = right {
for j in l ..< r {
XCTAssertTrue(x[i].isApproximatelyEqual(to: x[j], relativeTolerance: tol))
}
}
// if a ≤ b ≤ c, and a ≈ c, then a ≈ b and b ≈ c (absolute tolerance)
left = x.firstIndex { x[i].isApproximatelyEqual(to: $0, absoluteTolerance: tol) }
right = x.lastIndex { x[i].isApproximatelyEqual(to: $0, absoluteTolerance: tol) }
if let l = left, let r = right {
for j in l ..< r {
XCTAssertTrue(x[i].isApproximatelyEqual(to: x[j], absoluteTolerance: tol))
}
}
}
}
func testFloat() {
testSpecials(Float.self)
testDefaults(Float.self)
testRandom(Float.self)
}
func testDouble() {
testSpecials(Double.self)
testDefaults(Double.self)
testRandom(Double.self)
}
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
func testFloat80() {
testSpecials(Float80.self)
testDefaults(Float80.self)
testRandom(Float80.self)
}
#endif
}
@@ -0,0 +1,160 @@
//===--- AugmentedArithmeticTests.swift -----------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 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 AugmentedArithmeticTests: XCTestCase {
func testTwoSumSpecials<T: Real & FixedWidthFloatingPoint>(_: T.Type) {
// Must be exact and not overflow on outer bounds
var x = T.greatestFiniteMagnitude
var y = -T.greatestFiniteMagnitude
XCTAssertEqual(Augmented.sum(x, y).head, .zero)
XCTAssertEqual(Augmented.sum(x, y).tail, .zero)
XCTAssert(Augmented.sum(x, y).head.isFinite)
XCTAssert(Augmented.sum(x, y).tail.isFinite)
// Must be exact on lower subnormal bounds
x = T.leastNonzeroMagnitude
y = -T.leastNonzeroMagnitude
XCTAssertEqual(Augmented.sum(x, y).head, .zero)
XCTAssertEqual(Augmented.sum(x, y).tail, .zero)
// Must preserve floating point signs for:
// (1) (+0) + (-0) == +0
// (2) (-0) + (+0) == +0
// (3) (-0) + (-0) == -0
x = T(sign: .plus, exponent: 1, significand: 0)
y = T(sign: .minus, exponent: 1, significand: 0)
XCTAssertEqual(Augmented.sum(x, y).head.sign, .plus) // (1)
XCTAssertEqual(Augmented.sum(x, y).tail.sign, .plus)
x = T(sign: .minus, exponent: 1, significand: 0)
y = T(sign: .plus, exponent: 1, significand: 0)
XCTAssertEqual(Augmented.sum(x, y).head.sign, .plus) // (2)
XCTAssertEqual(Augmented.sum(x, y).tail.sign, .plus)
x = T(sign: .minus, exponent: 1, significand: 0)
y = T(sign: .minus, exponent: 1, significand: 0)
XCTAssertEqual(Augmented.sum(x, y).head.sign, .minus) // (3)
XCTAssertEqual(Augmented.sum(x, y).tail.sign, .plus)
// Infinity and NaN are propagated correctly
XCTAssertEqual(Augmented.sum( 0, T.infinity).head, T.infinity)
XCTAssertEqual(Augmented.sum( T.infinity, 0 ).head, T.infinity)
XCTAssertEqual(Augmented.sum( T.infinity, T.infinity).head, T.infinity)
XCTAssertEqual(Augmented.sum( 0, -T.infinity).head, -T.infinity)
XCTAssertEqual(Augmented.sum(-T.infinity, 0 ).head, -T.infinity)
XCTAssertEqual(Augmented.sum(-T.infinity, -T.infinity).head, -T.infinity)
XCTAssert(Augmented.sum( T.infinity, -T.infinity).head.isNaN)
XCTAssert(Augmented.sum(-T.infinity, T.infinity).head.isNaN)
XCTAssert(Augmented.sum( T.infinity, T.nan).head.isNaN)
XCTAssert(Augmented.sum( T.nan, T.infinity).head.isNaN)
XCTAssert(Augmented.sum(-T.infinity, T.nan).head.isNaN)
XCTAssert(Augmented.sum( T.nan, -T.infinity).head.isNaN)
XCTAssert(Augmented.sum( 0, T.nan).head.isNaN)
XCTAssert(Augmented.sum(T.nan, 0).head.isNaN)
XCTAssert(Augmented.sum(T.nan, T.nan).head.isNaN)
}
func testTwoSumRandomValues<T: Real & FixedWidthFloatingPoint>(_: T.Type) {
// For randomly-chosen well-scaled finite values, we expect:
// (1) `head` to be exactly the IEEE 754 sum of `a + b`
// (2) `tail` to be less than or equal `head.ulp/2`
// (3) the result of `twoSum` for unordered input to be exactly equal to
// the result of `fastTwoSum` for ordered input.
var g = SystemRandomNumberGenerator()
let values: [T] = (0 ..< 100).map { _ in
T.random(
in: T.ulpOfOne ..< 1,
using: &g)
}
for a in values {
for b in values {
let twoSum = Augmented.sum(a, b)
XCTAssertEqual(twoSum.head, a + b) // (1)
XCTAssert(twoSum.tail.magnitude <= twoSum.head.ulp/2) // (2)
let x: T = a.magnitude < b.magnitude ? b : a
let y: T = a.magnitude < b.magnitude ? a : b
let fastTwoSum = Augmented.sum(large: x, small: y)
XCTAssertEqual(twoSum.head, fastTwoSum.head) // (3)
XCTAssertEqual(twoSum.tail, fastTwoSum.tail) // (3)
}
}
}
func testTwoSumCancellation<T: Real & FixedWidthFloatingPoint>(_: T.Type) {
// Must be exact for exactly representable values
XCTAssertEqual(Augmented.sum( 0.984375, 1.375).head, 2.359375)
XCTAssertEqual(Augmented.sum( 0.984375, 1.375).tail, 0.0)
XCTAssertEqual(Augmented.sum(-0.984375, 1.375).head, 0.390625)
XCTAssertEqual(Augmented.sum(-0.984375, 1.375).tail, 0.0)
XCTAssertEqual(Augmented.sum( 0.984375,-1.375).head,-0.390625)
XCTAssertEqual(Augmented.sum( 0.984375,-1.375).tail, 0.0)
XCTAssertEqual(Augmented.sum(-0.984375,-1.375).head,-2.359375)
XCTAssertEqual(Augmented.sum(-0.984375,-1.375).tail, 0.0)
XCTAssertEqual(Augmented.sum( 1.375, 0.984375).head, 2.359375)
XCTAssertEqual(Augmented.sum( 1.375, 0.984375).tail, 0.0)
XCTAssertEqual(Augmented.sum( 1.375,-0.984375).head, 0.390625)
XCTAssertEqual(Augmented.sum( 1.375,-0.984375).tail, 0.0)
XCTAssertEqual(Augmented.sum(-1.375, 0.984375).head,-0.390625)
XCTAssertEqual(Augmented.sum(-1.375, 0.984375).tail, 0.0)
XCTAssertEqual(Augmented.sum(-1.375,-0.984375).head,-2.359375)
XCTAssertEqual(Augmented.sum(-1.375,-0.984375).tail, 0.0)
// Must handle cancellation when `b` is not representable in `a` and
// we expect `b` to be lost entirely in the calculation of `a + b`.
var a: T = 1.0
var b: T = .ulpOfOne * .ulpOfOne
var twoSum = Augmented.sum(a, b)
XCTAssertEqual(twoSum.head, a) // a + b = a
XCTAssertEqual(twoSum.tail, b) // Error: b
twoSum = Augmented.sum( a, -b)
XCTAssertEqual(twoSum.head, a)
XCTAssertEqual(twoSum.tail,-b)
twoSum = Augmented.sum(-a, b)
XCTAssertEqual(twoSum.head,-a)
XCTAssertEqual(twoSum.tail, b)
twoSum = Augmented.sum(-a, -b)
XCTAssertEqual(twoSum.head,-a)
XCTAssertEqual(twoSum.tail,-b)
// Must handle cancellation when `b` is only partially representable in `a`.
// We expect the fractional digits of `b` to be cancelled in the following
// example but the fractional digits to be preserved in `tail`.
let exponent = T.Exponent(T.significandBitCount + 1)
a = T(sign: .plus, exponent: exponent, significand: 1.0)
b = 256 + 0.5
twoSum = Augmented.sum( a, b)
XCTAssertEqual(twoSum.head, a + 256)
XCTAssertEqual(twoSum.tail, 0.5)
twoSum = Augmented.sum( a, -b)
XCTAssertEqual(twoSum.head, a - 256)
XCTAssertEqual(twoSum.tail, -0.5)
twoSum = Augmented.sum(-a, b)
XCTAssertEqual(twoSum.head, -a + 256)
XCTAssertEqual(twoSum.tail, 0.5)
twoSum = Augmented.sum(-a, -b)
XCTAssertEqual(twoSum.head, -a - 256)
XCTAssertEqual(twoSum.tail, -0.5)
}
func testTwoSum() {
testTwoSumSpecials(Float32.self)
testTwoSumRandomValues(Float32.self)
testTwoSumCancellation(Float32.self)
testTwoSumSpecials(Float64.self)
testTwoSumRandomValues(Float64.self)
testTwoSumCancellation(Float64.self)
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
testTwoSumSpecials(Float80.self)
testTwoSumRandomValues(Float80.self)
testTwoSumCancellation(Float80.self)
#endif
}
}
+22
View File
@@ -0,0 +1,22 @@
#[[
This source file is part of the Swift Numerics open source project
Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
#]]
add_library(RealTests
ApproximateEqualityTests.swift
AugmentedArithmeticTests.swift
ElementaryFunctionChecks.swift
IntegerExponentTests.swift
RelaxedArithmeticTests.swift)
target_compile_options(RealTests PRIVATE
-enable-testing)
target_link_libraries(RealTests PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
RealModule
_TestSupport
XCTest)
@@ -0,0 +1,178 @@
//===--- ElementaryFunctionChecks.swift ------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
import RealModule
import _TestSupport
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
public typealias TestLiteralType = Float80
#else
public typealias TestLiteralType = Double
#endif
@discardableResult
internal func assertClose<T>(
_ expected: TestLiteralType,
_ observed: T,
allowedError: T = 16,
file: StaticString = #file,
line: UInt = #line
) -> T where T: BinaryFloatingPoint {
// Shortcut relative-error check if we got the sign wrong; it's OK to
// underflow to zero, but we do not want to allow going right through
// zero and getting the sign wrong.
guard observed.sign == expected.sign else {
print("Sign was wrong: expected \(expected) but saw \(observed).")
XCTFail(file: file, line: line)
return .infinity
}
if observed.isNaN && expected.isNaN { return 0 }
// If T(expected) is zero or infinite, and matches observed, the error
// is zero.
let expectedT = T(expected)
if observed.isZero && expectedT.isZero { return 0 }
if observed.isInfinite && expectedT.isInfinite { return 0 }
// Special-case where only one of expectedT or observed is infinity.
// Artificially knock everything down a binade, treat actual infinity as
// the base of the next binade up.
func topBinade(signOf x: T) -> T {
T(signOf: x, magnitudeOf: T.greatestFiniteMagnitude.binade)
}
if observed.isInfinite {
return assertClose(
expected/2, topBinade(signOf: observed),
allowedError: allowedError, file: file, line: line
)
}
if expectedT.isInfinite {
return assertClose(
TestLiteralType(topBinade(signOf: expectedT)), observed/2,
allowedError: allowedError, file: file, line: line
)
}
// Compute error in ulp, compare to tolerance.
let absoluteError = (TestLiteralType(observed) - expected).magnitude
let scale = max(expectedT.magnitude, T.leastNormalMagnitude).ulp
let ulps = T(absoluteError/TestLiteralType(scale))
if ulps > allowedError {
print("ULP error was unacceptably large: expected \(expected) but saw \(observed) (\(ulps)-ulp error).")
XCTFail(file: file, line: line)
}
return ulps
}
internal func assertClose<T>(
_ expected: TestLiteralType,
_ observed: T,
allowedError: T = 16,
worstError: inout T,
file: StaticString = #file,
line: UInt = #line
) where T: BinaryFloatingPoint {
worstError = max(worstError, assertClose(
expected, observed, allowedError: allowedError, file: file, line: line
))
}
internal extension ElementaryFunctions where Self: BinaryFloatingPoint {
static func elementaryFunctionChecks() {
assertClose(1.1863995522992575361931268186727044683, Self.acos(0.375))
assertClose(0.3843967744956390830381948729670469737, Self.asin(0.375))
assertClose(0.3587706702705722203959200639264604997, Self.atan(0.375))
assertClose(0.9305076219123142911494767922295555080, Self.cos(0.375))
assertClose(0.3662725290860475613729093517162641571, Self.sin(0.375))
assertClose(0.3936265759256327582294137871012180981, Self.tan(0.375))
assertClose(0.4949329230945269058895630995767185785, Self.acosh(1.125))
assertClose(0.9670596312833237113713762009167286709, Self.asinh(1.125))
assertClose(0.7331685343967135223291211023213964500, Self.atanh(0.625))
assertClose(1.0711403467045867672994980155670160493, Self.cosh(0.375))
assertClose(0.3838510679136145687542956764205024589, Self.sinh(0.375))
assertClose(0.3583573983507859463193602315531580424, Self.tanh(0.375))
assertClose(1.4549914146182013360537936919875185083, Self.exp(0.375))
assertClose(0.4549914146182013360537936919875185083, Self.expMinusOne(0.375))
assertClose(-0.980829253011726236856451127452003999, Self.log(0.375))
assertClose(0.3184537311185346158102472135905995955, Self.log(onePlus: 0.375))
assertClose(-0.7211247851537041911608191553900547941, Self.root(-0.375, 3))
XCTAssertEqual(-10, Self.root(-1000, 3))
assertClose(0.6123724356957945245493210186764728479, Self.sqrt(0.375))
assertClose(0.54171335479545025876069682133938570, Self.pow(0.375, 0.625))
assertClose(-0.052734375, Self.pow(-0.375, 3))
}
}
internal extension Real where Self: BinaryFloatingPoint {
static func realFunctionChecks() {
assertClose(1.2968395546510096659337541177924511598, Self.exp2(0.375))
assertClose(2.3713737056616552616517527574788898386, Self.exp10(0.375))
assertClose(-1.415037499278843818546261056052183491, Self.log2(0.375))
assertClose(-0.425968732272281148346188780918363771, Self.log10(0.375))
assertClose(0.54041950027058415544357836460859991, Self.atan2(y: 0.375, x: 0.625))
assertClose(0.72886898685566255885926910969319788, Self.hypot(0.375, 0.625))
assertClose(0.4041169094348222983238250859191217675, Self.erf(0.375))
assertClose(0.5958830905651777016761749140808782324, Self.erfc(0.375))
assertClose(2.3704361844166009086464735041766525098, Self.gamma(0.375))
#if !os(Windows)
assertClose( -0.11775527074107877445136203331798850, Self.logGamma(1.375))
XCTAssertEqual(.plus, Self.signGamma(1.375))
XCTAssertEqual(.minus, Self.signGamma(-2.375))
#endif
}
}
extension Real {
static func powZeroChecks() {
// pow(_:Self,_:Self) is defined by exp(y log(x)) and has edge-cases to
// match. In particular, if x is zero, log(x) is -infinity, so pow(0,0)
// is exp(0 * -infinity) = exp(nan) = nan.
XCTAssertEqual(pow(0, -1 as Self), infinity)
XCTAssert(pow(0, 0 as Self).isNaN)
XCTAssertEqual(pow(0, 1 as Self), zero)
// pow(_:Self,_:Int) is defined by repeated multiplication or division,
// and hence pow(0, 0) is 1.
XCTAssertEqual(pow(0, -1), infinity)
XCTAssertEqual(pow(0, 0), 1)
XCTAssertEqual(pow(0, 1), zero)
}
}
final class ElementaryFunctionChecks: XCTestCase {
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
func testFloat16() {
if #available(macOS 11.0, iOS 14.0, watchOS 14.0, tvOS 7.0, *) {
Float16.elementaryFunctionChecks()
Float16.realFunctionChecks()
Float16.powZeroChecks()
}
}
#endif
func testFloat() {
Float.elementaryFunctionChecks()
Float.realFunctionChecks()
Float.powZeroChecks()
}
func testDouble() {
Double.elementaryFunctionChecks()
Double.realFunctionChecks()
Double.powZeroChecks()
}
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
func testFloat80() {
Float80.elementaryFunctionChecks()
Float80.realFunctionChecks()
Float80.powZeroChecks()
}
#endif
}
+198
View File
@@ -0,0 +1,198 @@
//===--- IntegerExponentTests.swift ---------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
import RealModule
import _TestSupport
internal extension Real where Self: FixedWidthFloatingPoint {
static func testIntegerExponentCommon() {
// TODO: replace with seedable generator, print seed.
var g = SystemRandomNumberGenerator()
// If x is -1, then the result is ±1 with sign chosen by parity of n.
// Simply converting n to Real will flip parity when n is large, so
// first check that we get those cases right.
XCTAssertEqual(Self.pow(-1, 0), 1)
XCTAssertEqual(Self.pow(-1, 1), -1)
XCTAssertEqual(Self.pow(-1, -1), -1)
XCTAssertEqual(Self.pow(-1, 2), 1)
XCTAssertEqual(Self.pow(-1, -2), 1)
XCTAssertEqual(Self.pow(-1, Int.max - 1), 1)
XCTAssertEqual(Self.pow(-1, -Int.max + 1), 1)
XCTAssertEqual(Self.pow(-1, Int.max), -1)
XCTAssertEqual(Self.pow(-1, -Int.max), -1)
XCTAssertEqual(Self.pow(-1, Int.min), 1)
// Generate some random test values that definitely overflow or
// underflow; we want to be sure that we get the right ±0 or ±∞
// result.
for _ in 0 ..< 10 {
let x = Self.random(in: 2 ..< 4, using: &g)
let nLowerBound = 1 - Int(Self.leastNonzeroMagnitude.exponent)
let n = Int.random(in: nLowerBound ..< .max, using: &g)
let even = n & -2
let odd = even | 1
assertClose( .infinity, Self.pow(x, even))
assertClose( .infinity, Self.pow(x, odd))
assertClose( 0.0, Self.pow(1/x, even))
assertClose( 0.0, Self.pow(1/x, odd))
assertClose( .infinity, Self.pow(-x, even))
assertClose(-.infinity, Self.pow(-x, odd))
assertClose( 0.0, Self.pow(-1/x, even))
assertClose(-0.0, Self.pow(-1/x, odd))
assertClose( 0.0, Self.pow(x, -even))
assertClose( 0.0, Self.pow(x, -odd))
assertClose( .infinity, Self.pow(1/x, -even))
assertClose( .infinity, Self.pow(1/x, -odd))
assertClose( 0.0, Self.pow(-x, -even))
assertClose(-0.0, Self.pow(-x, -odd))
assertClose( .infinity, Self.pow(-1/x, -even))
assertClose(-.infinity, Self.pow(-1/x, -odd))
}
}
static func testIntegerExponentDoubleAndSmaller() {
// max/min exponents, these always saturate, but this will reveal
// errors in some implementations that one could try.
let u = Self(1).nextUp
let d = Self(1).nextDown
assertClose( .infinity, Self.pow(-u, Int.max - 1))
assertClose( 0.0, Self.pow(-d, Int.max - 1))
assertClose( 0.0, Self.pow(-u, -Int.max + 1))
assertClose( .infinity, Self.pow(-d, -Int.max + 1))
assertClose(-.infinity, Self.pow(-u, Int.max))
assertClose(-0.0, Self.pow(-d, Int.max))
assertClose(-0.0, Self.pow(-u, -Int.max))
assertClose(-.infinity, Self.pow(-d, -Int.max))
assertClose( 0.0, Self.pow(-u, Int.min))
assertClose( .infinity, Self.pow(-d, Int.min))
}
}
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
@available(macOS 11.0, iOS 14.0, watchOS 14.0, tvOS 7.0, *)
extension Float16 {
static func testIntegerExponent() {
testIntegerExponentCommon()
testIntegerExponentDoubleAndSmaller()
let u = Float16(1).nextUp
let d = Float16(1).nextDown
// Smallest exponents not exactly representable as Float16.
assertClose(-7.3890572722436554354625993393835304, Float16.pow(-u, 0x801))
assertClose(-0.3676100238077049750885141244927184, Float16.pow(-d, 0x801))
// Exponents close to overflow boundary.
assertClose( 65403.86633107, Float16.pow(-u, 11360))
assertClose(-65467.73729429, Float16.pow(-u, 11361))
assertClose( 65531.67063149, Float16.pow(-u, 11362))
assertClose( 65487.96799785, Float16.pow(-d, -22706))
assertClose(-65519.96016590, Float16.pow(-d, -22707))
assertClose( 65551.96796276, Float16.pow(-d, -22708))
// Exponents close to underflow boundary.
assertClose( 5.966876499900e-8, Float16.pow(-u, -17042))
assertClose(-5.961055156973e-8, Float16.pow(-u, -17043))
assertClose( 5.955239493405e-8, Float16.pow(-u, -17044))
assertClose( 5.964109628044e-8, Float16.pow(-d, 34060))
assertClose(-5.961197465140e-8, Float16.pow(-d, 34061))
assertClose( 5.958286724190e-8, Float16.pow(-d, 34062))
}
}
#endif
extension Float {
static func testIntegerExponent() {
testIntegerExponentCommon()
testIntegerExponentDoubleAndSmaller()
let u = Float(1).nextUp
let d = Float(1).nextDown
// Smallest exponents not exactly representable as Float.
assertClose(-7.3890560989306677280287919329569359, Float.pow(-u, 0x1000001))
assertClose(-0.3678794082804575860056608283059288, Float.pow(-d, 0x1000001))
// Exponents close to overflow boundary.
assertClose(-3.4028231352500001570898203463449749e38, Float.pow(-u, 744261161))
assertClose( 3.4028235408981285772043562848249166e38, Float.pow(-u, 744261162))
assertClose(-3.4028239465463053543440887892352174e38, Float.pow(-u, 744261163))
assertClose( 3.4028233551634475284795244782720072e38, Float.pow(-d, -1488522190))
assertClose(-3.4028235579875369356575053576685267e38, Float.pow(-d, -1488522191))
assertClose( 3.4028237608116384320940078199368685e38, Float.pow(-d, -1488522192))
// Exponents close to underflow boundary.
assertClose( 7.0064936491761438872280296737844625e-46, Float.pow(-u, -872181048))
assertClose(-7.0064928139371132951305928725186420e-46, Float.pow(-u, -872181049))
assertClose( 7.0064919786981822712727285793333389e-46, Float.pow(-u, -872181050))
assertClose(-7.0064924138100205091278464932003585e-46, Float.pow(-d, 1744361943))
assertClose( 7.0064919961905290625123586120258840e-46, Float.pow(-d, 1744361944))
assertClose(-7.0064915785710625079583096856510544e-46, Float.pow(-d, 1744361945))
}
}
extension Double {
static func testIntegerExponent() {
testIntegerExponentCommon()
// Following tests only make sense (and are only necessary) on 64b platforms.
#if arch(arm64) || arch(x86_64)
testIntegerExponentDoubleAndSmaller()
let u: Double = 1.nextUp
let d: Double = 1.nextDown
// Smallest exponent not exactly representable as Double.
assertClose(-7.3890560989306502272304274605750685, Double.pow(-u, 0x20000000000001))
assertClose(-0.1353352832366126918939994949724833, Double.pow(-u, -0x20000000000001))
assertClose(-0.3678794411714422603312898889458068, Double.pow(-d, 0x20000000000001))
assertClose(-2.7182818284590456880451484776630468, Double.pow(-d, -0x20000000000001))
// Exponents close to overflow boundary.
#if os(Windows)
// TODO: It appears that the Windows pow doesn't carry enough precision
// through the computation of log(1.nextDown) to produce a good result
// for these cases; we'll want to provide a better implementation at some
// point in the future. It's acceptable in the short term, however.
let tol: Double = 360
#else
let tol: Double = 16
#endif
assertClose( 1.7976931348623151738531864721534215e308, Double.pow(-u, 3196577161300664268), allowedError: tol)
assertClose(-1.7976931348623155730212483790972209e308, Double.pow(-u, 3196577161300664269), allowedError: tol)
assertClose( 1.7976931348623159721893102860411089e308, Double.pow(-u, 3196577161300664270), allowedError: tol)
assertClose( 1.7976931348623157075547244136070910e308, Double.pow(-d, -6393154322601327474), allowedError: tol)
assertClose(-1.7976931348623159071387553670790721e308, Double.pow(-d, -6393154322601327475), allowedError: tol)
assertClose( 1.7976931348623161067227863205510754e308, Double.pow(-d, -6393154322601327476), allowedError: tol)
// Exponents close to underflow boundary.
assertClose( 2.4703282292062334560337346683707907e-324, Double.pow(-u, -3355781687888880946))
assertClose(-2.4703282292062329075106789791206172e-324, Double.pow(-u, -3355781687888880947))
assertClose( 2.4703282292062323589876232898705654e-324, Double.pow(-u, -3355781687888880948))
assertClose(-2.4703282292062332640976590913373022e-324, Double.pow(-d, 6711563375777760775))
assertClose( 2.4703282292062329898361312467121758e-324, Double.pow(-d, 6711563375777760776))
assertClose(-2.4703282292062327155746034020870799e-324, Double.pow(-d, 6711563375777760777))
#endif
}
}
final class IntegerExponentTests: XCTestCase {
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
func testFloat16() {
if #available(macOS 11.0, iOS 14.0, watchOS 14.0, tvOS 7.0, *) {
Float16.testIntegerExponent()
}
}
#endif
func testFloat() {
Float.testIntegerExponent()
}
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
}
@@ -0,0 +1,129 @@
//===--- RelaxedArithmeticTests.swift -------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
import RealModule
import _TestSupport
#if canImport(Accelerate)
import Accelerate
#endif
#if !DEBUG
func strictSum<T: Real>(_ array: [T]) -> T {
array.reduce(0, +)
}
func relaxedSum<T: Real>(_ array: [T]) -> T {
array.reduce(0, Relaxed.sum)
}
func strictSumOfSquares<T: Real>(_ array: [T]) -> T {
array.reduce(0) { $0 + $1*$1 }
}
func relaxedSumOfSquares<T: Real>(_ array: [T]) -> T {
array.reduce(0) { Relaxed.multiplyAdd($1, $1, $0) }
}
// TODO: not a great harness, but making it better bumps up against the
// limitations of what XCT measure { } lets us do easily. Good enough for now.
func benchmarkReduction(_ data: [Float], _ reduction: ([Float]) -> Float) {
var accum: Float = 0
let iters = 100_000
for _ in 0 ..< iters {
accum += reduction(data)
}
blackHole(accum)
}
final class RelaxedArithmeticTests: XCTestCase {
var floatData: [Float] = []
override func setUp() {
super.setUp()
floatData = (0 ..< 1024).map { _ in .random(in: .sqrt(1/2) ..< .sqrt(2)) }
}
func testStrictSumPerformance() {
measure { benchmarkReduction(floatData, strictSum) }
}
func testRelaxedSumPerformance() {
// Performance of this should be closer to vDSP.sum than to
// strict sum
measure { benchmarkReduction(floatData, relaxedSum) }
}
#if canImport(Accelerate)
func testvDSPSumPerformance() {
measure { benchmarkReduction(floatData, vDSP.sum) }
}
#endif
func testStrictDotPerformance() {
measure { benchmarkReduction(floatData, strictSumOfSquares) }
}
func testRelaxedDotPerformance() {
// Performance of this should be closer to vDSP.sumOfSquares than to
// strict sumOfSquares
measure { benchmarkReduction(floatData, relaxedSumOfSquares) }
}
#if canImport(Accelerate)
func testvDSPDotPerformance() {
measure { benchmarkReduction(floatData, vDSP.sumOfSquares) }
}
#endif
func testRelaxedArithmetic<T: FixedWidthFloatingPoint & Real>(_ type: T.Type) {
// Relaxed add is still an add; it's just permitted to reorder relative
// to other adds or form FMAs. So if we do one in isolation, it has to
// produce the same result as a normal addition.
let a = T.random(in: -1 ... 1)
let b = T.random(in: -1 ... 1)
XCTAssertEqual(a + b, Relaxed.sum(a, b))
// Same is true for mul.
XCTAssertEqual(a * b, Relaxed.product(a, b))
// add + mul must be either two operations or an FMA:
let unfused = a + 1.5 * b
let fused = a.addingProduct(1.5, b)
let relaxed = Relaxed.multiplyAdd(1.5, b, a)
XCTAssert(relaxed == unfused || relaxed == fused)
// Summing all values in an array can be associated however we want, but
// has to satisfy the usual error bound of 0.5 * sum.ulp * numberOfElements.
// We don't have a golden reference, but we can compare two sums with twice
// the bound for a sanity check.
let array = (0 ..< 128).map { _ in T.random(in: 1 ..< 2) }
var ref = strictSum(array)
var tst = relaxedSum(array)
var bound = max(ref, tst).ulp * T(array.count)
XCTAssertLessThanOrEqual(abs(ref - tst), bound)
// Similarly for sum of squares ...
ref = strictSumOfSquares(array)
tst = relaxedSumOfSquares(array)
bound = 2 * max(ref, tst).ulp * T(array.count)
XCTAssertLessThanOrEqual(abs(ref - tst), bound)
}
func testRelaxedArithmetic() {
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
testRelaxedArithmetic(Float16.self)
#endif
testRelaxedArithmetic(Float.self)
testRelaxedArithmetic(Double.self)
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
testRelaxedArithmetic(Float80.self)
#endif
}
}
#endif
+194
View File
@@ -0,0 +1,194 @@
//===--- WindowsMain.swift ------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2021 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
@testable
import IntegerUtilitiesTests
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 !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
extension ElementaryFunctionChecks {
static var all = testCase([
("testFloat16", ElementaryFunctionChecks.testFloat16),
("testFloat", ElementaryFunctionChecks.testFloat),
("testDouble", ElementaryFunctionChecks.testDouble),
])
}
extension IntegerExponentTests {
static var all = testCase([
("testFloat16", IntegerExponentTests.testFloat16),
("testFloat", IntegerExponentTests.testFloat),
("testDouble", IntegerExponentTests.testDouble),
])
}
#else
extension ElementaryFunctionChecks {
static var all = testCase([
("testFloat", ElementaryFunctionChecks.testFloat),
("testDouble", ElementaryFunctionChecks.testDouble),
])
}
extension IntegerExponentTests {
static var all = testCase([
("testFloat", IntegerExponentTests.testFloat),
("testDouble", IntegerExponentTests.testDouble),
])
}
#endif
extension RealTests.AugmentedArithmeticTests {
static var all = testCase([
("testTwoSum", RealTests.AugmentedArithmeticTests.testTwoSum),
])
}
extension RealTests.RelaxedArithmeticTests {
static var all = testCase([
("testRelaxedArithmetic", RealTests.RelaxedArithmeticTests.testRelaxedArithmetic),
])
}
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),
])
}
extension IntegerUtilitiesDivideTests {
static var all = testCase([
("testDivideInt8", IntegerUtilitiesDivideTests.testDivideInt8),
("testDivideInt", IntegerUtilitiesDivideTests.testDivideInt),
("testDivideUInt8", IntegerUtilitiesDivideTests.testDivideUInt8),
("testDivideStochasticInt8", IntegerUtilitiesDivideTests.testDivideStochasticInt8),
("testDivideStochasticUInt32", IntegerUtilitiesDivideTests.testDivideStochasticUInt32),
("testRemainderByMinusOne", IntegerUtilitiesDivideTests.testRemainderByMinusOne),
])
}
extension IntegerUtilitiesGCDTests {
static var all = testCase([
("testGCDInt", IntegerUtilitiesGCDTests.testGCDInt),
])
}
extension IntegerUtilitiesRotateTests {
static var all = testCase([
("testRotateUInt8", IntegerUtilitiesRotateTests.testRotateUInt8),
("testRotateInt16", IntegerUtilitiesRotateTests.testRotateInt16),
])
}
extension IntegerUtilitiesSaturatingTests {
static var all = testCase([
("testSaturatingAddSigned", IntegerUtilitiesSaturatingTests.testSaturatingAddSigned),
("testSaturatingSubSigned", IntegerUtilitiesSaturatingTests.testSaturatingSubSigned),
("testSaturatingNegSigned", IntegerUtilitiesSaturatingTests.testSaturatingNegSigned),
("testSaturatingMulSigned", IntegerUtilitiesSaturatingTests.testSaturatingMulSigned),
("testSaturatingAddUnsigned", IntegerUtilitiesSaturatingTests.testSaturatingAddUnsigned),
("testSaturatingSubUnsigned", IntegerUtilitiesSaturatingTests.testSaturatingSubUnsigned),
("testSaturatingNegUnsigned", IntegerUtilitiesSaturatingTests.testSaturatingNegUnsigned),
("testSaturatingMulUnsigned", IntegerUtilitiesSaturatingTests.testSaturatingMulUnsigned),
("testSaturatingShifts", IntegerUtilitiesSaturatingTests.testSaturatingShifts),
("testEdgeCaseForNegativeCount", IntegerUtilitiesSaturatingTests.testEdgeCaseForNegativeCount)
])
}
extension IntegerUtilitiesShiftTests {
static var all = testCase([
("testRoundingShifts", IntegerUtilitiesShiftTests.testRoundingShifts),
("testStochasticShifts", IntegerUtilitiesShiftTests.testStochasticShifts),
])
}
extension IntegerUtilitiesTests.DoubleWidthTests {
static var all = testCase([
("testArithmetic_Signed", IntegerUtilitiesTests.DoubleWidthTests.testArithmetic_Signed),
("testArithmetic_Unsigned", IntegerUtilitiesTests.DoubleWidthTests.testArithmetic_Unsigned),
("testBitwise_LeftAndRightShifts", IntegerUtilitiesTests.DoubleWidthTests.testBitwise_LeftAndRightShifts),
("testCompileTime_SR_6947", IntegerUtilitiesTests.DoubleWidthTests.testCompileTime_SR_6947),
("testConditionalConformance", IntegerUtilitiesTests.DoubleWidthTests.testConditionalConformance),
("testConversions", IntegerUtilitiesTests.DoubleWidthTests.testConversions),
("testConversions_Exact", IntegerUtilitiesTests.DoubleWidthTests.testConversions_Exact),
("testConversions_SignedMax", IntegerUtilitiesTests.DoubleWidthTests.testConversions_SignedMax),
("testConversions_SignedMin", IntegerUtilitiesTests.DoubleWidthTests.testConversions_SignedMin),
("testConversions_ToAndFromString_Binary", IntegerUtilitiesTests.DoubleWidthTests.testConversions_ToAndFromString_Binary),
("testConversions_ToAndFromString_Decimal", IntegerUtilitiesTests.DoubleWidthTests.testConversions_ToAndFromString_Decimal),
("testConversions_ToAndFromString_Hexadecimal", IntegerUtilitiesTests.DoubleWidthTests.testConversions_ToAndFromString_Hexadecimal),
("testConversions_UnsignedMax", IntegerUtilitiesTests.DoubleWidthTests.testConversions_UnsignedMax),
("testConversions_UnsignedMin", IntegerUtilitiesTests.DoubleWidthTests.testConversions_UnsignedMin),
("testDivision_ByMinusOne", IntegerUtilitiesTests.DoubleWidthTests.testDivision_ByMinusOne),
("testDivision_ByZero", IntegerUtilitiesTests.DoubleWidthTests.testDivision_ByZero),
("testInitialization", IntegerUtilitiesTests.DoubleWidthTests.testInitialization),
("testInitialization_Overflow", IntegerUtilitiesTests.DoubleWidthTests.testInitialization_Overflow),
("testLiterals", IntegerUtilitiesTests.DoubleWidthTests.testLiterals),
("testLiterals_Underflow", IntegerUtilitiesTests.DoubleWidthTests.testLiterals_Underflow),
("testMagnitude", IntegerUtilitiesTests.DoubleWidthTests.testMagnitude),
("testMultipleOf", IntegerUtilitiesTests.DoubleWidthTests.testMultipleOf),
("testMultiplication_ByMinusOne", IntegerUtilitiesTests.DoubleWidthTests.testMultiplication_ByMinusOne),
("testNested", IntegerUtilitiesTests.DoubleWidthTests.testNested),
("testRemainder_ByMinusOne", IntegerUtilitiesTests.DoubleWidthTests.testRemainder_ByMinusOne),
("testRemainder_ByZero", IntegerUtilitiesTests.DoubleWidthTests.testRemainder_ByZero),
("testTwoWords", IntegerUtilitiesTests.DoubleWidthTests.testTwoWords),
("testWords", IntegerUtilitiesTests.DoubleWidthTests.testWords),
])
}
var testCases = [
ComplexTests.ApproximateEqualityTests.all,
RealTests.ApproximateEqualityTests.all,
ElementaryFunctionChecks.all,
IntegerExponentTests.all,
ArithmeticTests.all,
PropertyTests.all,
IntegerUtilitiesDivideTests.all,
IntegerUtilitiesGCDTests.all,
IntegerUtilitiesRotateTests.all,
IntegerUtilitiesShiftTests.all,
IntegerUtilitiesSaturatingTests.all,
IntegerUtilitiesTests.DoubleWidthTests.all,
]
XCTMain(testCases)
#endif
+88
View File
@@ -0,0 +1,88 @@
#[[
This source file is part of the Swift Numerics open source project
Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
#]]
# Returns the architecture name in a variable
#
# Usage:
# get_swift_host_arch(result_var_name)
#
# Sets ${result_var_name} with the converted architecture name derived from
# CMAKE_SYSTEM_PROCESSOR.
function(get_swift_host_arch result_var_name)
if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64")
set("${result_var_name}" "x86_64" PARENT_SCOPE)
elseif ("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "AArch64|aarch64|arm64")
if(CMAKE_SYSTEM_NAME MATCHES Darwin)
set("${result_var_name}" "arm64" PARENT_SCOPE)
else()
set("${result_var_name}" "aarch64" PARENT_SCOPE)
endif()
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64")
set("${result_var_name}" "powerpc64" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64le")
set("${result_var_name}" "powerpc64le" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "s390x")
set("${result_var_name}" "s390x" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv6l")
set("${result_var_name}" "armv6" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7l")
set("${result_var_name}" "armv7" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7-a")
set("${result_var_name}" "armv7" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "AMD64")
set("${result_var_name}" "x86_64" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "IA64")
set("${result_var_name}" "itanium" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86")
set("${result_var_name}" "i686" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "i686")
set("${result_var_name}" "i686" PARENT_SCOPE)
else()
message(FATAL_ERROR "Unrecognized architecture on host system: ${CMAKE_SYSTEM_PROCESSOR}")
endif()
endfunction()
# Returns the os name in a variable
#
# Usage:
# get_swift_host_os(result_var_name)
#
#
# Sets ${result_var_name} with the converted OS name derived from
# CMAKE_SYSTEM_NAME.
function(get_swift_host_os result_var_name)
if(CMAKE_SYSTEM_NAME STREQUAL Darwin)
set(${result_var_name} macosx PARENT_SCOPE)
else()
string(TOLOWER ${CMAKE_SYSTEM_NAME} cmake_system_name_lc)
set(${result_var_name} ${cmake_system_name_lc} PARENT_SCOPE)
endif()
endfunction()
function(_install_target module)
get_swift_host_arch(swift_arch)
get_swift_host_os(swift_os)
install(TARGETS ${module}
ARCHIVE DESTINATION lib/swift$<$<NOT:$<BOOL:${BUILD_SHARED_LIBS}>>:_static>/${swift_os}
LIBRARY DESTINATION lib/swift$<$<NOT:$<BOOL:${BUILD_SHARED_LIBS}>>:_static>/${swift_os}
RUNTIME DESTINATION bin)
if(CMAKE_SYSTEM_NAME STREQUAL Darwin)
install(FILES $<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module}.swiftdoc
DESTINATION lib/swift$<$<NOT:$<BOOL:${BUILD_SHARED_LIBS}>>:_static>/${swift_os}/${mmodule}.swiftmodule
RENAME ${swift_arch}.swiftdoc)
install(FILES $<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module}.swiftmodule
DESTINATION lib/swift$<$<NOT:$<BOOL:${BUILD_SHARED_LIBS}>>:_static>/${swift_os}/${mmodule}.swiftmodule
RENAME ${swift_arch}.swiftmodule)
else()
install(FILES
$<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module}.swiftdoc
$<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module}.swiftmodule
DESTINATION lib/swift$<$<NOT:$<BOOL:${BUILD_SHARED_LIBS}>>:_static>/${swift_os}/${swift_arch})
endif()
endfunction()