mirror of
https://github.com/apple/swift-numerics
synced 2026-11-22 04:30:45 +00:00
Compare commits
506
Commits
0.0.2
..
Quaternions
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4b6b631fb | ||
|
|
9a726a793e | ||
|
|
98b9088b4c | ||
|
|
bb31091fdc | ||
|
|
8a9ad438cb | ||
|
|
1bab0de693 | ||
|
|
0b6cdc3844 | ||
|
|
c2184941ab | ||
|
|
e5ed4ac651 | ||
|
|
eeff10ed00 | ||
|
|
aa376839bf | ||
|
|
bc944e79f0 | ||
|
|
ff9f52fc92 | ||
|
|
360b914e9c | ||
|
|
e7c68b70b7 | ||
|
|
c142bcedfe | ||
|
|
e8940b786e | ||
|
|
5ea4f613d3 | ||
|
|
f99c42cacb | ||
|
|
9d7b668a10 | ||
|
|
42c26ee85d | ||
|
|
844aff56c5 | ||
|
|
b197152494 | ||
|
|
85281cc937 | ||
|
|
52bb20ad8f | ||
|
|
af266bb9d9 | ||
|
|
92af6727ee | ||
|
|
e9dfc766be | ||
|
|
211b94fb16 | ||
|
|
ea46df54b9 | ||
|
|
fda8513ec0 | ||
|
|
1b541a1581 | ||
|
|
acbdeeaa3d | ||
|
|
4b8ae5dd44 | ||
|
|
daff65f930 | ||
|
|
22f1901206 | ||
|
|
46a25b6d61 | ||
|
|
111d482833 | ||
|
|
5c4bce2635 | ||
|
|
31bf80751a | ||
|
|
bd99cdeffb | ||
|
|
5b96cba10e | ||
|
|
e99724f03b | ||
|
|
015c9bd961 | ||
|
|
896142fc32 | ||
|
|
528fb9daf1 | ||
|
|
ab8c3d9ddb | ||
|
|
1fe4ce7b1f | ||
|
|
e50371b030 | ||
|
|
39bd408dad | ||
|
|
06341f3bea | ||
|
|
1ded0b7c56 | ||
|
|
fb718d6f74 | ||
|
|
a5c6f27f26 | ||
|
|
a5478a7885 | ||
|
|
1b1c7cddf5 | ||
|
|
e7aa60d838 | ||
|
|
7896ee2eef | ||
|
|
e5b84606f5 | ||
|
|
273c6f7e54 | ||
|
|
8ec29a889b | ||
|
|
03e1f5ba6b | ||
|
|
4188358cb4 | ||
|
|
fcab66685d | ||
|
|
bb05e58135 | ||
|
|
5e1de5d8e0 | ||
|
|
9b7cbcdb4a | ||
|
|
43932b1cfe | ||
|
|
09c038ed3b | ||
|
|
69100e86b4 | ||
|
|
2bf3285bde | ||
|
|
4dd08f1c10 | ||
|
|
00e141fb19 | ||
|
|
000df70c1b | ||
|
|
bdd9b2f4bc | ||
|
|
2f438bd6c9 | ||
|
|
57fc357bfc | ||
|
|
7fb314a581 | ||
|
|
f1e353ec03 | ||
|
|
e2ad631369 | ||
|
|
e29fa04051 | ||
|
|
22ec1b960b | ||
|
|
99a7c6113d | ||
|
|
15fee28c1f | ||
|
|
dd731f3362 | ||
|
|
be0d7c65d1 | ||
|
|
5bfe9e16ce | ||
|
|
46619b49ec | ||
|
|
231815ea4b | ||
|
|
e74905c6d5 | ||
|
|
a50d9575fe | ||
|
|
1e94d23860 | ||
|
|
b3fe4357f8 | ||
|
|
aa901641d1 | ||
|
|
2c19b7b8cd | ||
|
|
221387985a | ||
|
|
8b2fd7bbde | ||
|
|
b43c10c1e3 | ||
|
|
61a8b91b3e | ||
|
|
8c4747f116 | ||
|
|
c3757dc266 | ||
|
|
d86286fc8b | ||
|
|
9c548804c8 | ||
|
|
acbf4257ca | ||
|
|
6ff93f255e | ||
|
|
af0352e8b1 | ||
|
|
e79692fab1 | ||
|
|
c1e6972eeb | ||
|
|
da6c765795 | ||
|
|
2361b4959b | ||
|
|
264b17140b | ||
|
|
5cc83cc00a | ||
|
|
5b34639450 | ||
|
|
450691764d | ||
|
|
95e9441f8c | ||
|
|
d2f6811b87 | ||
|
|
129e496ef1 | ||
|
|
5d8425644a | ||
|
|
cd967fa90f | ||
|
|
6356eb395b | ||
|
|
1be6eb5b47 | ||
|
|
2b458e8aeb | ||
|
|
31fe14d084 | ||
|
|
c327d04b01 | ||
|
|
9b36b1ce46 | ||
|
|
7888cf22cc | ||
|
|
1d23717b47 | ||
|
|
0d774a5bc3 | ||
|
|
7ba979e24b | ||
|
|
d0ffe3c0e0 | ||
|
|
e750ab6419 | ||
|
|
06e2bf1f76 | ||
|
|
c4cc31ea95 | ||
|
|
7b1e0db437 | ||
|
|
e30276bff2 | ||
|
|
ddc8ce302b | ||
|
|
b5adc8c39b | ||
|
|
683c8f210a | ||
|
|
c69fea9be8 | ||
|
|
3ee07816b2 | ||
|
|
53afff107a | ||
|
|
1043e9ed38 | ||
|
|
e7af7dffbc | ||
|
|
da661919b9 | ||
|
|
6deae1b98f | ||
|
|
155cfc306c | ||
|
|
877fd0aa9a | ||
|
|
262cbea1f2 | ||
|
|
84c41a0bef | ||
|
|
a883d95a4d | ||
|
|
3d6de9f3ef | ||
|
|
3fa18ae9b5 | ||
|
|
1ba2178227 | ||
|
|
97bab250eb | ||
|
|
ab63ebd7b2 | ||
|
|
347f1e31fe | ||
|
|
fa7db5761d | ||
|
|
907430bdad | ||
|
|
57ad9c588b | ||
|
|
05a3ee869f | ||
|
|
4e905b38b7 | ||
|
|
43e0f5b026 | ||
|
|
0599b610d9 | ||
|
|
2fae6a86e3 | ||
|
|
faa65e8842 | ||
|
|
0111e791a1 | ||
|
|
1883189574 | ||
|
|
e8a3ddbb3e | ||
|
|
a7e27e16e1 | ||
|
|
a0d66e1537 | ||
|
|
182c9b246b | ||
|
|
b3867a9155 | ||
|
|
470e4236ff | ||
|
|
3d13ebaf94 | ||
|
|
485c60c6c4 | ||
|
|
b38fcb77a6 | ||
|
|
716e22fd64 | ||
|
|
35e15a381f | ||
|
|
bc9f6e7368 | ||
|
|
ef6dbc6e78 | ||
|
|
0bb0a9acff | ||
|
|
d59ec36291 | ||
|
|
a118de9878 | ||
|
|
58f4e72d8a | ||
|
|
8680be387b | ||
|
|
f7075cc79a | ||
|
|
fe151134b0 | ||
|
|
f00824e9fa | ||
|
|
4779aef990 | ||
|
|
dbffff1ea5 | ||
|
|
7953ef315a | ||
|
|
93e5499e54 | ||
|
|
740cc5012f | ||
|
|
f6b0aeb607 | ||
|
|
313ab7266a | ||
|
|
30c01a9fc5 | ||
|
|
9a23fdf1c9 | ||
|
|
86699a7f8a | ||
|
|
b750c890b7 | ||
|
|
79390164f5 | ||
|
|
0fff91683a | ||
|
|
9c0332d570 | ||
|
|
97c716ba37 | ||
|
|
8353ce4c3d | ||
|
|
5428505255 | ||
|
|
e601f16e20 | ||
|
|
6c4accd836 | ||
|
|
60a3edbaa9 | ||
|
|
89cfa62803 | ||
|
|
2baff8fc30 | ||
|
|
b9e8b970f2 | ||
|
|
d34f5636c4 | ||
|
|
2624562948 | ||
|
|
c8e3d9f54b | ||
|
|
a7ceb774fe | ||
|
|
0ea36c3109 | ||
|
|
0dc8fef6e9 | ||
|
|
98a8a166df | ||
|
|
0d9f0b2a98 | ||
|
|
1db31ebdf0 | ||
|
|
48003e8b7a | ||
|
|
56db9b5ec9 | ||
|
|
5803eaf5bb | ||
|
|
cc53a7b085 | ||
|
|
027bcc5b8e | ||
|
|
fc1b2d1e67 | ||
|
|
270972dd8a | ||
|
|
b6018fa8a9 | ||
|
|
5bbf0e2229 | ||
|
|
27f8192a63 | ||
|
|
c4f8886a11 | ||
|
|
7f2d022d3d | ||
|
|
4ce74b4235 | ||
|
|
445b0da15d | ||
|
|
9596f40d3b | ||
|
|
d329698498 | ||
|
|
ba65b0fc77 | ||
|
|
1939f34fde | ||
|
|
47a233758d | ||
|
|
f3365bd0b4 | ||
|
|
8983be89c7 | ||
|
|
f5b33a6c07 | ||
|
|
bfd905c9e4 | ||
|
|
80d758ac5b | ||
|
|
48099a09b4 | ||
|
|
9e50430d23 | ||
|
|
cdb092bb31 | ||
|
|
84044a8382 | ||
|
|
db932c9871 | ||
|
|
b501ca406c | ||
|
|
be0534a3e3 | ||
|
|
c74d817e8d | ||
|
|
05366d7f4a | ||
|
|
6ec74ec80e | ||
|
|
d4a440fd05 | ||
|
|
f6e5563514 | ||
|
|
8b05d1c8e0 | ||
|
|
1e724835bd | ||
|
|
f956c239e1 | ||
|
|
af5393445b | ||
|
|
43e1d4d049 | ||
|
|
9c4bd83ca4 | ||
|
|
b37b64db2e | ||
|
|
0acd49c55f | ||
|
|
24d8f51bb3 | ||
|
|
3eaa0b3b77 | ||
|
|
710ca088d5 | ||
|
|
1b3e3f12ed | ||
|
|
63df367680 | ||
|
|
501f58252a | ||
|
|
9837c10f9e | ||
|
|
dec7339db4 | ||
|
|
cddd5e626d | ||
|
|
92eb76200d | ||
|
|
eeaf9e384a | ||
|
|
d78c067765 | ||
|
|
c124585c19 | ||
|
|
caca93c5c6 | ||
|
|
c3806f23ff | ||
|
|
bc17ae6a82 | ||
|
|
e22ff866a4 | ||
|
|
abb899865e | ||
|
|
b6f4c44221 | ||
|
|
ae38370107 | ||
|
|
9d84cefefa | ||
|
|
f2cfa8d668 | ||
|
|
bd68569533 | ||
|
|
85264c808c | ||
|
|
b505d3ca1d | ||
|
|
7738390f54 | ||
|
|
5f28ad0e97 | ||
|
|
63edd6769c | ||
|
|
8552becf91 | ||
|
|
89c4e42e48 | ||
|
|
67af2fe0d9 | ||
|
|
83c378f2f4 | ||
|
|
b8f452189b | ||
|
|
0289df5635 | ||
|
|
b9415c9ad2 | ||
|
|
b68a81dbdd | ||
|
|
21ff6d38fd | ||
|
|
4fbcb11f03 | ||
|
|
e29479b3aa | ||
|
|
996cf7f5b9 | ||
|
|
632919ce2a | ||
|
|
909a77c3d9 | ||
|
|
4a6730b024 | ||
|
|
84474a3410 | ||
|
|
97dfcff73b | ||
|
|
988f1e1cea | ||
|
|
32c2b64370 | ||
|
|
ac7a9a9a92 | ||
|
|
3d6bff6cae | ||
|
|
12148ffa66 | ||
|
|
3a5c73964b | ||
|
|
32f48e6b73 | ||
|
|
05440473eb | ||
|
|
342d38eb3b | ||
|
|
ecc77886a1 | ||
|
|
10e75aa392 | ||
|
|
d7e692e414 | ||
|
|
faf13772af | ||
|
|
17f5b59a07 | ||
|
|
702c6fc1d8 | ||
|
|
f50a1acf2d | ||
|
|
2aa93ccf24 | ||
|
|
50161d39df | ||
|
|
d34cff5a13 | ||
|
|
9f55a78685 | ||
|
|
5827f9a943 | ||
|
|
3cad9b69a0 | ||
|
|
6583ac70c3 | ||
|
|
97852afaf5 | ||
|
|
105b59b8a4 | ||
|
|
0cf166da79 | ||
|
|
4a2cbc186b | ||
|
|
5a7eb37c19 | ||
|
|
198da2adf9 | ||
|
|
26c51aca1b | ||
|
|
c5a3504143 | ||
|
|
00c6183670 | ||
|
|
ae364a28f0 | ||
|
|
e042c13415 | ||
|
|
16837299c1 | ||
|
|
0c066bd268 | ||
|
|
2b4c6701f2 | ||
|
|
874c767424 | ||
|
|
0ee972ff92 | ||
|
|
754cbd9e2e | ||
|
|
209a794eb6 | ||
|
|
af19aec6ff | ||
|
|
ed8fc21f1e | ||
|
|
1cbb94ac71 | ||
|
|
0b2dc469ed | ||
|
|
efbe11a734 | ||
|
|
4798b68203 | ||
|
|
5f408c0121 | ||
|
|
09beddce47 | ||
|
|
2179fa1f82 | ||
|
|
6d9de5d4ce | ||
|
|
e20b32d40f | ||
|
|
21282166fa | ||
|
|
6b24333510 | ||
|
|
e07b39453b | ||
|
|
0f02c65854 | ||
|
|
a76404b263 | ||
|
|
298ea7d3f5 | ||
|
|
8e580358d4 | ||
|
|
4b4dd42ad4 | ||
|
|
7be984de7e | ||
|
|
6f96e6522d | ||
|
|
e95124c81f | ||
|
|
2aeb3f8475 | ||
|
|
ecfc4db4e9 | ||
|
|
f3e99a9c70 | ||
|
|
6d8d614bf2 | ||
|
|
beb85076a5 | ||
|
|
6d396dfb44 | ||
|
|
f49d1af281 | ||
|
|
82b04be57e | ||
|
|
5eb865d25d | ||
|
|
81e76b1a9a | ||
|
|
dcad77ec73 | ||
|
|
6ae59362f8 | ||
|
|
3d7462a834 | ||
|
|
0f8ef268d0 | ||
|
|
694e5ae6de | ||
|
|
c26e60c6ba | ||
|
|
96a5383b0a | ||
|
|
38b5251804 | ||
|
|
aaec0af9c8 | ||
|
|
3811e3bc7a | ||
|
|
a0501be80a | ||
|
|
cda1b5e6f4 | ||
|
|
fa16d7db6a | ||
|
|
a4372aa8d6 | ||
|
|
145156c40e | ||
|
|
c2d6cb716d | ||
|
|
4077cd3461 | ||
|
|
337be4044e | ||
|
|
ddbc41f80b | ||
|
|
2342ba6314 | ||
|
|
6af70e51ea | ||
|
|
d32bb739d4 | ||
|
|
6b89e8d4b0 | ||
|
|
ce58d083a1 | ||
|
|
555340e882 | ||
|
|
7109a22972 | ||
|
|
ea6d7ffd5e | ||
|
|
97824411d9 | ||
|
|
d368762c95 | ||
|
|
7e032e20fc | ||
|
|
1ec79f5270 | ||
|
|
44cb9f2d4a | ||
|
|
af3912cd4a | ||
|
|
4771ef24d2 | ||
|
|
336740bd6d | ||
|
|
189f072825 | ||
|
|
e6a343a205 | ||
|
|
66ac02125c | ||
|
|
4cd11553db | ||
|
|
13b74ae5f4 | ||
|
|
2828bec340 | ||
|
|
e69f12617b | ||
|
|
80522b2bee | ||
|
|
a7ef6cd74c | ||
|
|
18ce9c0bbd | ||
|
|
06c17a9a0f | ||
|
|
2327363b24 | ||
|
|
8b73836979 | ||
|
|
1dcd7f314b | ||
|
|
30627f2d06 | ||
|
|
c07076e917 | ||
|
|
968d004d54 | ||
|
|
cfeda4df2d | ||
|
|
f275f7df53 | ||
|
|
7c0eb30664 | ||
|
|
91ecc8a3b6 | ||
|
|
40b5a03063 | ||
|
|
110beefe0b | ||
|
|
085f6dab2e | ||
|
|
e97070e36c | ||
|
|
93b8e9f0df | ||
|
|
697e9351e8 | ||
|
|
f30f73ed10 | ||
|
|
c634b5ddce | ||
|
|
86f0b33c65 | ||
|
|
593946d4aa | ||
|
|
5f09b7ef22 | ||
|
|
6d75786ee0 | ||
|
|
4297fbee6a | ||
|
|
a410fd7029 | ||
|
|
c111cd001e | ||
|
|
52fa265ac9 | ||
|
|
750170404a | ||
|
|
a5cc950a86 | ||
|
|
5ae8cd103a | ||
|
|
488e250259 | ||
|
|
6e77726ac9 | ||
|
|
c14381db8c | ||
|
|
8978159f21 | ||
|
|
59444343c4 | ||
|
|
ee082efdaf | ||
|
|
6dc8bb4d17 | ||
|
|
ff6a0ff2a5 | ||
|
|
4db6faa3e7 | ||
|
|
75e4116989 | ||
|
|
9e1645a495 | ||
|
|
29d25b62c5 | ||
|
|
a35f5ba889 | ||
|
|
fc9ff1401d | ||
|
|
33d10c02cd | ||
|
|
5dfc460876 | ||
|
|
014ce562a4 | ||
|
|
9dba38cc1a | ||
|
|
0fa2cd458e | ||
|
|
be3d09ab26 | ||
|
|
ba4469d3fd | ||
|
|
6951647e4c | ||
|
|
a7c141e818 | ||
|
|
76954c06a7 | ||
|
|
4352c3a6a1 | ||
|
|
43052f0819 | ||
|
|
119377cc49 | ||
|
|
016cd6a2fc | ||
|
|
a2aa24d236 | ||
|
|
eda432142d | ||
|
|
7bd2909875 | ||
|
|
323542cba1 | ||
|
|
98f3d25fe8 | ||
|
|
f3e1e15312 | ||
|
|
8cbda03867 | ||
|
|
b6839260cb | ||
|
|
1879299216 | ||
|
|
53af148f0f | ||
|
|
2c12891617 | ||
|
|
f25a870cec | ||
|
|
3d637e1302 | ||
|
|
b7e48c538c | ||
|
|
7ff707f6f8 | ||
|
|
de5399615c | ||
|
|
f7842a76db | ||
|
|
5bf2f828ef | ||
|
|
65aac0be46 | ||
|
|
55f33b7769 | ||
|
|
5e978d85a2 |
No files matched your search
@@ -1,15 +0,0 @@
|
||||
name: Swift
|
||||
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: macOS-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Build
|
||||
run: swift build -v
|
||||
- name: Run tests
|
||||
run: swift test -v -c release
|
||||
@@ -0,0 +1,23 @@
|
||||
name: Pull request
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
|
||||
jobs:
|
||||
tests:
|
||||
name: Test
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
|
||||
with:
|
||||
windows_exclude_swift_versions: '[{"swift_version": "5.9"}]'
|
||||
enable_wasm_sdk_build: true
|
||||
wasm_sdk_build_command: swift build --target Numerics
|
||||
soundness:
|
||||
name: Soundness
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
|
||||
with:
|
||||
license_header_check_project_name: "Swift Numerics"
|
||||
# https://github.com/apple/swift-numerics/issues/303
|
||||
license_header_check_enabled: false
|
||||
# https://github.com/apple/swift-numerics/issues/302
|
||||
format_check_enabled: false
|
||||
@@ -4,3 +4,4 @@
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
/.swiftpm
|
||||
.*.sw?
|
||||
@@ -0,0 +1,4 @@
|
||||
version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [Numerics, RealModule, ComplexModule]
|
||||
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<array/>
|
||||
</plist>
|
||||
@@ -0,0 +1,30 @@
|
||||
#[[
|
||||
This source file is part of the Swift Numerics open source project
|
||||
|
||||
Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
project(swift-numerics
|
||||
LANGUAGES Swift)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules)
|
||||
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift)
|
||||
|
||||
include(CTest)
|
||||
include(SwiftSupport)
|
||||
|
||||
add_subdirectory(Sources)
|
||||
|
||||
get_property(SWIFT_NUMERICS_EXPORTS GLOBAL PROPERTY SWIFT_NUMERICS_EXPORTS)
|
||||
export(TARGETS ${SWIFT_NUMERICS_EXPORTS}
|
||||
NAMESPACE SwiftNumerics::
|
||||
FILE swift-numerics-config.cmake
|
||||
EXPORT_LINK_INTERFACE_LIBRARIES)
|
||||
+82
-12
@@ -1,9 +1,9 @@
|
||||
// swift-tools-version:5.0
|
||||
// swift-tools-version:5.9
|
||||
//===--- 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-2025 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,92 @@
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let excludedFilenames = ["CMakeLists.txt", "README.md"]
|
||||
|
||||
let package = Package(
|
||||
|
||||
name: "swift-numerics",
|
||||
products: [
|
||||
.library(name: "Complex", targets: ["Complex"]),
|
||||
.library(name: "ComplexModule", targets: ["ComplexModule"]),
|
||||
.library(name: "Numerics", targets: ["Numerics"]),
|
||||
.library(name: "Real", targets: ["Real"]),
|
||||
],
|
||||
dependencies: [
|
||||
.library(name: "QuaternionModule", targets: ["QuaternionModule"]),
|
||||
.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: "Numerics",
|
||||
dependencies: [
|
||||
"ComplexModule",
|
||||
"IntegerUtilities",
|
||||
"QuaternionModule",
|
||||
"RealModule"],
|
||||
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: "QuaternionModule",
|
||||
dependencies: ["RealModule"],
|
||||
exclude: ["README.md", "Transformation.md"]
|
||||
),
|
||||
|
||||
.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: "ComplexTests",
|
||||
dependencies: ["_TestSupport"],
|
||||
exclude: ["CMakeLists.txt"]
|
||||
),
|
||||
|
||||
.testTarget(
|
||||
name: "IntegerUtilitiesTests",
|
||||
dependencies: ["_TestSupport"],
|
||||
exclude: ["CMakeLists.txt"]
|
||||
),
|
||||
|
||||
.testTarget(
|
||||
name: "RealTests",
|
||||
dependencies: ["_TestSupport"],
|
||||
exclude: ["CMakeLists.txt"]
|
||||
),
|
||||
|
||||
.testTarget(
|
||||
name: "QuaternionTests",
|
||||
dependencies: ["_TestSupport"],
|
||||
exclude: ["CMakeLists.txt"]
|
||||
)
|
||||
]
|
||||
)
|
||||
@@ -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", branch: "Quaternions"),
|
||||
```
|
||||
|
||||
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.
|
||||
4. When the design has stabilized and is functional enough to be useful, raise a PR to merge the new module to main.
|
||||
|
||||
### How to propose a new feature for an existing module
|
||||
|
||||
To propose a new feature for an existing module:
|
||||
1. Raise an issue with the [enhancement] tag.
|
||||
2. Raise a PR with your implementation, and discuss the implementation there.
|
||||
3. Once there is a consensus that the new feature is desirable and the design is suitable, it can be merged.
|
||||
|
||||
To fix a bug, or make smaller improvements:
|
||||
1. Raise a PR with your change. Be sure to add test coverage for whatever changes you are making.
|
||||
### How to fix a bug, or make smaller improvements
|
||||
|
||||
Questions about how to use Swift Numerics modules, or issues that are not clearly bugs can be discussed in the ["Swift Numerics" section of the Swift forums.](https://forums.swift.org/c/related-projects/swift-numerics)
|
||||
1. Raise a PR with your change.
|
||||
2. Make sure to add test coverage for whatever changes you are making.
|
||||
|
||||
### Forums
|
||||
|
||||
Questions about how to use Swift Numerics modules, or issues that are not clearly bugs can be discussed in the ["Swift Numerics" section of the Swift forums](https://forums.swift.org/c/related-projects/swift-numerics).
|
||||
|
||||
## Modules
|
||||
1. [Real](Sources/Real/README.md)
|
||||
2. [Complex](Sources/Complex/README.md)
|
||||
|
||||
1. [`RealModule`](Sources/RealModule/README.md)
|
||||
2. [`ComplexModule`](Sources/ComplexModule/README.md)
|
||||
3. [`QuaternionModule`](Sources/QuaternionModule/README.md) (on main only, not yet present in a released tag)
|
||||
4. [`IntegerUtilities`](Sources/IntegerUtilities/README.md) (on main only, not yet present in a released tag)
|
||||
|
||||
## 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.
|
||||
@@ -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()
|
||||
@@ -1,167 +0,0 @@
|
||||
//===--- Arithmetic.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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
@usableFromInline @_transparent
|
||||
internal func divided(by a: RealType) -> Complex {
|
||||
Complex(x/a, y/a)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Multiplicative structure
|
||||
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: Complex, w: Complex) -> Complex {
|
||||
// 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 lenSq = w.lengthSquared
|
||||
guard lenSq.isNormal else { return rescaledDivide(z, w) }
|
||||
return z * (w.conjugate.divided(by: lenSq))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func *=(z: inout Complex, w: Complex) {
|
||||
z = z * w
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func /=(z: inout Complex, w: Complex) {
|
||||
z = z / w
|
||||
}
|
||||
|
||||
@usableFromInline @_alwaysEmitIntoClient @inline(never)
|
||||
internal static func rescaledDivide(_ z: Complex, _ w: Complex) -> Complex {
|
||||
if w.isZero { return .infinity }
|
||||
if z.isZero || !w.isFinite { return .zero }
|
||||
// TODO: detect when RealType is Float and just promote to Double, then
|
||||
// use the naive algorithm.
|
||||
let zScale = z.magnitude
|
||||
let wScale = w.magnitude
|
||||
let zNorm = z.divided(by: zScale)
|
||||
let wNorm = w.divided(by: wScale)
|
||||
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
|
||||
// to avoid spurious overflow or underflow. There are three options
|
||||
// to choose from:
|
||||
//
|
||||
// - r * (zScale / wScale)
|
||||
// - (r * zScale) / wScale
|
||||
// - (r / wScale) * zScale
|
||||
//
|
||||
// The simplest case is when zScale / wScale is normal:
|
||||
if (zScale / wScale).isNormal {
|
||||
return r.multiplied(by: zScale / wScale)
|
||||
}
|
||||
// Otherwise, we need to compute either rNorm * zScale or rNorm / wScale
|
||||
// first. Choose the first if the first scaling behaves well, otherwise
|
||||
// choose the other one.
|
||||
if (r.magnitude * zScale).isNormal {
|
||||
return r.multiplied(by: zScale).divided(by: wScale)
|
||||
}
|
||||
return r.divided(by: wScale).multiplied(by: zScale)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@inlinable
|
||||
public var normalized: Complex? {
|
||||
if length.isNormal {
|
||||
return self.divided(by: length)
|
||||
}
|
||||
if isZero || !isFinite {
|
||||
return nil
|
||||
}
|
||||
return self.divided(by: magnitude).normalized
|
||||
}
|
||||
|
||||
/// The reciprocal of this value, if it can be computed without undue overflow or underflow.
|
||||
///
|
||||
/// If z.reciprocal is non-nil, you can safely replace division by z with multiplication by this value. It is
|
||||
/// not advantageous to do this for an isolated division, but if you are dividing many values by a single
|
||||
/// denominator, this will often be a significant performance win.
|
||||
///
|
||||
/// Typical use looks 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 let recip = divisor.reciprocal {
|
||||
/// return data.map { $0 * recip }
|
||||
/// }
|
||||
/// // Fallback on using division.
|
||||
/// return data.map { $0 / divisor }
|
||||
/// }
|
||||
/// ```
|
||||
@inlinable
|
||||
public var reciprocal: Complex? {
|
||||
let recip = 1/self
|
||||
if recip.isNormal || isZero || !isFinite {
|
||||
return recip
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
extension Complex: SignedNumeric {}
|
||||
@@ -1,513 +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 `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`
|
||||
/// - `.lengthSquared`
|
||||
@_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`
|
||||
/// - `.lengthSquared`
|
||||
/// - `.phase`
|
||||
/// - `.polar`
|
||||
/// - `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`
|
||||
/// - `.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`
|
||||
/// - `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)
|
||||
}
|
||||
|
||||
/// 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`
|
||||
/// - `.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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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-2025 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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
//===--- Complex+AlgebraicField.swift -------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 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: AlgebraicField {
|
||||
/// The multiplicative identity `1 + 0i`.
|
||||
///
|
||||
/// See also: ``zero``, ``i``, ``infinity``
|
||||
@_transparent
|
||||
public static var one: Complex {
|
||||
Complex(1, 0)
|
||||
}
|
||||
|
||||
/// The [complex conjugate][conj] of this value.
|
||||
///
|
||||
/// [conj]: https://en.wikipedia.org/wiki/Complex_conjugate
|
||||
@_transparent
|
||||
public var conjugate: Complex {
|
||||
Complex(x, -y)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func /=(z: inout Complex, w: Complex) {
|
||||
z = z / w
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func /(z: Complex, w: Complex) -> Complex {
|
||||
// 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 (see below).
|
||||
let lenSq = w.lengthSquared
|
||||
guard lenSq.isNormal else { return rescaledDivide(z, w) }
|
||||
return z * w.conjugate.divided(by: lenSq)
|
||||
}
|
||||
|
||||
@usableFromInline @_alwaysEmitIntoClient @inline(never)
|
||||
internal static func rescaledDivide(_ z: Complex, _ w: Complex) -> Complex {
|
||||
if w.isZero { return .infinity }
|
||||
if !w.isFinite { return .zero }
|
||||
// Scaling algorithm adapted from Doug Priest's "Efficient Scaling for
|
||||
// Complex Division":
|
||||
if w.magnitude < .leastNormalMagnitude {
|
||||
// A difference from Priest's algorithm is that he didn't have to worry
|
||||
// about types like Float16, where the significand width is comparable
|
||||
// to the exponent range, such that |leastNormalMagnitude|^(-¾) isn't
|
||||
// representable (e.g. for Float16 it would want to be 2¹⁸, but the
|
||||
// largest allowed exponent is 15). Note that it's critical to use zʹ/wʹ
|
||||
// after rescaling to avoid this, rather than falling through into the
|
||||
// normal rescaling, because otherwise we might end up back in the
|
||||
// situation where |w| ~ 1.
|
||||
let s = 1/(RealType(RealType.radix) * .leastNormalMagnitude)
|
||||
let wʹ = w.multiplied(by: s)
|
||||
let zʹ = z.multiplied(by: s)
|
||||
return zʹ / wʹ
|
||||
}
|
||||
// Having handled that case, we proceed pretty similarly to Priest:
|
||||
//
|
||||
// 1. Choose real scale s ~ |w|^(-¾), an exact power of the radix.
|
||||
// 2. wʹ ← sw
|
||||
// 3. zʹ ← sz
|
||||
// 4. return zʹ * (wʹ.conjugate / wʹ.lengthSquared) (i.e. zʹ/wʹ).
|
||||
//
|
||||
// Why is this safe and accurate? First, observe that wʹ and zʹ are both
|
||||
// computed exactly because:
|
||||
//
|
||||
// - s is an exact power of radix.
|
||||
// - wʹ ~ |w|^(¼), and hence cannot overflow or underflow.
|
||||
// - zʹ might overflow or underflow, but only if the final result also
|
||||
// overflows or underflows. (This is more subtle than I make it
|
||||
// sound. In particular, most of the fast ways one might try to
|
||||
// compute s give rise to a situation where when |w| is close to
|
||||
// one, multiplication by s is a dilation even though the actual
|
||||
// division is a contraction or vice-versa, and thus intermediate
|
||||
// computations might incorrectly overflow or underflow. Priest
|
||||
// had to take some care to avoid this situation, but we do not,
|
||||
// because we have already ruled out |w| ~ 1 before we call this
|
||||
// function.)
|
||||
//
|
||||
// Next observe that |wʹ.lengthSquared| ~ |w|^(½), so again this cannot
|
||||
// overflow or underflow, and neither can (wʹ.conjugate/wʹ.lengthSquared),
|
||||
// which has magnitude like |w|^(-¼).
|
||||
//
|
||||
// Note that because the scale factor is always a power of the radix,
|
||||
// the rescaling does not affect rounding, and so this algorithm is scale-
|
||||
// invariant compared to the mainline `/` implementation, up to the
|
||||
// underflow boundary.
|
||||
//
|
||||
// Note that our final assembly of the result is different from Priest;
|
||||
// he applies s to w twice, instead of once to w and once to z, and
|
||||
// does the product as (zw̅ʺ)*(1/|wʹ|²), while we do zʹ(w̅ʹ/|wʹ|²). We
|
||||
// prefer our version for three reasons:
|
||||
//
|
||||
// 1. it extracts a little more ILP
|
||||
// 2. it makes it so that we get exactly the same roundings on the
|
||||
// rescaled divide path as on the fast path, so that z/w = tz/tw
|
||||
// when tz and tw are computed exactly.
|
||||
// 3. it unlocks a future optimization where we hoist s and
|
||||
// (w̅ʹ/|wʹ|²) and make divisions all fast-path without perturbing
|
||||
// rounding.
|
||||
let s = RealType(
|
||||
sign: .plus,
|
||||
exponent: -3*w.magnitude.exponent/4,
|
||||
significand: 1
|
||||
)
|
||||
let wʹ = w.multiplied(by: s)
|
||||
let zʹ = z.multiplied(by: s)
|
||||
return zʹ * wʹ.conjugate.divided(by: wʹ.lengthSquared)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@inlinable
|
||||
public var normalized: Complex? {
|
||||
if length.isNormal {
|
||||
return self.divided(by: length)
|
||||
}
|
||||
if isZero || !isFinite {
|
||||
return nil
|
||||
}
|
||||
return self.divided(by: magnitude).normalized
|
||||
}
|
||||
|
||||
/// The reciprocal of this value, if it can be computed without undue
|
||||
/// overflow or underflow.
|
||||
///
|
||||
/// If z.reciprocal is non-nil, you can safely replace division by z with
|
||||
/// multiplication by this value. It is not advantageous to do this for an
|
||||
/// isolated division, but if you are dividing many values by a single
|
||||
/// denominator, this will often be a significant performance win.
|
||||
///
|
||||
/// 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, multiply by reciprocal.
|
||||
/// if let recip = divisor.reciprocal {
|
||||
/// return data.map { $0 * recip }
|
||||
/// }
|
||||
/// // Fallback on using division.
|
||||
/// 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
|
||||
if recip.isNormal || isZero || !isFinite {
|
||||
return recip
|
||||
}
|
||||
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))
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//===--- Complex+Codable.swift --------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 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,488 @@
|
||||
//===--- Complex+ElementaryFunctions.swift --------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 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
|
||||
// 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".
|
||||
//
|
||||
// Elementary functions of complex numbers have many similarities with
|
||||
// elementary functions of quaternions and their definition in terms of real
|
||||
// operations. Therefore, if you make a modification to one of the following
|
||||
// functions, you should almost surely make a parallel modification to the same
|
||||
// elementary function of quaternions.
|
||||
|
||||
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-2025 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-2025 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,59 @@
|
||||
//===--- Complex+Numeric.swift --------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 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 infinity-norm of the value (a.k.a. "maximum norm" or "Чебышёв
|
||||
/// [Chebyshev] norm").
|
||||
///
|
||||
/// Equal to `max(abs(real), abs(imaginary))`.
|
||||
///
|
||||
/// If you need to work with the Euclidean norm (a.k.a. 2-norm) instead,
|
||||
/// use the ``length`` or ``lengthSquared`` properties. If you just need
|
||||
/// to know "how big" a number is, use this property.
|
||||
///
|
||||
/// **Edge cases:**
|
||||
///
|
||||
/// - If `z` is not finite, `z.magnitude` is infinity.
|
||||
/// - If `z` is zero, `z.magnitude` is zero.
|
||||
/// - Otherwise, `z.magnitude` is finite and non-zero.
|
||||
@_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-2025 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)))"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
//===--- Complex.swift ----------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 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](https://en.wikipedia.org/wiki/Complex_number).
|
||||
// See Documentation.docc/Complex.md for more details.
|
||||
@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 storage for the real component of the value.
|
||||
@usableFromInline @inline(__always)
|
||||
internal var x: RealType
|
||||
|
||||
/// The storage for 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 value.
|
||||
///
|
||||
/// Use this when you need the underlying RealType values,
|
||||
/// without fixup for NaN or infinity.
|
||||
public var rawStorage: (x: RealType, y: RealType) {
|
||||
@_transparent
|
||||
get { (x, y) }
|
||||
@_transparent
|
||||
set { (x, y) = newValue }
|
||||
}
|
||||
|
||||
/// The raw representation of the real part of this value.
|
||||
@available(*, deprecated, message: "Use rawStorage")
|
||||
@_transparent
|
||||
public var _rawX: RealType { x }
|
||||
|
||||
/// The raw representation of the imaginary part of this value.
|
||||
@available(*, deprecated, message: "Use rawStorage")
|
||||
@_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 zero real part and specified imaginary 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
# ``Complex``
|
||||
|
||||
A complex number type represented by its real and imaginary parts, and equipped
|
||||
with the usual arithmetic operators and math functions.
|
||||
|
||||
## Overview
|
||||
|
||||
You can access these Cartesian components using the real and imaginary
|
||||
properties.
|
||||
|
||||
```swift
|
||||
let z = Complex(1,-1) // 1 - i
|
||||
let re = z.real // 1
|
||||
let im = z.imaginary // -1
|
||||
```
|
||||
|
||||
All `Complex` numbers with a non-finite component are treated as a single
|
||||
"point at infinity," with infinite magnitude and indeterminant phase. Thus,
|
||||
the real and imaginary parts of an infinity are nan.
|
||||
|
||||
```swift
|
||||
let w = Complex<Double>.infinity
|
||||
w == -w // true
|
||||
let re = w.real // .nan
|
||||
let im = w.imag // .nan
|
||||
```
|
||||
|
||||
See <doc:Infinity> for more details.
|
||||
|
||||
The ``magnitude`` property of a complex number is the infinity norm of the
|
||||
value (a.k.a. “maximum norm” or “Чебышёв [Chebyshev] norm”). To get the two
|
||||
norm (a.k.a. "Euclidean norm"), use the ``length`` property. See
|
||||
<doc:Magnitude> for more details.
|
||||
|
||||
## Topics
|
||||
|
||||
### Real and imaginary parts
|
||||
|
||||
- ``real``
|
||||
- ``imaginary``
|
||||
- ``rawStorage``
|
||||
- ``init(_:_:)``
|
||||
- ``init(_:)-5aesj``
|
||||
- ``init(imaginary:)``
|
||||
|
||||
### Phase, length and magnitude
|
||||
|
||||
- ``magnitude``
|
||||
- ``length``
|
||||
- ``lengthSquared``
|
||||
- ``normalized``
|
||||
- ``phase``
|
||||
- ``polar``
|
||||
- ``init(length:phase:)``
|
||||
|
||||
### Scaling by real numbers
|
||||
- ``multiplied(by:)``
|
||||
- ``divided(by:)``
|
||||
|
||||
### Complex-specific operations
|
||||
- ``conjugate``
|
||||
|
||||
### Classification
|
||||
- ``isZero``
|
||||
- ``isSubnormal``
|
||||
- ``isNormal``
|
||||
- ``isFinite``
|
||||
@@ -0,0 +1,88 @@
|
||||
# ``ComplexModule``
|
||||
|
||||
Types and operations for working with complex numbers.
|
||||
|
||||
## Overview
|
||||
|
||||
### Representation
|
||||
|
||||
The `Complex` type is generic over an associated `RealType`; complex numbers
|
||||
are represented as two `RealType` values, the real and imaginary parts of the
|
||||
number.
|
||||
|
||||
```
|
||||
let z = Complex<Double>(1, 2)
|
||||
let re = z.real
|
||||
let im = z.imaginary
|
||||
```
|
||||
|
||||
### Memory layout
|
||||
|
||||
A `Complex` value is stored as two `RealType` values arranged consecutively
|
||||
in memory. Thus it has the same memory layout as:
|
||||
- A Fortran complex value built on the corresponding real type (as used
|
||||
by BLAS and LAPACK).
|
||||
- A C struct with real and imaginary parts and nothing else (as used by
|
||||
computational libraries predating C99).
|
||||
- A C99 `_Complex` value built on the corresponding real type.
|
||||
- A C++ `std::complex` value built on the corresponding real type.
|
||||
Functions taking complex arguments in these other languages are not
|
||||
automatically converted on import, but you can safely write shims that
|
||||
map them into Swift types by converting pointers.
|
||||
|
||||
### Real-Complex arithmetic
|
||||
|
||||
Because the real numbers are a subset of the complex numbers, many
|
||||
languages support arithmetic with mixed real and complex operands.
|
||||
For example, C allows the following:
|
||||
|
||||
```c
|
||||
#include <complex.h>
|
||||
double r = 1;
|
||||
double complex z = CMPLX(0, 2); // 2i
|
||||
double complex w = r + z; // 1 + 2i
|
||||
```
|
||||
|
||||
The `Complex` type does not provide such mixed operators:
|
||||
|
||||
```swift
|
||||
let r = 1.0
|
||||
let z = Complex(imaginary: 2.0)
|
||||
let w = r + z // error: binary operator '+' cannot be applied to operands of type 'Double' and 'Complex<Double>'
|
||||
```
|
||||
|
||||
In order to write the example from C above in Swift, you have to perform an
|
||||
explicit conversion:
|
||||
|
||||
```swift
|
||||
let r = 1.0
|
||||
let z = Complex(imaginary: 2.0)
|
||||
let w = Complex(r) + z // OK
|
||||
```
|
||||
|
||||
There are two reasons for this choice. Most importantly, Swift generally avoids
|
||||
mixed-type arithmetic. Second, if we _did_ provide such heterogeneous operators,
|
||||
it would lead to undesirable behavior in common expressions when combined with
|
||||
literal type inference. Consider the following example:
|
||||
|
||||
```swift
|
||||
let a: Double = 1
|
||||
let b = 2*a
|
||||
```
|
||||
|
||||
`b` ought to have type `Double`, but if we did have a Complex-by-Real `*`
|
||||
operation, `2*a` would either be ambiguous (if there were no type context),
|
||||
or be inferred to have type `Complex<Double>` (if the expression appeared
|
||||
in the context of an extension defined on `Complex`).
|
||||
|
||||
Note that we _do_ provide heterogeneous multiplication and division by a real
|
||||
value, spelled as ``Complex/divided(by:)`` and ``Complex/multiplied(by:)``
|
||||
to avoid ambiguity.
|
||||
|
||||
```swift
|
||||
let z = Complex<Double>(1,3)
|
||||
let w = z.multiplied(by: 2)
|
||||
```
|
||||
|
||||
These operations are generally more efficient than converting the scale to
|
||||
a complex number and then using `*` or `/`.
|
||||
@@ -0,0 +1,55 @@
|
||||
# Zero and infinity
|
||||
|
||||
Semantics of `Complex` zero and infinity values, and important considerations
|
||||
when porting code from other languages.
|
||||
|
||||
## Overview
|
||||
|
||||
Unlike C and C++'s complex types, `Complex` does not attempt to make a
|
||||
semantic distinction between different infinity and NaN values. Any `Complex`
|
||||
datum with a non-finite component is treated as the "point at infinity" on
|
||||
the Riemann sphere--a value with infinite magnitude and unspecified phase.
|
||||
|
||||
As a consequence, all values with either component infinite or NaN compare
|
||||
equal, and hash the same. Similarly, all zero values compare equal and hash
|
||||
the same.
|
||||
|
||||
### Rationale
|
||||
|
||||
This choice has some drawbacks,¹ but also some significant advantages.
|
||||
In particular, complex multiplication is the most common operation performed
|
||||
with a complex type, and one would like to be able to use the usual naive
|
||||
arithmetic implementation, consisting of four real multiplications and two
|
||||
real additions:
|
||||
|
||||
```
|
||||
(a + bi) * (c + di) = (ac - bd) + (ad + bc)i
|
||||
```
|
||||
|
||||
`Complex` can use this implementation, because we do not differentiate between
|
||||
infinities and NaN values. C and C++, by contrast, cannot use this
|
||||
implementation by default, because, for example:
|
||||
|
||||
```
|
||||
(1 + ∞i) * (0 - 2i) = (1*0 - ∞*(-2)) + (1*(-2) + ∞*0)i
|
||||
= (0 - ∞) + (-2 + nan)i
|
||||
= -∞ + nan i
|
||||
```
|
||||
|
||||
`Complex` treats this as "infinity", which is the correct result. C and C++
|
||||
treat it as a nan value, however, which is incorrect; infinity multiplied
|
||||
by a non-zero number should be infinity. Thus, C and C++ (by default) must
|
||||
detect these special cases and fix them up, which makes multiplication a
|
||||
more computationally expensive operation.²
|
||||
|
||||
### Footnotes:
|
||||
¹ W. Kahan, Branch Cuts for Complex Elementary Functions, or Much Ado
|
||||
About Nothing's Sign Bit. In A. Iserles and M.J.D. Powell, editors,
|
||||
_Proceedings The State of Art in Numerical Analysis_, pages 165–211, 1987.
|
||||
|
||||
² This can be addressed in C programs by use of the `STDC CX_LIMITED_RANGE`
|
||||
pragma, which instructs the compiler to simply not care about these cases.
|
||||
Unfortunately, this pragma is not often used in real C or C++ programs
|
||||
(though it does see some use in _libraries_). Programmers tend to specify
|
||||
`-ffast-math` or maybe `-ffinite-math-only` instead, which has other
|
||||
undesirable consequences.
|
||||
@@ -0,0 +1,144 @@
|
||||
# Magnitude and norms
|
||||
|
||||
Introduction to the concept of norm and discussion of the `Complex` type's
|
||||
`.magnitude` property.
|
||||
|
||||
## Overview
|
||||
|
||||
In mathematics, a *norm* is a function that gives each element of a vector
|
||||
space a non-negative length.¹
|
||||
|
||||
Many different norms can be defined on the complex numbers, viewed as a
|
||||
vector space over the reals. All of these norms have some basic
|
||||
properties. If we use *‖z‖* to represent any norm of *z*, it must:
|
||||
- be *subadditive* (a.k.a. satisfy the triangle inequalty):
|
||||
‖z + w‖ ≤ ‖z‖ + ‖w‖ for any two complex numbers z and w.
|
||||
- be *homogeneous*
|
||||
‖az‖ = |a|‖z‖ for any real number a and complex number z.
|
||||
- and be *positive definite*
|
||||
‖z‖ is zero if and only if z is zero.
|
||||
|
||||
The three most commonly-used norms are:
|
||||
- 1-norm ("taxicab norm"):
|
||||
‖x + iy‖₁ = |x| + |y|
|
||||
- 2-norm ("Euclidean norm"):
|
||||
‖x + iy‖₂ = √(x² + y²)
|
||||
- ∞-norm ("maximum norm" or "Чебышёв [Chebyshev] norm")²:
|
||||
‖x + iy‖ = max(|x|,|y|)
|
||||
|
||||
> Exercise:
|
||||
> 1. Check that these properties hold for one of the three norms
|
||||
that we just defined. (Hint: write z = a+bi and w = c+di,
|
||||
and use the fact that the absolute value is a norm on the
|
||||
real numbers, and therefore has the same property).
|
||||
|
||||
The `Complex` type gives special names to two of these norms; `length`
|
||||
for the 2-norm, and `magnitude` for the ∞-norm.
|
||||
|
||||
### Magnitude:
|
||||
|
||||
The `Numeric` protocol requires us to choose a norm to call `magnitude`,
|
||||
but does not give guidance as to which one we should pick. The easiest choice
|
||||
might have been the Euclidean norm; it's the one with which people are most
|
||||
likely to be familiar.
|
||||
|
||||
However, there are good reasons to make a different choice:
|
||||
- Computing the Euclidean norm requires special care to avoid spurious
|
||||
overflow/underflow (see implementation notes for `length` below). The
|
||||
naive expressions for the taxicab and maximum norm always give the best
|
||||
answer possible.
|
||||
- Even when special care is used, the Euclidean and taxicab norms are
|
||||
not necessarily representable. Both can be infinite even for finite
|
||||
numbers.
|
||||
|
||||
```swift
|
||||
let big = Double.greatestFiniteMagnitude
|
||||
let z = Complex(big, big)
|
||||
```
|
||||
|
||||
The taxicab norm of `z` would be `big + big`, which overflows; the
|
||||
Euclidean norm would be `sqrt(2) * big`, which also overflows.
|
||||
But the maximum norm is always equal to the magnitude of either `real`
|
||||
or `imaginary`, so it is necessarily representable.
|
||||
- The ∞-norm is the choice of established computational libraries, like
|
||||
BLAS and LAPACK.
|
||||
|
||||
For these reasons, the `magnitude` property of `Complex` binds the
|
||||
maximum norm:
|
||||
|
||||
```swift
|
||||
Complex(2, 3).magnitude // 3
|
||||
Complex(-1, 0.5).magnitude // 1
|
||||
```
|
||||
|
||||
### Length:
|
||||
|
||||
The `length` property of a `Complex` value is its Euclidean norm.
|
||||
|
||||
```swift
|
||||
Complex(2, 3).length // 3.605551275463989
|
||||
Complex(-1, 0.5).length // 1.118033988749895
|
||||
```
|
||||
|
||||
Aside from familiarity, the Euclidean norm has one important property
|
||||
that the maximum norm lacks:
|
||||
- it is *multiplicative*:
|
||||
‖zw‖₂ = ‖z‖₂‖w‖₂ for any two complex numbers z and w.
|
||||
|
||||
> Exercises:
|
||||
> 1. Find z and w that show that the maximum norm is not multiplicative.
|
||||
(i.e. exhibit z and w such that ‖zw‖ ≠ ‖z‖‖w‖.)
|
||||
> 2. Is the 1-norm multiplicative?
|
||||
|
||||
### Implementation notes:
|
||||
|
||||
The `length` property takes special care to produce an accurate answer,
|
||||
even when the value is poorly-scaled. The naive expression for `length`
|
||||
would be `sqrt(x*x + y*y)`, but this can overflow or underflow even when
|
||||
the final result should be a finite number.
|
||||
|
||||
```swift
|
||||
// Suppose that length were implemented like this:
|
||||
extension Complex {
|
||||
var naiveLength: RealType {
|
||||
.sqrt(real*real + imaginary*imaginary)
|
||||
}
|
||||
}
|
||||
|
||||
// Then taking the length of even a modestly large number:
|
||||
let z = Complex<Float>(1e20, 1e20)
|
||||
// or small number:
|
||||
let w = Complex<Float>(1e-24, 1e-24)
|
||||
// would overflow:
|
||||
z.naiveLength // Inf
|
||||
// or underflow:
|
||||
w.naiveLength // 0
|
||||
```
|
||||
|
||||
Instead, `length` is implemented using a two-step algorithm. First we
|
||||
compute `lengthSquared`, which is `x*x + y*y`. If this is a normal
|
||||
number (meaning that no overflow or underflow has occured), we can safely
|
||||
return its square root. Otherwise, we redo the computation with a more
|
||||
careful computation, which avoids spurious under- or overflow:
|
||||
|
||||
```swift
|
||||
let z = Complex<Float>(1e20, 1e20)
|
||||
let w = Complex<Float>(1e-24, 1e-24)
|
||||
z.length // 1.41421358E+20
|
||||
w.length // 1.41421362E-24
|
||||
```
|
||||
|
||||
### Footnotes:
|
||||
|
||||
¹ Throughout this documentation, "norm" refers to a
|
||||
[vector norm](https://en.wikipedia.org/wiki/Norm_(mathematics)).
|
||||
To confuse the matter, there are several similar things also called
|
||||
"norm" in mathematics. The other one you are most likely to run into
|
||||
is the [field norm](https://en.wikipedia.org/wiki/Field_norm).
|
||||
|
||||
Field norms are much less common than vector norms, but the C++
|
||||
`std::norm` operation implements a field norm. To get the (Euclidean)
|
||||
vector norm in C++, use `std::abs`.
|
||||
|
||||
² There's no subscript-∞ in unicode, so I write the infinity norm
|
||||
without the usual subscript.
|
||||
@@ -0,0 +1,130 @@
|
||||
//===--- Polar.swift ------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 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).
|
||||
///
|
||||
/// 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. See <doc:Magnitude> for more details.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// - If a complex value is not finite, its `length` is `infinity`.
|
||||
///
|
||||
/// See also ``lengthSquared``, ``phase``, ``polar``
|
||||
/// and ``init(length:phase:)``.
|
||||
@_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.
|
||||
///
|
||||
/// Note that because of how `lengthSquared` is used, it is a primary
|
||||
/// design goal that it be as fast as possible. Therefore, it does not
|
||||
/// normalize infinities, and may return either `.infinity` or `.nan`
|
||||
/// for non-finite values.
|
||||
@_transparent
|
||||
public var lengthSquared: 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.
|
||||
///
|
||||
/// See also ``length``, ``polar`` and ``init(length:phase:)``.
|
||||
@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(length:phase:)``.
|
||||
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.
|
||||
@@ -0,0 +1,41 @@
|
||||
//===--- Scale.swift ------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 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.
|
||||
|
||||
extension Complex {
|
||||
/// The result of multiplying this value by the real number `a`.
|
||||
///
|
||||
/// Equivalent to `self * Complex(a)`, but may be computed more efficiently.
|
||||
@inlinable @inline(__always)
|
||||
public func multiplied(by a: RealType) -> Complex {
|
||||
Complex(x*a, y*a)
|
||||
}
|
||||
|
||||
/// The result of dividing this value by the real number `a`.
|
||||
///
|
||||
/// More efficient than `self / Complex(a)`. May not produce exactly the
|
||||
/// same result, but will always be more accurate if they differ.
|
||||
@inlinable @inline(__always)
|
||||
public func divided(by a: RealType) -> Complex {
|
||||
Complex(x/a, y/a)
|
||||
}
|
||||
}
|
||||
@@ -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,325 @@
|
||||
//===--- 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`.
|
||||
///
|
||||
/// By default, this function uses ``RoundingRule/down``, which **is not
|
||||
/// the same** as the rounding of the `/` operator from the Swift standard
|
||||
/// library. They agree when the signs of the arguments match, but produce
|
||||
/// different results when the quotient is negative. This behavior is
|
||||
/// chosen because it generally produces a more useful remainder; in
|
||||
/// particular, when the divisor is positive, the remainder is always
|
||||
/// positive. To match the behavior of `/`, use ``RoundingRule/towardZero``.
|
||||
///
|
||||
/// Note that the remainder of division is not always representable in an
|
||||
/// unsigned type if a rounding rule other than ``RoundingRule/down``,
|
||||
/// ``RoundingRule/towardZero``, or ``RoundingRule/requireExact`` is
|
||||
/// used. For example:
|
||||
/// ```swift
|
||||
/// 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 the `SignedInteger` protocol is extended with
|
||||
/// ``SignedInteger/divided(by:rounding:)`` returning 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 .awayFromZero:
|
||||
break
|
||||
|
||||
case .toNearestOrDown:
|
||||
if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||
|
||||
2*r.magnitude == other.magnitude && other.signum() != r.signum() {
|
||||
break
|
||||
}
|
||||
return q
|
||||
|
||||
case .toNearestOrUp:
|
||||
if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||
|
||||
2*r.magnitude == other.magnitude && other.signum() == r.signum() {
|
||||
break
|
||||
}
|
||||
return q
|
||||
|
||||
case .toNearestOrZero:
|
||||
if r.magnitude <= other.magnitude.shifted(rightBy: 1, rounding: .down) {
|
||||
return q
|
||||
}
|
||||
// Otherwise, round q away from zero.
|
||||
|
||||
case .toNearestOrAway:
|
||||
if r.magnitude < other.magnitude.shifted(rightBy: 1, rounding: .up) {
|
||||
return q
|
||||
}
|
||||
|
||||
case .toNearestOrEven:
|
||||
// First guarantee that |r| <= |other/2|; if not we have to round away
|
||||
// instead, so break to do that.
|
||||
if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||
|
||||
2*r.magnitude == other.magnitude && !q.isMultiple(of: 2) {
|
||||
break
|
||||
}
|
||||
return q
|
||||
|
||||
case .toOdd:
|
||||
// If q is already odd, we have the correct result.
|
||||
if q._lowWord & 1 == 1 { return q }
|
||||
|
||||
case .requireExact:
|
||||
preconditionFailure("Division was not exact.")
|
||||
}
|
||||
|
||||
// We didn't have the right result, so round q away from zero.
|
||||
return other.signum() == r.signum() ? q+1 : q-1
|
||||
}
|
||||
|
||||
// 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 ``RoundingRule/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 ``RoundingRule/towardZero``.
|
||||
///
|
||||
/// - 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 ``RoundingRule/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 ``RoundingRule/towardZero``.
|
||||
///
|
||||
/// 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.
|
||||
return other.signum() == r.signum() ? (q, r) : (q-1, r+other)
|
||||
|
||||
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.
|
||||
return other.signum() == r.signum() ? (q+1, r-other) : (q, r)
|
||||
|
||||
case .towardZero:
|
||||
// This is exactly what the `/` operator did for us.
|
||||
return (q, r)
|
||||
|
||||
case .awayFromZero:
|
||||
break
|
||||
|
||||
case .toNearestOrDown:
|
||||
// If |r| < |other/2|, we already rounded q to nearest. If the are
|
||||
// equal and q is negative, then we already broke the tie in the right
|
||||
// direction. However, we don't have access to the before-rounding q,
|
||||
// which may have rounded up to zero, losing the sign information, so
|
||||
// we have to look at other and r instead.
|
||||
if 2*r.magnitude < other.magnitude ||
|
||||
2*r.magnitude == other.magnitude && other.signum() == r.signum() {
|
||||
return (q, r)
|
||||
}
|
||||
|
||||
case .toNearestOrUp:
|
||||
// If |r| < |other/2|, we already rounded q to nearest. If the are
|
||||
// equal and q is non-negative, then we already broke the tie in the
|
||||
// right direction.
|
||||
if 2*r.magnitude < other.magnitude ||
|
||||
2*r.magnitude == other.magnitude && other.signum() != r.signum() {
|
||||
return (q, r)
|
||||
}
|
||||
|
||||
case .toNearestOrZero:
|
||||
// Check first if |r| <= |other/2|. If this holds, we have already
|
||||
// rounded q correctly. Because we're working with magnitudes, we can
|
||||
// safely compute 2r without worrying about overflow, even for fixed-
|
||||
// width types, because r cannot be .min (because |r| < |other| by
|
||||
// construction).
|
||||
if 2*r.magnitude <= other.magnitude {
|
||||
return (q, r)
|
||||
}
|
||||
|
||||
case .toNearestOrAway:
|
||||
// Check first if |r| < |other/2|. If this holds, we already rounded
|
||||
// q to nearest.
|
||||
if 2*r.magnitude < other.magnitude {
|
||||
return (q, r)
|
||||
}
|
||||
|
||||
case .toNearestOrEven:
|
||||
// If |r| < |other/2|, we already rounded q to nearest. If the are
|
||||
// equal and q is even, then we already broke the tie in the right
|
||||
// direction.
|
||||
if 2*r.magnitude < other.magnitude ||
|
||||
2*r.magnitude == other.magnitude && q.isMultiple(of: 2) {
|
||||
return (q, r)
|
||||
}
|
||||
|
||||
case .toOdd:
|
||||
// If q is already odd, we have the correct result.
|
||||
if q._lowWord & 1 == 1 { return (q, r) }
|
||||
|
||||
case .requireExact:
|
||||
preconditionFailure("Division was not exact.")
|
||||
}
|
||||
|
||||
// Fallthrough behavior is to round q away from zero and adjust r to
|
||||
// match.
|
||||
return other.signum() == r.signum() ? (q+1, r-other) : (q-1, r+other)
|
||||
}
|
||||
}
|
||||
|
||||
/// `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`.
|
||||
public func euclideanDivision<T>(_ a: T, _ b: T) -> (quotient: T, remainder: T)
|
||||
where T: SignedInteger
|
||||
{
|
||||
a.divided(by: b, rounding: a >= 0 ? .towardZero : .awayFromZero)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//===--- GCD.swift --------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2021-2024 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][gcd] 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
|
||||
///
|
||||
/// [gcd]: https://en.wikipedia.org/wiki/Greatest_common_divisor
|
||||
@inlinable
|
||||
public func gcd<T: BinaryInteger>(_ a: T, _ b: T) -> T {
|
||||
var x = a
|
||||
var y = b
|
||||
if x.magnitude < y.magnitude { swap(&x, &y) }
|
||||
// Avoid overflow when x = signed min, y = -1.
|
||||
if y.magnitude == 1 { return 1 }
|
||||
// Euclidean algorithm for GCD. It's worth using Lehmer instead for larger
|
||||
// integer types, but for now this is good and dead-simple and faster than
|
||||
// the other obvious choice, the binary algorithm.
|
||||
while y != 0 { (x, y) = (y, x%y) }
|
||||
// Try to convert result to T.
|
||||
if let result = T(exactly: x.magnitude) { return result }
|
||||
// If that fails, produce a diagnostic.
|
||||
fatalError("GCD (\(x)) is not representable as \(T.self).")
|
||||
}
|
||||
@@ -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:)
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
//===--- RoundingRule.swift -----------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2021-2025 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:
|
||||
/// ```
|
||||
/// Directed rounding rules
|
||||
///
|
||||
/// value | down | up | towardZero | awayFromZero |
|
||||
/// =======+==============+==============+==============+==============+
|
||||
/// -1.5 | -2 | -1 | -1 | -2 |
|
||||
/// -------+--------------+--------------+--------------+--------------+
|
||||
/// -0.5 | -1 | 0 | 0 | -1 |
|
||||
/// -------+--------------+--------------+--------------+--------------+
|
||||
/// 0.5 | 0 | 1 | 0 | 1 |
|
||||
/// -------+--------------+--------------+--------------+--------------+
|
||||
/// 0.7 | 0 | 1 | 0 | 1 |
|
||||
/// -------+--------------+--------------+--------------+--------------+
|
||||
/// 1.2 | 1 | 2 | 1 | 2 |
|
||||
/// -------+--------------+--------------+--------------+--------------+
|
||||
/// 2.0 | 2 | 2 | 2 | 2 |
|
||||
/// -------+--------------+--------------+--------------+--------------+
|
||||
///
|
||||
/// toNearestOr... rounding rules
|
||||
///
|
||||
/// value | orDown | orUp | orZero | orAway | orEven |
|
||||
/// =======+==========+==========+==========+==========+==========+
|
||||
/// -1.5 | -2 | -1 | -1 | -2 | -2 |
|
||||
/// -------+----------+----------+----------+----------+----------+
|
||||
/// -0.5 | -1 | 0 | 0 | -1 | 0 |
|
||||
/// -------+----------+----------+----------+----------+----------+
|
||||
/// 0.5 | 0 | 1 | 0 | 1 | 0 |
|
||||
/// -------+----------+----------+----------+----------+----------+
|
||||
/// 0.7 | 1 | 1 | 1 | 1 | 1 |
|
||||
/// -------+----------+----------+----------+----------+----------+
|
||||
/// 1.2 | 1 | 1 | 1 | 1 | 1 |
|
||||
/// -------+----------+----------+----------+----------+----------+
|
||||
/// 2.0 | 2 | 2 | 2 | 2 | 2 |
|
||||
/// -------+----------+----------+----------+----------+----------+
|
||||
///
|
||||
/// Specialized rounding rules
|
||||
///
|
||||
/// value | toOdd | requireExact |
|
||||
/// =======+==============+================+
|
||||
/// -1.5 | -1 | trap |
|
||||
/// -------+--------------+----------------+
|
||||
/// -0.5 | -1 | trap |
|
||||
/// -------+--------------+----------------+
|
||||
/// 0.5 | 1 | trap |
|
||||
/// -------+--------------+----------------+
|
||||
/// 0.7 | 1 | trap |
|
||||
/// -------+--------------+----------------+
|
||||
/// 1.2 | 1 | trap |
|
||||
/// -------+--------------+----------------+
|
||||
/// 2.0 | 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 is less than
|
||||
/// the value being rounded is chosen.
|
||||
///
|
||||
/// Examples:
|
||||
/// - `(-4).divided(by: 3, rounding: .toNearestOrDown)`
|
||||
/// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2.
|
||||
///
|
||||
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrDown)` is `2`,
|
||||
/// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is less.
|
||||
case toNearestOrDown
|
||||
|
||||
/// Produces the representable value that is closest to the value being
|
||||
/// rounded. If two values are equally close, the one that is greater than
|
||||
/// the value being rounded is chosen.
|
||||
///
|
||||
/// Examples:
|
||||
/// - `(-4).divided(by: 3, rounding: .toNearestOrUp)`
|
||||
/// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2.
|
||||
///
|
||||
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrUp)` is `3`,
|
||||
/// because 5/2 = 2.5 is equally close to 2 and 3, and 3 is greater.
|
||||
case toNearestOrUp
|
||||
|
||||
/// Produces the representable value that is closest to the value being
|
||||
/// rounded. If two values are equally close, the one that has smaller
|
||||
/// magnitude is returned.
|
||||
///
|
||||
/// Examples:
|
||||
/// - `(-4).divided(by: 3, rounding: .toNearestOrZero)`
|
||||
/// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2.
|
||||
///
|
||||
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrZero)` is `3`,
|
||||
/// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is closer to zero.
|
||||
case toNearestOrZero
|
||||
|
||||
/// 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: .toNearestOrAway)`
|
||||
/// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2.
|
||||
///
|
||||
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrAway)` is `3`,
|
||||
/// because 5/2 = 2.5 is equally close to 2 and 3, and 3 is further away
|
||||
/// from zero.
|
||||
case toNearestOrAway
|
||||
|
||||
/// 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
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
extension RoundingRule {
|
||||
/// 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.
|
||||
///
|
||||
/// > Deprecated: Use `.toNearestOrAway` instead.
|
||||
@inlinable
|
||||
@available(*, deprecated, renamed: "toNearestOrAway")
|
||||
public static var toNearestOrAwayFromZero: Self { .toNearestOrAway }
|
||||
}
|
||||
|
||||
extension FloatingPoint {
|
||||
/// `self` rounded to integer according to `rule`.
|
||||
///
|
||||
/// This mirrors the standard library `rounded` API, providing access to
|
||||
/// the expanded set of rounding rules defined in IntegerUtilities. It is
|
||||
/// not just a shadow because that would lead to ambiguity errors in
|
||||
/// existing code that uses the shortened `rounded(.down)` form.
|
||||
@inlinable @inline(__always)
|
||||
public func rounding(_ rule: RoundingRule) -> Self {
|
||||
switch rule {
|
||||
case .down:
|
||||
return rounded(.down)
|
||||
case .up:
|
||||
return rounded(.up)
|
||||
case .towardZero:
|
||||
return rounded(.towardZero)
|
||||
case .awayFromZero:
|
||||
return rounded(.awayFromZero)
|
||||
case .toNearestOrDown:
|
||||
// FP doesn't have toNearestOrDown, so round toNearestOrEven and fixup
|
||||
// any exact-halfway cases.
|
||||
let nearest = rounded(.toNearestOrEven)
|
||||
return nearest - self == 1/2 ? rounded(.down) : nearest
|
||||
case .toNearestOrUp:
|
||||
// FP doesn't have toNearestOrUp, so round toNearestOrEven and fixup
|
||||
// any exact-halfway cases.
|
||||
let nearest = rounded(.toNearestOrEven)
|
||||
return self - nearest == 1/2 ? rounded(.up) : nearest
|
||||
case .toNearestOrZero:
|
||||
// FP doesn't have toNearestOrZero, so round toNearestOrEven and fixup
|
||||
// any exact-halfway cases.
|
||||
let nearest = rounded(.toNearestOrEven)
|
||||
return (self - nearest).magnitude == 1/2 ? rounded(.towardZero) : nearest
|
||||
case .toNearestOrAway:
|
||||
return self.rounded(.toNearestOrAwayFromZero)
|
||||
case .toNearestOrEven:
|
||||
return self.rounded(.toNearestOrEven)
|
||||
case .toOdd:
|
||||
let trunc = rounded(.towardZero)
|
||||
if trunc == self { return trunc }
|
||||
let one = Self(signOf: self, magnitudeOf: 1)
|
||||
// We have eliminated all large values at this point; add ±0.5, and see
|
||||
// which way that rounds, then select the other value.
|
||||
let even = (trunc + one/2).rounded(.toNearestOrEven)
|
||||
return trunc == even ? trunc + one : trunc
|
||||
case .requireExact:
|
||||
let trunc = rounded(.towardZero)
|
||||
precondition(isInfinite || trunc == self, "\(self) is not an exact integer.")
|
||||
return self
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
/// ```
|
||||
///
|
||||
/// If the "normal addition" `self + other` does not trap,
|
||||
/// this method 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.
|
||||
///
|
||||
/// If the "normal subtraction" `self - other` does not trap,
|
||||
/// this method 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)
|
||||
/// ```
|
||||
///
|
||||
/// If the "normal multiplication" `self * other` does not trap,
|
||||
/// this method 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 shift 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:)`, defined on `BinaryInteger`, 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,177 @@
|
||||
//===--- 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 ``RoundingRule/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)
|
||||
let half: Magnitude = (1 as Magnitude) << (count &- 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 .toNearestOrDown:
|
||||
return floor + Self((lost + (half - 1)) >> count)
|
||||
case .toNearestOrUp:
|
||||
return floor + Self((lost + half) >> count)
|
||||
case .toNearestOrZero:
|
||||
let round = half - (self < 0 ? 0 : 1)
|
||||
return floor + Self((round + lost) >> count)
|
||||
case .toNearestOrAway:
|
||||
let round = half - (self > 0 ? 0 : 1)
|
||||
return floor + Self((round + lost) >> count)
|
||||
case .toNearestOrEven:
|
||||
let round = mask >> 1 + Magnitude(floor & 1)
|
||||
return floor + Self((round + lost) >> count)
|
||||
case .toOdd:
|
||||
return floor | (lost == 0 ? 0 : 1)
|
||||
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 ``RoundingRule/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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#[[
|
||||
This source file is part of the Swift Numerics open source project
|
||||
|
||||
Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
add_library(Numerics
|
||||
Numerics.swift)
|
||||
set_target_properties(Numerics PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
# NOTE: generate the force load symbol to ensure that the import library is
|
||||
# generated on Windows for autolinking.
|
||||
target_compile_options(Numerics PUBLIC
|
||||
$<$<NOT:$<PLATFORM_ID:Darwin>>:-autolink-force-load>
|
||||
# SR-12254: workaround for the swift compiler not properly tracking the force
|
||||
# load symbol when validating the TBD
|
||||
-Xfrontend -validate-tbd-against-ir=none)
|
||||
target_link_libraries(Numerics PUBLIC
|
||||
ComplexModule
|
||||
IntegerUtilities
|
||||
RealModule)
|
||||
|
||||
|
||||
_install_target(Numerics)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_NUMERICS_EXPORTS Numerics)
|
||||
@@ -10,5 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// A module that re-exports the complete Swift Numerics public API.
|
||||
@_exported import Real
|
||||
@_exported import Complex
|
||||
@_exported import ComplexModule
|
||||
@_exported import IntegerUtilities
|
||||
@_exported import RealModule
|
||||
@_exported import QuaternionModule
|
||||
@@ -0,0 +1,83 @@
|
||||
//===--- ImaginaryHelper.swift --------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2019-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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// Provides common vector operations on SIMD3 to ease the use of the quaternions
|
||||
// imaginary/vector components internally to the module, and in tests.
|
||||
extension SIMD3 where Scalar: FloatingPoint {
|
||||
/// Returns a vector with infinity in all lanes
|
||||
@usableFromInline @inline(__always)
|
||||
internal static var infinity: Self {
|
||||
SIMD3(repeating: .infinity)
|
||||
}
|
||||
|
||||
/// Returns a vector with nan in all lanes
|
||||
@usableFromInline @inline(__always)
|
||||
internal static var nan: Self {
|
||||
SIMD3(repeating: .nan)
|
||||
}
|
||||
|
||||
/// True if all values of this instance are finite
|
||||
@usableFromInline @inline(__always)
|
||||
internal var isFinite: Bool {
|
||||
x.isFinite && y.isFinite && z.isFinite
|
||||
}
|
||||
|
||||
/// The ∞-norm of the value (`max(abs(x), abs(y), abs(z))`).
|
||||
@usableFromInline @inline(__always)
|
||||
internal var magnitude: Scalar {
|
||||
Swift.max(x.magnitude, y.magnitude, z.magnitude)
|
||||
}
|
||||
|
||||
/// The 1-norm of the value (`abs(x) + abs(y) + abs(z))`).
|
||||
@usableFromInline @inline(__always)
|
||||
internal var oneNorm: Scalar {
|
||||
x.magnitude + y.magnitude + z.magnitude
|
||||
}
|
||||
|
||||
/// The Euclidean norm (a.k.a. 2-norm, `sqrt(x*x + y*y + z*z)`).
|
||||
@usableFromInline @inline(__always)
|
||||
internal var length: Scalar {
|
||||
let naive = lengthSquared
|
||||
guard naive.isNormal else { return carefulLength }
|
||||
return naive.squareRoot()
|
||||
}
|
||||
|
||||
// Implementation detail of `length`, moving slow path off of the
|
||||
// inline function.
|
||||
@usableFromInline
|
||||
internal var carefulLength: Scalar {
|
||||
guard isFinite else { return .infinity }
|
||||
guard !magnitude.isZero else { return .zero }
|
||||
// Unscale the vector, calculate its length and rescale the result
|
||||
return (self / magnitude).length * magnitude
|
||||
}
|
||||
|
||||
/// Returns the squared length of this instance.
|
||||
@usableFromInline @inline(__always)
|
||||
internal var lengthSquared: Scalar {
|
||||
dot(self)
|
||||
}
|
||||
|
||||
/// Returns the scalar/dot product of this vector with `other`.
|
||||
@usableFromInline @inline(__always)
|
||||
internal func dot(_ other: SIMD3<Scalar>) -> Scalar {
|
||||
(self * other).sum()
|
||||
}
|
||||
|
||||
/// Returns the vector/cross product of this vector with `other`.
|
||||
@usableFromInline @inline(__always)
|
||||
internal func cross(_ other: SIMD3<Scalar>) -> SIMD3<Scalar> {
|
||||
let yzx = SIMD3<Int>(1,2,0)
|
||||
let zxy = SIMD3<Int>(2,0,1)
|
||||
return (self[yzx] * other[zxy]) - (self[zxy] * other[yzx])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
//===--- Polar.swift ------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2022 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
|
||||
|
||||
// Norms and related quantities defined for Quaternion.
|
||||
//
|
||||
// The following API are provided by this extension:
|
||||
//
|
||||
// var magnitude: RealType // infinity norm
|
||||
// var length: RealType // Euclidean norm
|
||||
// var lengthSquared: RealType // Euclidean norm squared
|
||||
//
|
||||
// For detailed documentation, consult Norms.md or the inline documentation
|
||||
// for each operation.
|
||||
//
|
||||
// Implementation notes:
|
||||
//
|
||||
// `.magnitude` does not bind the Euclidean norm; it binds the infinity norm
|
||||
// instead. There are two reasons for this choice:
|
||||
//
|
||||
// - It's simply faster to compute in general, because it does not require
|
||||
// a square root.
|
||||
//
|
||||
// - There exist finite values `q` for which the Euclidean norm is not
|
||||
// representable (consider the quaternion with `r`, `x`, `y` and `z` all
|
||||
// equal to `RealType.greatestFiniteMagnitude`; the Euclidean norm is
|
||||
// `.sqrt(4) * .greatestFiniteMagnitude`, which overflows).
|
||||
//
|
||||
// The infinity norm is unique among the common vector norms in having
|
||||
// the property that every finite vector has a representable finite norm,
|
||||
// which makes it the obvious choice to bind `.magnitude`.
|
||||
extension Quaternion {
|
||||
/// The Euclidean norm (a.k.a. 2-norm, `sqrt(r*r + x*x + y*y + z*z)`).
|
||||
///
|
||||
/// This value is highly prone to overflow or underflow.
|
||||
///
|
||||
/// 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 quaternion is not finite, its `.length` is `infinity`.
|
||||
///
|
||||
/// See also `.magnitude`, `.lengthSquared`, `.polar` and
|
||||
/// `init(length:halfAngle:axis:)`.
|
||||
@_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.
|
||||
@usableFromInline
|
||||
internal var carefulLength: RealType {
|
||||
guard isFinite else { return .infinity }
|
||||
guard !magnitude.isZero else { return .zero }
|
||||
// Unscale the quaternion, calculate its length and rescale the result
|
||||
return divided(by: magnitude).length * magnitude
|
||||
}
|
||||
|
||||
/// The squared length `(r*r + x*x + y*y + z*z)`.
|
||||
///
|
||||
/// This value is highly prone to overflow or underflow.
|
||||
///
|
||||
/// For many cases, `.magnitude` can be used instead, which is similarly
|
||||
/// cheap to compute and always returns a representable value.
|
||||
///
|
||||
/// This property is more efficient to compute than `length`.
|
||||
///
|
||||
/// See also `.magnitude`, `.length`, `.polar` and
|
||||
/// `init(length:halfAngle:axis:)`.
|
||||
@_transparent
|
||||
public var lengthSquared: RealType {
|
||||
(components * components).sum()
|
||||
}
|
||||
|
||||
/// The half rotation angle in radians within *[0, π]* range.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// - If the quaternion is zero or non-finite, halfAngle is `nan`.
|
||||
@inlinable
|
||||
public var halfAngle: RealType {
|
||||
guard isFinite else { return .nan }
|
||||
// A zero quaternion does not encode transformation properties.
|
||||
// If imaginary is zero, real must be non-zero or nan is returned.
|
||||
guard !isReal else { return isPure ? .nan : .zero }
|
||||
// If lengthSquared computes without over/underflow, everything is fine
|
||||
// and the result is correct. If not, we have to do the computation
|
||||
// carefully and unscale the quaternion first.
|
||||
let lenSq = imaginary.lengthSquared
|
||||
guard lenSq.isNormal else { return divided(by: magnitude).halfAngle }
|
||||
return .atan2(y: .sqrt(lenSq), x: real)
|
||||
}
|
||||
|
||||
/// The [polar decomposition][wiki].
|
||||
///
|
||||
/// Returns the length of this quaternion, halfAngle in radians of range
|
||||
/// *[0, π]* and the rotation axis as SIMD3 vector of unit length.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// - If the quaternion is zero, length is `.zero` and halfAngle and axis
|
||||
/// are `nan`.
|
||||
/// - If the quaternion is non-finite, length is `.infinity` and halfAngle and
|
||||
/// axis are `nan`.
|
||||
/// - For any length other than `.zero` or `.infinity`, if halfAngle is zero,
|
||||
/// axis is `nan`.
|
||||
///
|
||||
/// See also `.magnitude`, `.length`, `.lengthSquared` and
|
||||
/// `init(length:halfAngle:axis:)`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Polar_decomposition#Quaternion_polar_decomposition
|
||||
public var polar: (
|
||||
length: RealType,
|
||||
halfAngle: RealType,
|
||||
axis: SIMD3<RealType>
|
||||
) {
|
||||
(length, halfAngle, axis)
|
||||
}
|
||||
|
||||
/// Creates a new quaternion from given half rotation angle about given
|
||||
/// rotation axis.
|
||||
///
|
||||
/// The angle-axis values are transformed using the following equation:
|
||||
///
|
||||
/// Q = (cos(halfAngle), unitAxis * sin(halfAngle))
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - halfAngle: The half rotation angle
|
||||
/// - unitAxis: The rotation axis of unit length
|
||||
@usableFromInline @inline(__always)
|
||||
internal init(halfAngle: RealType, unitAxis: SIMD3<RealType>) {
|
||||
self.init(real: .cos(halfAngle), imaginary: unitAxis * .sin(halfAngle))
|
||||
}
|
||||
|
||||
/// Creates a quaternion specified with [polar coordinates][wiki].
|
||||
///
|
||||
/// This initializer reads given `length`, `halfAngle` and `axis` values and
|
||||
/// creates a quaternion of equal rotation properties and specified *length*
|
||||
/// using the following equation:
|
||||
///
|
||||
/// Q = (cos(halfAngle), axis * sin(halfAngle)) * length
|
||||
///
|
||||
/// Edge cases:
|
||||
/// - Negative lengths are interpreted as reflecting the point through the
|
||||
/// origin, i.e.:
|
||||
/// ```
|
||||
/// Quaternion(length: -r, halfAngle: θ, axis: axis) == -Quaternion(length: r, halfAngle: θ, axis: axis)
|
||||
/// ```
|
||||
/// - For any `θ` and any `axis`, even `.infinity` or `.nan`:
|
||||
/// ```
|
||||
/// Quaternion(length: .zero, halfAngle: θ, axis: axis) == .zero
|
||||
/// ```
|
||||
/// - For any `θ` and any `axis`, even `.infinity` or `.nan`:
|
||||
/// ```
|
||||
/// Quaternion(length: .infinity, halfAngle: θ, axis: axis) == .infinity
|
||||
/// ```
|
||||
/// - Otherwise, `θ` must be finite, or a precondition failure occurs and
|
||||
/// `axis` must be of unit length, or an assertion failure occurs.
|
||||
///
|
||||
/// See also `.magnitude`, `.length`, `.lengthSquared` and `.polar`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Polar_decomposition#Quaternion_polar_decomposition
|
||||
@inlinable
|
||||
public init(length: RealType, halfAngle: RealType, axis: SIMD3<RealType>) {
|
||||
guard !length.isZero, length.isFinite else {
|
||||
self = Quaternion(length)
|
||||
return
|
||||
}
|
||||
|
||||
// Length is finite and non-zero, therefore
|
||||
// 1. `halfAngle` must be finite or a precondition failure needs to occur;
|
||||
// as this is not representable.
|
||||
// 2. `axis` must be of unit length or an assertion failure occurs; while
|
||||
// "wrong" by definition, it is representable.
|
||||
precondition(
|
||||
halfAngle.isFinite,
|
||||
"Either halfAngle must be finite, or length must be zero or infinite."
|
||||
)
|
||||
assert(
|
||||
// TODO: Replace with `approximateEquality()`
|
||||
abs(.sqrt(axis.lengthSquared)-1) < max(.sqrt(axis.lengthSquared), 1)*RealType.ulpOfOne.squareRoot(),
|
||||
"Given axis must be of unit length."
|
||||
)
|
||||
|
||||
self = Quaternion(
|
||||
halfAngle: halfAngle,
|
||||
unitAxis: axis
|
||||
).multiplied(by: length)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//===--- Quaternion+AdditiveArithmetic.swift ------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2022 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 Quaternion: AdditiveArithmetic {
|
||||
/// The additive identity, with real and *all* imaginary parts zero, i.e.:
|
||||
/// `0 + 0i + 0j + 0k`
|
||||
///
|
||||
/// See also: `one`, `i`, `j`, `k`, `infinity`
|
||||
@_transparent
|
||||
public static var zero: Quaternion {
|
||||
Quaternion(from: SIMD4(repeating: 0))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func + (lhs: Quaternion, rhs: Quaternion) -> Quaternion {
|
||||
Quaternion(from: lhs.components + rhs.components)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func - (lhs: Quaternion, rhs: Quaternion) -> Quaternion {
|
||||
Quaternion(from: lhs.components - rhs.components)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func += (lhs: inout Quaternion, rhs: Quaternion) {
|
||||
lhs = lhs + rhs
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func -= (lhs: inout Quaternion, rhs: Quaternion) {
|
||||
lhs = lhs - rhs
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
//===--- Quaternion+Codable.swift -----------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2022 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 Quaternion: Decodable where RealType: Decodable {
|
||||
public init(from decoder: Decoder) throws {
|
||||
try self.init(from: SIMD4(from: decoder))
|
||||
}
|
||||
}
|
||||
|
||||
extension Quaternion: Encodable where RealType: Encodable {
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
try components.encode(to: encoder)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
//===--- Quaternion+ElementaryFunctions.swift -----------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2022 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// (r + xi + yj + zk) is a common representation that is often seen for
|
||||
// quaternions. However, when we want to expand the elementary functions of
|
||||
// quaternions in terms of real operations it is almost always easier to view
|
||||
// them as real part (r) and imaginary vector part (v),
|
||||
// i.e: r + xi + yj + zk = r + v; and so we diverge a little from the
|
||||
// representation that is used in the documentation in other files and use this
|
||||
// notation of quaternions in the comments of the following functions.
|
||||
//
|
||||
// Quaternionic elementary functions have many similarities with elementary
|
||||
// functions of complex numbers and their definition in terms of real
|
||||
// operations. Therefore, if you make a modification to one of the following
|
||||
// functions, you should almost surely make a parallel modification to the same
|
||||
// elementary function of complex numbers.
|
||||
|
||||
import RealModule
|
||||
|
||||
extension Quaternion/*: ElementaryFunctions */ {
|
||||
|
||||
// MARK: - exp-like functions
|
||||
@inlinable
|
||||
public static func exp(_ q: Quaternion) -> Quaternion {
|
||||
// Mathematically, this operation can be expanded in terms of the `Real`
|
||||
// operations `exp`, `cos` and `sin` as follows (`let θ = ||v||`):
|
||||
//
|
||||
// ```
|
||||
// exp(r + v) = exp(r) exp(v)
|
||||
// = exp(r) (cos(θ) + (v/θ) sin(θ))
|
||||
// ```
|
||||
//
|
||||
// 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(r)` may be infinity when
|
||||
// `exp(r) cos(||v||)` would not be.
|
||||
guard q.isFinite else { return q }
|
||||
let (â, θ) = q.imaginary.unitAxisAndLength
|
||||
let rotation = Quaternion(halfAngle: θ, unitAxis: â)
|
||||
// If real < log(greatestFiniteMagnitude), then exp(real) 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 q.real < RealType.log(.greatestFiniteMagnitude) - 1 else {
|
||||
let halfScale = RealType.exp(q.real/2)
|
||||
return rotation.multiplied(by: halfScale).multiplied(by: halfScale)
|
||||
}
|
||||
return rotation.multiplied(by: .exp(q.real))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func expMinusOne(_ q: Quaternion) -> Quaternion {
|
||||
// Mathematically, this operation can be expanded in terms of the `Real`
|
||||
// operations `exp`, `cos` and `sin` as follows (`let θ = ||v||`):
|
||||
//
|
||||
// ```
|
||||
// exp(r + v) - 1 = exp(r) exp(v) - 1
|
||||
// = exp(r) (cos(θ) + (v/θ) sin(θ)) - 1
|
||||
// = exp(r) cos(θ) + exp(r) (v/θ) sin(θ) - 1
|
||||
// = (exp(r) cos(θ) - 1) + exp(r) (v/θ) sin(θ)
|
||||
// -------- 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(r) cos(θ) - 1
|
||||
// = exp(r) cos(θ) - cos(θ) + cos(θ) - 1
|
||||
// = (exp(r) - 1) cos(θ) + (cos(θ) - 1)
|
||||
// = expMinusOne(r) cos(θ) + cosMinusOne(θ)
|
||||
// ```
|
||||
//
|
||||
// See `expMinusOne` on complex numbers for error bounds.
|
||||
guard q.isFinite else { return q }
|
||||
let (â, θ) = q.imaginary.unitAxisAndLength
|
||||
// If exp(q) is close to the overflow boundary, we don't need to
|
||||
// worry about the "MinusOne" part of this function; we're just
|
||||
// computing exp(q). (Even when θ is near a multiple of π/2,
|
||||
// it can't be close enough to overcome the scaling from exp(r),
|
||||
// so the -1 term is _always_ negligable).
|
||||
guard q.real < RealType.log(.greatestFiniteMagnitude) - 1 else {
|
||||
let halfScale = RealType.exp(q.real/2)
|
||||
let rotation = Quaternion(halfAngle: θ, unitAxis: â)
|
||||
return rotation.multiplied(by: halfScale).multiplied(by: halfScale)
|
||||
}
|
||||
return Quaternion(
|
||||
real: RealType._mulAdd(.cos(θ), .expMinusOne(q.real), .cosMinusOne(θ)),
|
||||
imaginary: â * .exp(q.real) * .sin(θ)
|
||||
)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func cosh(_ q: Quaternion) -> Quaternion {
|
||||
// Mathematically, this operation can be expanded in terms of
|
||||
// trigonometric `Real` operations as follows (`let θ = ||v||`):
|
||||
//
|
||||
// ```
|
||||
// cosh(q) = (exp(q) + exp(-q)) / 2
|
||||
// = cosh(r) cos(θ) + (v/θ) sinh(r) sin(θ)
|
||||
// ```
|
||||
//
|
||||
// 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 |r| >= -log(ulpOfOne), cosh(r) and sinh(r) are
|
||||
// both just exp(|r|)/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.
|
||||
guard q.isFinite else { return q }
|
||||
let (â, θ) = q.imaginary.unitAxisAndLength
|
||||
guard q.real.magnitude < -RealType.log(.ulpOfOne) else {
|
||||
let rotation = Quaternion(halfAngle: θ, unitAxis: â)
|
||||
let firstScale = RealType.exp(q.real.magnitude/2)
|
||||
return rotation.multiplied(by: firstScale).multiplied(by: firstScale/2)
|
||||
}
|
||||
return Quaternion(
|
||||
real: .cosh(q.real) * .cos(θ),
|
||||
imaginary: â * .sinh(q.real) * .sin(θ)
|
||||
)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func sinh(_ q: Quaternion) -> Quaternion {
|
||||
// Mathematically, this operation can be expanded in terms of
|
||||
// trigonometric `Real` operations as follows (`let θ = ||v||`):
|
||||
//
|
||||
// ```
|
||||
// sinh(q) = (exp(q) - exp(-q)) / 2
|
||||
// = sinh(r) cos(θ) + (v/θ) cosh(r) sin(θ)
|
||||
// ```
|
||||
guard q.isFinite else { return q }
|
||||
let (â, θ) = q.imaginary.unitAxisAndLength
|
||||
guard q.real.magnitude < -RealType.log(.ulpOfOne) else {
|
||||
let rotation = Quaternion(halfAngle: θ, unitAxis: â)
|
||||
let firstScale = RealType.exp(q.real.magnitude/2)
|
||||
let secondScale = RealType(signOf: q.real, magnitudeOf: firstScale/2)
|
||||
return rotation.multiplied(by: firstScale).multiplied(by: secondScale)
|
||||
}
|
||||
return Quaternion(
|
||||
real: .sinh(q.real) * .cos(θ),
|
||||
imaginary: â * .cosh(q.real) * .sin(θ)
|
||||
)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func tanh(_ q: Quaternion) -> Quaternion {
|
||||
// Mathematically, this operation can be expanded in terms of
|
||||
// trigonometric `Real` operations as follows (`let θ = ||v||`):
|
||||
//
|
||||
// ```
|
||||
// tanh(q) = sinh(q) / cosh(q)
|
||||
// ```
|
||||
guard q.isFinite else { return q }
|
||||
// Note that when |r| is larger than -log(.ulpOfOne),
|
||||
// sinh(r + v) == ±cosh(r + v), so tanh(r + v) is just ±1.
|
||||
guard q.real.magnitude < -RealType.log(.ulpOfOne) else {
|
||||
return Quaternion(
|
||||
real: RealType(signOf: q.real, magnitudeOf: 1),
|
||||
imaginary:
|
||||
RealType(signOf: q.components.x, magnitudeOf: 0),
|
||||
RealType(signOf: q.components.y, magnitudeOf: 0),
|
||||
RealType(signOf: q.components.z, magnitudeOf: 0)
|
||||
)
|
||||
}
|
||||
return sinh(q) / cosh(q)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func cos(_ q: Quaternion) -> Quaternion {
|
||||
// cos(q) = cosh(q * (v/θ)))
|
||||
let (â,_) = q.imaginary.unitAxisAndLength
|
||||
let p = Quaternion(imaginary: â)
|
||||
return cosh(q * p)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func sin(_ q: Quaternion) -> Quaternion {
|
||||
// sin(q) = -(v/θ) * sinh(q * (v/θ)))
|
||||
let (â,_) = q.imaginary.unitAxisAndLength
|
||||
let p = Quaternion(imaginary: â)
|
||||
return -p * sinh(q * p)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func tan(_ q: Quaternion) -> Quaternion {
|
||||
// tan(q) = -(v/θ) * tanh(q * (v/θ)))
|
||||
let (â,_) = q.imaginary.unitAxisAndLength
|
||||
let p = Quaternion(imaginary: â)
|
||||
return -p * tanh(q * p)
|
||||
}
|
||||
}
|
||||
|
||||
extension SIMD3 where Scalar: FloatingPoint {
|
||||
|
||||
/// Returns the normalized axis and the length of this vector.
|
||||
@usableFromInline @inline(__always)
|
||||
internal var unitAxisAndLength: (Self, Scalar) {
|
||||
if self == .zero {
|
||||
return (SIMD3(
|
||||
Scalar(signOf: x, magnitudeOf: 0),
|
||||
Scalar(signOf: y, magnitudeOf: 0),
|
||||
Scalar(signOf: z, magnitudeOf: 0)
|
||||
), .zero)
|
||||
}
|
||||
return (self/length, length)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//===--- Quaternion+Hashable.swift ----------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2022 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 Quaternion: Hashable {
|
||||
/// Returns a Boolean value indicating whether two values are equal.
|
||||
///
|
||||
/// - Important:
|
||||
/// Quaternions are frequently used to represent 3D transformations. It's
|
||||
/// important to be aware that, when used this way, any quaternion and its
|
||||
/// negation represent the same transformation, but they do not compare
|
||||
/// equal using `==` because they are not the same quaternion. You can
|
||||
/// compare quaternions as 3D transformations using `equals(as3DTransform:)`.
|
||||
@_transparent
|
||||
public static func == (lhs: Quaternion, rhs: Quaternion) -> Bool {
|
||||
// Identify all numbers with either component non-finite as a single "point at infinity".
|
||||
guard lhs.isFinite || rhs.isFinite else { return true }
|
||||
// For finite numbers, equality is defined componentwise. Cases where
|
||||
// only one of lhs or rhs 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 lhs.components == rhs.components
|
||||
}
|
||||
|
||||
/// Returns a Boolean value indicating whether the 3D transformation of the
|
||||
/// two quaternions are equal.
|
||||
///
|
||||
/// Use this method to test for equality of the 3D transformation properties
|
||||
/// of quaternions; where for any quaternion `q`, its negation represent the
|
||||
/// same 3D transformation; i.e. `q.equals(as3DTransform: q)` as well as
|
||||
/// `q.equals(as3DTransform: -q)` are both `true`.
|
||||
///
|
||||
/// - Parameter other: The value to compare.
|
||||
/// - Returns: True if the 3D transformation of this quaternion equals `other`.
|
||||
@_transparent
|
||||
public func equals(as3DTransform other: Quaternion) -> Bool {
|
||||
// Identify all numbers with either component non-finite as a single "point at infinity".
|
||||
guard isFinite || other.isFinite else { return true }
|
||||
// For finite numbers, equality is defined componentwise. Cases where only
|
||||
// one of lhs or rhs 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 components == other.components || components == -other.components
|
||||
}
|
||||
|
||||
@_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.
|
||||
// For any normal values we use the "canonical transform" representation,
|
||||
// where real is always non-negative. This allows people who are using
|
||||
// quaternions as rotations to get the expected semantics out of collections
|
||||
// (while unfortunately producing some collisions for people who are not,
|
||||
// but not in too catastrophic of a fashion).
|
||||
if isFinite {
|
||||
canonicalizedTransform.components.hash(into: &hasher)
|
||||
} else {
|
||||
hasher.combine(RealType.infinity)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//===--- Quaternion+IntegerLiteral.swift ----------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2022 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 Quaternion: ExpressibleByIntegerLiteral {
|
||||
public typealias IntegerLiteralType = RealType.IntegerLiteralType
|
||||
|
||||
@inlinable
|
||||
public init(integerLiteral value: IntegerLiteralType) {
|
||||
self.init(RealType(integerLiteral: value))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//===--- Quaternion+Numeric.swift -----------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2022 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 Quaternion: Numeric {
|
||||
@_transparent
|
||||
public static func * (lhs: Quaternion, rhs: Quaternion) -> Quaternion {
|
||||
|
||||
let rhsX = SIMD4(+rhs.components.w, +rhs.components.z, -rhs.components.y, +rhs.components.x)
|
||||
let rhsY = SIMD4(-rhs.components.z, +rhs.components.w, +rhs.components.x, +rhs.components.y)
|
||||
let rhsZ = SIMD4(+rhs.components.y, -rhs.components.x, +rhs.components.w, +rhs.components.z)
|
||||
let rhsR = SIMD4(-rhs.components.x, -rhs.components.y, -rhs.components.z, +rhs.components.w)
|
||||
|
||||
let x = (lhs.components * rhsX).sum()
|
||||
let y = (lhs.components * rhsY).sum()
|
||||
let z = (lhs.components * rhsZ).sum()
|
||||
let r = (lhs.components * rhsR).sum()
|
||||
|
||||
return Quaternion(from: SIMD4(x,y,z,r))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func *= (lhs: inout Quaternion, rhs: Quaternion) {
|
||||
lhs = lhs * rhs
|
||||
}
|
||||
|
||||
/// The quaternion with specified real part and zero imaginary part.
|
||||
///
|
||||
/// Equivalent to `Quaternion(RealType(real))`.
|
||||
@inlinable
|
||||
public init<Other: BinaryInteger>(_ real: Other) {
|
||||
self.init(RealType(real))
|
||||
}
|
||||
|
||||
/// The quaternion 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)
|
||||
}
|
||||
|
||||
/// The ∞-norm of the value (`max(abs(r), abs(x), abs(y), abs(z))`).
|
||||
///
|
||||
/// If you need the Euclidean norm (a.k.a. 2-norm) use the `length` or `lengthSquared`
|
||||
/// properties instead.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// - If `q` is not finite, `q.magnitude` is `.infinity`.
|
||||
/// - If `q` is zero, `q.magnitude` is `0`.
|
||||
/// - Otherwise, `q.magnitude` is finite and non-zero.
|
||||
///
|
||||
/// See also `.length` and `.lengthSquared`
|
||||
@_transparent
|
||||
public var magnitude: RealType {
|
||||
guard isFinite else { return .infinity }
|
||||
return max(abs(components.max()), abs(components.min()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//===--- Quaternion+SignedNumeric.swift -----------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2022 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 Quaternion: SignedNumeric {
|
||||
/// The multiplicative identity, with real part one and *all* imaginary parts
|
||||
/// zero, i.e.: `1 + 0i + 0j + 0k`
|
||||
///
|
||||
/// See also: `zero`, `i`, `j`, `k`, `infinity`
|
||||
@_transparent
|
||||
public static var one: Quaternion {
|
||||
Quaternion(from: SIMD4(0,0,0,1))
|
||||
}
|
||||
|
||||
/// The [conjugate][conj] of this value.
|
||||
///
|
||||
/// [conj]: https://en.wikipedia.org/wiki/Quaternion#Conjugation,_the_norm,_and_reciprocal
|
||||
@_transparent
|
||||
public var conjugate: Quaternion {
|
||||
Quaternion(from: components * [-1, -1, -1, 1])
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func / (lhs: Quaternion, rhs: Quaternion) -> Quaternion {
|
||||
// Try the naive expression lhs/rhs = lhs*conj(rhs) / |rhs|^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 = rhs.lengthSquared
|
||||
guard lengthSquared.isNormal else { return rescaledDivide(lhs, rhs) }
|
||||
return lhs * (rhs.conjugate.divided(by: lengthSquared))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func /= (lhs: inout Quaternion, rhs: Quaternion) {
|
||||
lhs = lhs / rhs
|
||||
}
|
||||
|
||||
@usableFromInline @_alwaysEmitIntoClient @inline(never)
|
||||
internal static func rescaledDivide(_ lhs: Quaternion, _ rhs: Quaternion) -> Quaternion {
|
||||
if rhs.isZero { return .infinity }
|
||||
if lhs.isZero || !rhs.isFinite { return .zero }
|
||||
// TODO: detect when RealType is Float and just promote to Double, then
|
||||
// use the naive algorithm.
|
||||
let lhsScale = lhs.magnitude
|
||||
let rhsScale = rhs.magnitude
|
||||
let lhsNorm = lhs.divided(by: lhsScale)
|
||||
let rhsNorm = rhs.divided(by: rhsScale)
|
||||
let r = (lhsNorm * rhsNorm.conjugate).divided(by: rhsNorm.lengthSquared)
|
||||
// At this point, the result is (r * lhsScale)/rhsScale 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
|
||||
// to avoid spurious overflow or underflow. There are three options
|
||||
// to choose from:
|
||||
//
|
||||
// - r * (lhsScale / rhsScale)
|
||||
// - (r * lhsScale) / rhsScale
|
||||
// - (r / rhsScale) * lhsScale
|
||||
//
|
||||
// The simplest case is when lhsScale / rhsScale is normal:
|
||||
if (lhsScale / rhsScale).isNormal {
|
||||
return r.multiplied(by: lhsScale / rhsScale)
|
||||
}
|
||||
// Otherwise, we need to compute either rNorm * lhsScale or rNorm / rhsScale
|
||||
// first. Choose the first if the first scaling behaves well, otherwise
|
||||
// choose the other one.
|
||||
if (r.magnitude * lhsScale).isNormal {
|
||||
return r.multiplied(by: lhsScale).divided(by: rhsScale)
|
||||
}
|
||||
return r.divided(by: rhsScale).multiplied(by: lhsScale)
|
||||
}
|
||||
|
||||
/// A normalized quaternion with the same direction and phase as this value.
|
||||
///
|
||||
/// If such a value cannot be produced, `nil` is returned.
|
||||
@inlinable
|
||||
public var normalized: Quaternion? {
|
||||
if length.isNormal {
|
||||
return divided(by: length)
|
||||
}
|
||||
if isZero || !isFinite {
|
||||
return nil
|
||||
}
|
||||
return divided(by: magnitude).normalized
|
||||
}
|
||||
|
||||
/// The reciprocal of this value, if it can be computed without undue overflow or underflow.
|
||||
///
|
||||
/// If z.reciprocal is non-nil, you can safely replace division by z with multiplication by this
|
||||
/// value. It is not advantageous to do this for an isolated division, but if you are dividing
|
||||
/// many values by a single denominator, this will often be a significant performance win.
|
||||
///
|
||||
/// Typical use looks like this:
|
||||
/// ```
|
||||
/// func divide<T: Real>(data: [Quaternion<T>], by divisor: Quaternion<T>) -> [Quaternion<T>] {
|
||||
/// // If divisor is well-scaled, use multiply by reciprocal.
|
||||
/// if let recip = divisor.reciprocal {
|
||||
/// return data.map { $0 * recip }
|
||||
/// }
|
||||
/// // Fallback on using division.
|
||||
/// return data.map { $0 / divisor }
|
||||
/// }
|
||||
/// ```
|
||||
@inlinable
|
||||
public var reciprocal: Quaternion? {
|
||||
let recip = Quaternion(1)/self
|
||||
if recip.isNormal || isZero || !isFinite {
|
||||
return recip
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
//===--- Quaternion+StringConvertible.swift -------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2022 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 Quaternion: CustomStringConvertible {
|
||||
public var description: String {
|
||||
guard isFinite else { return "inf" }
|
||||
return "(\(components.w), \(components.x), \(components.y), \(components.z))"
|
||||
}
|
||||
}
|
||||
|
||||
extension Quaternion: CustomDebugStringConvertible {
|
||||
public var debugDescription: String {
|
||||
let x = String(reflecting: components.x)
|
||||
let y = String(reflecting: components.y)
|
||||
let z = String(reflecting: components.z)
|
||||
let r = String(reflecting: components.w)
|
||||
return "Quaternion<\(RealType.self)>(\(r), \(x), \(y), \(z))"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
//===--- Quaternion.swift -------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2022 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 quaternion represented by a real (or scalar) part and three imaginary (or vector) parts.
|
||||
///
|
||||
/// TODO: introductory text on quaternions
|
||||
///
|
||||
/// Implementation notes:
|
||||
/// -
|
||||
/// This type does not provide heterogeneous real/quaternion arithmetic,
|
||||
/// not even the natural vector-space operations like real * quaternion.
|
||||
/// 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).
|
||||
///
|
||||
/// `.magnitude` does not return the Euclidean norm; it uses the "infinity
|
||||
/// norm" (`max(|r|,|x|,|y|,|z|)`) 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.
|
||||
/// Using the infinity norm avoids this problem entirely without significant
|
||||
/// downsides. You can access the Euclidean norm using the `length` property.
|
||||
/// See `Complex` type of the swift-numerics package for additional details.
|
||||
///
|
||||
/// Quaternions are frequently used to represent 3D transformations. It's
|
||||
/// important to be aware that, when used this way, any quaternion and its
|
||||
/// negation represent the same transformation, but they do not compare equal
|
||||
/// using `==` because they are not the same quaternion.
|
||||
/// You can compare quaternions as 3D transformations using `equals(as3DTransform:)`.
|
||||
public struct Quaternion<RealType> where RealType: Real & SIMDScalar {
|
||||
|
||||
/// The components of the 4-dimensional vector space of the quaternion.
|
||||
///
|
||||
/// Components are stored within a 4-dimensional SIMD vector with the
|
||||
/// scalar part last, i.e. in the form of:
|
||||
///
|
||||
/// xi + yj + zk + r // SIMD(x,y,z,r)
|
||||
@usableFromInline @inline(__always)
|
||||
internal var components: SIMD4<RealType>
|
||||
|
||||
/// A quaternion constructed from given 4-dimensional SIMD vector.
|
||||
///
|
||||
/// Creates a new quaternion by reading the values of the SIMD vector
|
||||
/// as components of a quaternion with the scalar part last, i.e. in the form of:
|
||||
///
|
||||
/// xi + yj + zk + r // SIMD(x,y,z,r)
|
||||
@usableFromInline @inline(__always)
|
||||
internal init(from components: SIMD4<RealType>) {
|
||||
self.components = components
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Basic Property
|
||||
extension Quaternion {
|
||||
/// The real part of this quaternion.
|
||||
///
|
||||
/// If `q` is not finite, `q.real` is `.nan`.
|
||||
public var real: RealType {
|
||||
@_transparent
|
||||
get { isFinite ? components[3] : .nan }
|
||||
|
||||
@_transparent
|
||||
set { components[3] = newValue }
|
||||
}
|
||||
|
||||
/// The imaginary part of this quaternion.
|
||||
///
|
||||
/// If `q` is not finite, `q.imaginary` is `.nan` in all lanes.
|
||||
public var imaginary: SIMD3<RealType> {
|
||||
@_transparent
|
||||
get { isFinite ? components[SIMD3(0,1,2)] : SIMD3(repeating: .nan) }
|
||||
|
||||
@_transparent
|
||||
set {
|
||||
components = SIMD4(newValue, components[3])
|
||||
}
|
||||
}
|
||||
|
||||
/// The quaternion with the imaginary unit **i** one, i.e. `0 + i + 0j + 0k`.
|
||||
///
|
||||
/// See also `.zero`, `.one`, `.j`, `.k` and `.infinity`.
|
||||
@_transparent
|
||||
public static var i: Quaternion {
|
||||
Quaternion(imaginary: SIMD3(1,0,0))
|
||||
}
|
||||
|
||||
/// The quaternion with the imaginary unit **j** one, i.e. `0 + 0i + j + 0k`.
|
||||
///
|
||||
/// See also `.zero`, `.one`, `.i`, `.k` and `.infinity`.
|
||||
@_transparent
|
||||
public static var j: Quaternion {
|
||||
Quaternion(imaginary: SIMD3(0,1,0))
|
||||
}
|
||||
|
||||
/// The quaternion with the imaginary unit **k** one, i.e. `0 + 0i + 0j + k`.
|
||||
///
|
||||
/// See also `.zero`, `.one`, `.i`, `.j` and `.infinity`.
|
||||
@_transparent
|
||||
public static var k: Quaternion {
|
||||
Quaternion(imaginary: SIMD3(0,0,1))
|
||||
}
|
||||
|
||||
/// The point at infinity.
|
||||
///
|
||||
/// See also `.zero`, `.one`, `.i`, `.j` and `.k`.
|
||||
@_transparent
|
||||
public static var infinity: Quaternion {
|
||||
Quaternion(.infinity)
|
||||
}
|
||||
|
||||
/// True if this value is finite.
|
||||
///
|
||||
/// A quaternion is finite if neither component is an infinity or nan.
|
||||
///
|
||||
/// See also `.isNormal`, `.isSubnormal`, `.isZero`, `.isReal`, `.isPure`.
|
||||
@_transparent
|
||||
public var isFinite: Bool {
|
||||
return components.x.isFinite
|
||||
&& components.y.isFinite
|
||||
&& components.z.isFinite
|
||||
&& components.w.isFinite
|
||||
}
|
||||
|
||||
/// True if this value is normal.
|
||||
///
|
||||
/// A quaternion is normal if it is finite and *any* of its real or imaginary components
|
||||
/// are 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`, `.isReal`, `.isPure`.
|
||||
@_transparent
|
||||
public var isNormal: Bool {
|
||||
return isFinite && (
|
||||
components.x.isNormal ||
|
||||
components.y.isNormal ||
|
||||
components.z.isNormal ||
|
||||
components.w.isNormal
|
||||
)
|
||||
}
|
||||
|
||||
/// True if this value is subnormal.
|
||||
///
|
||||
/// A quaternion 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`, `.isReal`, `.isPure`.
|
||||
@_transparent
|
||||
public var isSubnormal: Bool {
|
||||
isFinite && !isNormal && !isZero
|
||||
}
|
||||
|
||||
/// True if this value is zero.
|
||||
///
|
||||
/// A quaternion is zero if the real and *all* imaginary components are zero.
|
||||
///
|
||||
/// See also `.isFinite`, `.isNormal`, `.isSubnormal`, `.isReal`, `.isPure`.
|
||||
@_transparent
|
||||
public var isZero: Bool {
|
||||
components == .zero
|
||||
}
|
||||
|
||||
/// True if this quaternion is real.
|
||||
///
|
||||
/// A quaternion is real if *all* imaginary components are zero.
|
||||
///
|
||||
/// See also `.isFinite`, `.isNormal`, `.isSubnormal`, `.isZero`, `.isPure`.
|
||||
@_transparent
|
||||
public var isReal: Bool {
|
||||
imaginary == .zero
|
||||
}
|
||||
|
||||
/// True if this quaternion is pure.
|
||||
///
|
||||
/// A quaternion is pure if the real component is zero.
|
||||
///
|
||||
/// See also `.isFinite`, `.isNormal`, `.isSubnormal`, `.isZero`, `.isReal`.
|
||||
@_transparent
|
||||
public var isPure: Bool {
|
||||
real.isZero
|
||||
}
|
||||
|
||||
/// A "canonical" representation of the value.
|
||||
///
|
||||
/// For normal quaternion instances 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, +0, +0).
|
||||
/// For infinite values, the result has the representation (+inf, +0, +0, +0).
|
||||
///
|
||||
/// If the RealType admits non-canonical representations, the x, y, z and r
|
||||
/// 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.
|
||||
///
|
||||
/// See also `.canonicalizedTransform`.
|
||||
@_transparent
|
||||
public var canonicalized: Self {
|
||||
guard !isZero else { return .zero }
|
||||
guard isFinite else { return .infinity }
|
||||
return self.multiplied(by: 1)
|
||||
}
|
||||
|
||||
/// A "canonical transformation" representation of the value.
|
||||
///
|
||||
/// For normal quaternion instances with a RealType conforming to
|
||||
/// BinaryFloatingPoint (the common case) and a non-negative real component,
|
||||
/// the result is simply this value unmodified. For instances with a negative
|
||||
/// real component, the result is this quaternion negated -(r, x, y, z); so
|
||||
/// the real component is always positive.
|
||||
/// For zeros, the result has the representation (+0, +0, +0, +0). For
|
||||
/// infinite values, the result has the representation (+inf, +0, +0, +0).
|
||||
///
|
||||
/// If the RealType admits non-canonical representations, the x, y, z and r
|
||||
/// components are canonicalized in the result.
|
||||
///
|
||||
/// See also `.canonicalized`.
|
||||
@_transparent
|
||||
public var canonicalizedTransform: Self {
|
||||
let canonical = canonicalized
|
||||
if canonical.real.sign == .plus { return canonical }
|
||||
return -canonical
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Additional Initializers
|
||||
extension Quaternion {
|
||||
/// The quaternion with specified real part and zero imaginary part.
|
||||
///
|
||||
/// Equivalent to `Quaternion(real: real, imaginary: SIMD3(repeating: 0))`.
|
||||
@inlinable
|
||||
public init(_ real: RealType) {
|
||||
self.init(real: real, imaginary: SIMD3(repeating: 0))
|
||||
}
|
||||
|
||||
/// The quaternion with specified imaginary part and zero real part.
|
||||
///
|
||||
/// Equivalent to `Quaternion(real: 0, imaginary: imaginary)`.
|
||||
@inlinable
|
||||
public init(imaginary: SIMD3<RealType>) {
|
||||
self.init(real: 0, imaginary: imaginary)
|
||||
}
|
||||
|
||||
/// The quaternion with specified imaginary part and zero real part.
|
||||
///
|
||||
/// Equivalent to `Quaternion(real: 0, imaginary: imaginary)`.
|
||||
@inlinable
|
||||
public init(imaginary x: RealType, _ y: RealType, _ z: RealType) {
|
||||
self.init(imaginary: SIMD3(x, y, z))
|
||||
}
|
||||
|
||||
/// The quaternion with specified real part and imaginary parts.
|
||||
@inlinable
|
||||
public init(real: RealType, imaginary: SIMD3<RealType>) {
|
||||
self.init(from: SIMD4(imaginary, real))
|
||||
}
|
||||
|
||||
/// The quaternion with specified real part and imaginary parts.
|
||||
@inlinable
|
||||
public init(real: RealType, imaginary x: RealType, _ y: RealType, _ z: RealType) {
|
||||
self.init(real: real, imaginary: SIMD3(x, y, z))
|
||||
}
|
||||
}
|
||||
|
||||
extension Quaternion where RealType: BinaryFloatingPoint {
|
||||
/// `other` rounded to the nearest representable value of this type.
|
||||
@inlinable
|
||||
public init<Other: BinaryFloatingPoint>(_ other: Quaternion<Other>) {
|
||||
self.init(from: SIMD4(
|
||||
RealType(other.components.x),
|
||||
RealType(other.components.y),
|
||||
RealType(other.components.z),
|
||||
RealType(other.components.w)
|
||||
))
|
||||
}
|
||||
|
||||
/// `other`, if it can be represented exactly in this type; otherwise `nil`.
|
||||
@inlinable
|
||||
public init?<Other: BinaryFloatingPoint>(exactly other: Quaternion<Other>) {
|
||||
guard
|
||||
let x = RealType(exactly: other.components.x),
|
||||
let y = RealType(exactly: other.components.y),
|
||||
let z = RealType(exactly: other.components.z),
|
||||
let r = RealType(exactly: other.components.w)
|
||||
else { return nil }
|
||||
self.init(from: SIMD4(x, y, z, r))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
# Quaternion
|
||||
|
||||
This module provides a `Quaternion` type generic over an underlying `RealType`:
|
||||
|
||||
```swift
|
||||
1> import QuaternionModule
|
||||
2> let q = Quaternion(real: 1, imaginary: 1, 1, 1) // q = 1 + i + j + k
|
||||
```
|
||||
|
||||
The usual arithmetic operators are provided for Quaternions, many useful properties, plus conformances to the
|
||||
obvious usual protocols: `Equatable`, `Hashable`, `Codable` (if the underlying `RealType` is), and `AlgebraicField`
|
||||
(hence also `AdditiveArithmetic` and `SignedNumeric`).
|
||||
|
||||
### Dependencies:
|
||||
- `RealModule`.
|
||||
|
||||
### The magnitude property
|
||||
The `Numeric` protocol requires a `.magnitude` property, but (deliberately) does not fully specify the semantics.
|
||||
The most obvious choice for `Quaternion` would be to use the Euclidean norm (aka the "2-norm", given by `sqrt(real*real + i*i + k*k + j*j)`).
|
||||
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 `q = Quaternion(big, (big, big, big))`, where `big` is `Double.greatestFiniteMagnitude`. The 1-norm and 2-norm of `q` both overflow (the 1-norm would be `4*big`, and the 2-norm would be `sqrt(4)*big`, neither of which are representable as `Double`), but the ∞-norm is always equal to either `real`, `i`, `j` or `k`, 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 `.lengthSquared` properties.
|
||||
@@ -0,0 +1,39 @@
|
||||
//===--- Scale.swift ------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2022 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*p; is
|
||||
// that Quaternion(2) * p or is it RealType(2) * p? 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 Quaternion type context, then b will be inferred to have type
|
||||
// Quaternion! 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 Quaternion {
|
||||
/// `self` scaled by `scalar`.
|
||||
@usableFromInline @_transparent
|
||||
internal func multiplied(by scalar: RealType) -> Quaternion {
|
||||
Quaternion(from: components * scalar)
|
||||
}
|
||||
|
||||
/// `self` unscaled by `scalar`.
|
||||
@usableFromInline @_transparent
|
||||
internal func divided(by scalar: RealType) -> Quaternion {
|
||||
Quaternion(from: components / scalar)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
# Transformation
|
||||
|
||||
In computer science, quaternions are frequently used to represent three-dimensional rotations; as quaternions have some [advantages over other representations][advantages].
|
||||
|
||||
`Transformation.swift` encapsulates an API to interact with the three-dimensional transformation properties of quaternions. It provides conversions to and from other rotation representations, namely [*Angle-Axis*][angle_axis_wiki], [*Rotation Vector*][rotation_vector_wiki] and [*Polar decomposition*][polar_wiki], as well as it provides methods to directly transform arbitrary vectors by quaternions.
|
||||
|
||||
## Policies
|
||||
|
||||
- zero and non-finite quaternions have indeterminate transformation properties and can not be converted to other representations. Thus,
|
||||
|
||||
- The `angle` of `.zero` or `.infinity` is `RealType.nan`.
|
||||
- The `axis` of `.zero` or `.infinity` is `RealType.nan` in all lanes.
|
||||
- The `rotationVector` of `.zero` or `.infinity` is `RealType.nan` in all lanes.
|
||||
- The polar `phase` of `.zero` or `.infinity` is `RealType.nan`
|
||||
|
||||
- Quaternions with an `angle` of `.zero` have an indeterminate rotation axis. Thus,
|
||||
|
||||
- the `axis` of `angle == .zero` is `RealType.nan` in all lanes.
|
||||
- the `rotationVector` of `angle == .zero` is `RealType.nan` in all lanes.
|
||||
|
||||
|
||||
[advantages]: https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Advantages_of_quaternions
|
||||
[angle_axis_wiki]: https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Recovering_the_axis-angle_representation
|
||||
[polar_wiki]: https://en.wikipedia.org/wiki/Polar_decomposition#Quaternion_polar_decomposition
|
||||
[rotation_vector_wiki]: https://en.wikipedia.org/wiki/Axis–angle_representation#Rotation_vector
|
||||
@@ -0,0 +1,271 @@
|
||||
//===--- Transformation.swift ---------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2020 - 2022 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 Quaternion {
|
||||
/// The [rotation angle][wiki] of the Angle-Axis representation.
|
||||
///
|
||||
/// Returns the rotation angle about the rotation *axis* in radians
|
||||
/// within *[0, 2π]* range.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// - If the quaternion is zero or non-finite, angle is `nan`.
|
||||
///
|
||||
/// See also `.axis`, `.angleAxis`, `.rotationVector`,
|
||||
/// `init(length:angle:axis:)` and `init(rotation:)`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Recovering_the_axis-angle_representation
|
||||
@inlinable
|
||||
public var angle: RealType {
|
||||
2 * halfAngle
|
||||
}
|
||||
|
||||
/// The [rotation axis][wiki] of the Angle-Axis representation.
|
||||
///
|
||||
/// Returns the *(x,y,z)* rotation axis encoded in the quaternion
|
||||
/// as SIMD3 vector of unit length.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// - If the quaternion is zero or non-finite, axis is `nan` in all lanes.
|
||||
/// - If the rotation angle is zero, axis is `nan` in all lanes.
|
||||
///
|
||||
/// See also `.angle`, `.angleAxis`, `.rotationVector`,
|
||||
/// `init(length:angle:axis:)` and `init(rotation:)`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Recovering_the_axis-angle_representation
|
||||
@inlinable
|
||||
public var axis: SIMD3<RealType> {
|
||||
guard isFinite, imaginary != .zero else { return SIMD3(repeating: .nan) }
|
||||
|
||||
// If lengthSquared computes without over/underflow, everything is fine
|
||||
// and the result is correct. If not, we have to do the computation
|
||||
// carefully and unscale the quaternion first.
|
||||
let lenSq = imaginary.lengthSquared
|
||||
guard lenSq.isNormal else { return divided(by: magnitude).axis }
|
||||
return imaginary / .sqrt(lenSq)
|
||||
}
|
||||
|
||||
/// The [Angle-Axis][wiki] representation.
|
||||
///
|
||||
/// Returns the length of the quaternion, the rotation angle in radians
|
||||
/// within *[0, 2π]* and the rotation axis as SIMD3 vector of unit length.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// - If the quaternion is zero or non-finite, angle and axis are `nan`.
|
||||
/// - If the angle is zero, axis is `nan` in all lanes.
|
||||
///
|
||||
/// See also `.angle`, `.axis`, `.rotationVector`, `init(length:angle:axis:)`
|
||||
/// and `init(rotation:)`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Recovering_the_axis-angle_representation
|
||||
public var angleAxis: (length: RealType, angle: RealType, axis: SIMD3<RealType>) {
|
||||
(length, angle, axis)
|
||||
}
|
||||
|
||||
/// The [rotation vector][rotvector].
|
||||
///
|
||||
/// A rotation vector is a vector of same direction as the rotation axis,
|
||||
/// whose length is the rotation angle of an Angle-Axis representation. It
|
||||
/// is effectively the product of multiplying the rotation `axis` by the
|
||||
/// rotation `angle`. Rotation vectors are often called "scaled axis" — this
|
||||
/// is a different name for the same concept.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// - If the quaternion is zero or non-finite, the rotation vector is `nan`
|
||||
/// in all lanes.
|
||||
/// - If the rotation angle is zero, the rotation vector is `nan`
|
||||
/// in all lanes.
|
||||
///
|
||||
/// See also `.angle`, `.axis`, `.angleAxis`, `init(length:angle:axis:)`
|
||||
/// and `init(rotation:)`.
|
||||
///
|
||||
/// [rotvector]: https://en.wikipedia.org/wiki/Axis–angle_representation#Rotation_vector
|
||||
@_transparent
|
||||
public var rotationVector: SIMD3<RealType> {
|
||||
axis * angle
|
||||
}
|
||||
|
||||
/// Creates a unit quaternion specified with [Angle-Axis][wiki] values.
|
||||
///
|
||||
/// Angle-Axis is a representation of a three-dimensional rotation using two
|
||||
/// different quantities: an angle describing the magnitude of rotation, and
|
||||
/// a vector of unit length indicating the axis direction to rotate along.
|
||||
/// The optional length parameter scales the quaternion after the conversion.
|
||||
///
|
||||
/// This initializer reads given `length`, `angle` and `axis` values and
|
||||
/// creates a quaternion of equal rotation properties and of specified length
|
||||
/// using the following equation:
|
||||
///
|
||||
/// Q = (cos(angle/2), axis * sin(angle/2)) * length
|
||||
///
|
||||
/// If `length` is not specified, it defaults to *1*; and the final
|
||||
/// quaternion is of unit length.
|
||||
///
|
||||
/// - Note: `axis` must be of unit length, or an assertion failure occurs.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// - Negative lengths are interpreted as reflecting the point through the origin, i.e.:
|
||||
/// ```
|
||||
/// Quaternion(length: -r, angle: θ, axis: axis) == -Quaternion(length: r, angle: θ, axis: axis)
|
||||
/// ```
|
||||
/// - For any `θ` and any `axis`, even `.infinity` or `.nan`:
|
||||
/// ```
|
||||
/// Quaternion(length: .zero, angle: θ, axis: axis) == .zero
|
||||
/// ```
|
||||
/// - For any `θ` and any `axis`, even `.infinity` or `.nan`:
|
||||
/// ```
|
||||
/// Quaternion(length: .infinity, angle: θ, axis: axis) == .infinity
|
||||
/// ```
|
||||
/// - Otherwise, `θ` must be finite, or a precondition failure occurs.
|
||||
///
|
||||
/// See also `.angle`, `.axis`, `.angleAxis`, `.rotationVector`
|
||||
/// and `init(rotation:)`.
|
||||
///
|
||||
/// - Parameter length: The length of the quaternion. Defaults to `1`.
|
||||
/// - Parameter angle: The rotation angle about the rotation axis in radians.
|
||||
/// - Parameter axis: The rotation axis. Must be of unit length.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Recovering_the_axis-angle_representation
|
||||
@inlinable
|
||||
public init(length: RealType = 1, angle: RealType, axis: SIMD3<RealType>) {
|
||||
guard !length.isZero, length.isFinite else {
|
||||
self = Quaternion(length)
|
||||
return
|
||||
}
|
||||
|
||||
// Length is finite and non-zero, therefore
|
||||
// 1. `angle` must be finite or a precondition failure needs to occur; as
|
||||
// this is not representable.
|
||||
// 2. `axis` must be of unit length or an assertion failure occurs; while
|
||||
// "wrong" by definition, it is representable.
|
||||
precondition(
|
||||
angle.isFinite,
|
||||
"Either angle must be finite, or length must be zero or infinite."
|
||||
)
|
||||
assert(
|
||||
// TODO: Replace with `approximateEquality()`
|
||||
abs(.sqrt(axis.lengthSquared)-1) < max(.sqrt(axis.lengthSquared), 1)*RealType.ulpOfOne.squareRoot(),
|
||||
"Given axis must be of unit length."
|
||||
)
|
||||
|
||||
self = Quaternion(halfAngle: angle/2, unitAxis: axis).multiplied(by: length)
|
||||
}
|
||||
|
||||
/// Creates a unit quaternion specified with given [rotation vector][wiki].
|
||||
///
|
||||
/// A rotation vector is a vector of same direction as the rotation axis,
|
||||
/// whose length is the rotation angle of an Angle-Axis representation. It
|
||||
/// is effectively the product of multiplying the rotation `axis` by the
|
||||
/// rotation `angle`.
|
||||
///
|
||||
/// This initializer reads the angle and axis values of given rotation vector
|
||||
/// and creates a quaternion of equal rotation properties using the following
|
||||
/// equation:
|
||||
///
|
||||
/// Q = (cos(angle/2), axis * sin(angle/2))
|
||||
///
|
||||
/// Rotation vectors are sometimes referred to as *scaled axis* — this is a
|
||||
/// different name for the same concept.
|
||||
///
|
||||
/// The final quaternion is of unit length.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// - If `vector` is `.zero`, the quaternion is `.zero`:
|
||||
/// ```
|
||||
/// Quaternion(rotation: .zero) == .zero
|
||||
/// ```
|
||||
/// - If `vector` is `.infinity` or `-.infinity`, the quaternion is `.infinity`:
|
||||
/// ```
|
||||
/// Quaternion(rotation: -.infinity) == .infinity
|
||||
/// ```
|
||||
///
|
||||
/// See also `.angle`, `.axis`, `.angleAxis`, `.rotationVector`
|
||||
/// and `init(length:angle:axis:)`.
|
||||
///
|
||||
/// - Parameter vector: The rotation vector.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Axis–angle_representation#Rotation_vector
|
||||
@inlinable
|
||||
public init(rotation vector: SIMD3<RealType>) {
|
||||
let angle: RealType = .sqrt(vector.lengthSquared)
|
||||
if !angle.isZero, angle.isFinite {
|
||||
self = Quaternion(halfAngle: angle/2, unitAxis: vector/angle)
|
||||
} else {
|
||||
self = Quaternion(angle)
|
||||
}
|
||||
}
|
||||
|
||||
/// Transforms a vector by this quaternion.
|
||||
///
|
||||
/// Quaternions are frequently used to represent three-dimensional
|
||||
/// transformations, and thus are used to transform vectors in
|
||||
/// three-dimensional space. The transformation of an arbitrary vector
|
||||
/// by a quaternion is known as an action.
|
||||
///
|
||||
/// The canonical way of transforming an arbitrary three-dimensional vector
|
||||
/// `v` by a quaternion `q` is given by the following [formula][wiki]
|
||||
///
|
||||
/// p' = qpq⁻¹
|
||||
///
|
||||
/// where `p` is a *pure* quaternion (`real == .zero`) with imaginary part
|
||||
/// equal to vector `v`, and where `p'` is another pure quaternion with
|
||||
/// imaginary part equal to the transformed vector `v'`. The implementation
|
||||
/// uses this formular but boils down to a simpler and faster implementation
|
||||
/// as `p` is known to be pure and `q` is assumed to have unit length – which
|
||||
/// allows for simplification.
|
||||
///
|
||||
/// - Note: This method assumes this quaternion is of unit length.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// - For any quaternion `q`, even `.zero` or `.infinity`, if `vector` is
|
||||
/// `.infinity` or `-.infinity` in any of the lanes or all, the returning
|
||||
/// vector is `.infinity` in all lanes:
|
||||
/// ```
|
||||
/// SIMD3(-.infinity,0,0) * q == SIMD3(.infinity,.infinity,.infinity)
|
||||
/// ```
|
||||
/// - For any quaternion `q`, even `.zero` or `.infinity`, if `vector` is
|
||||
/// `.zero`, the returning vector is also `.zero`.
|
||||
/// ```
|
||||
/// SIMD3(0,0,0) * q == .zero
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter vector: A vector to rotate by this quaternion
|
||||
/// - Returns: The vector rotated by this quaternion
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Using_quaternion_as_rotations
|
||||
@inlinable
|
||||
public func act(on vector: SIMD3<RealType>) -> SIMD3<RealType> {
|
||||
guard vector.isFinite else { return .infinity }
|
||||
guard vector != .zero else { return .zero }
|
||||
|
||||
// The following expression have been split up so the type-checker
|
||||
// can resolve them in a reasonable time.
|
||||
let p1 = vector * (real*real - imaginary.lengthSquared)
|
||||
let p2 = imaginary * imaginary.dot(vector)
|
||||
let p3 = imaginary.cross(vector) * real
|
||||
let rotatedVector = p1 + (p2 + p3) * 2
|
||||
|
||||
// If the rotation computes without over/underflow, everything is fine
|
||||
// and the result is correct. If not, we have to do the computation
|
||||
// carefully and first unscale the vector, rotate it again and then
|
||||
// rescale the vector
|
||||
if
|
||||
(rotatedVector.x.isNormal || rotatedVector.x.isZero) &&
|
||||
(rotatedVector.y.isNormal || rotatedVector.y.isZero) &&
|
||||
(rotatedVector.z.isNormal || rotatedVector.z.isZero)
|
||||
{
|
||||
return rotatedVector
|
||||
}
|
||||
let scale = max(abs(vector.max()), abs(vector.min()))
|
||||
return act(on: vector/scale) * scale
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
//===--- Real.swift -------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A type that models the real numbers.
|
||||
///
|
||||
/// Types conforming to this protocol provide the arithmetic and utility operations defined by
|
||||
/// the `FloatingPoint` protocol, and provide all of the math functions defined by the
|
||||
/// `ElementaryFunctions` and `RealFunctions` protocols. This protocol does not
|
||||
/// add any additional conformances itself, but is very useful as a protocol against which to
|
||||
/// write generic code. For example, we can naturally write a generic version of the a sigmoid
|
||||
/// function:
|
||||
/// ```
|
||||
/// func sigmoid<T: Real>(_ x: T) -> T {
|
||||
/// return 1/(1 + .exp(-x))
|
||||
/// }
|
||||
/// ```
|
||||
/// See Also:
|
||||
/// -
|
||||
/// - `ElementaryFunctions`
|
||||
/// - `RealFunctions`
|
||||
public protocol Real: FloatingPoint, RealFunctions {
|
||||
}
|
||||
|
||||
// While `Real` does not provide any additional customization points,
|
||||
// it does allow us to default the implementation of a few operations,
|
||||
// and also provides `signGamma`.
|
||||
extension Real {
|
||||
// Most math libraries do not provide exp10, so we need a default implementation.
|
||||
@_transparent
|
||||
public static func exp10(_ x: Self) -> Self {
|
||||
return pow(10, x)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
public static func signGamma(_ x: Self) -> FloatingPointSign {
|
||||
// Gamma is strictly positive for x >= 0.
|
||||
if x >= 0 { return .plus }
|
||||
// For negative x, we arbitrarily choose to assign a sign of .plus to the
|
||||
// poles.
|
||||
let trunc = x.rounded(.towardZero)
|
||||
if x == trunc { return .plus }
|
||||
// Otherwise, signGamma is .minus if the integral part of x is even.
|
||||
return trunc.isEven ? .minus : .plus
|
||||
}
|
||||
|
||||
// Determines if this value is even, assuming that it is an integer.
|
||||
@inline(__always)
|
||||
private var isEven: Bool {
|
||||
if Self.radix == 2 {
|
||||
// For binary types, we can just check if x/2 is an integer. This works
|
||||
// because x/2 is always computed exactly.
|
||||
let half = self/2
|
||||
return half == half.rounded(.towardZero)
|
||||
} else {
|
||||
// For decimal types, it's not quite that simple, because x/2 is not
|
||||
// necessarily computed exactly. As an example, suppose that we had a
|
||||
// decimal type with a one digit significand, and self = 7. Then self/2
|
||||
// would round to 4, and we would (wrongly) conclude that it was an
|
||||
// integer, and hence that self was even.
|
||||
//
|
||||
// Instead, for decimal types, we check if 2*trunc(self/2) == self,
|
||||
// using an FMA; this is always correct; this approach works for any
|
||||
// radix, but the previous method is more efficient for radix == 2.
|
||||
let half = self/2
|
||||
return self.addingProduct(-2, half.rounded(.towardZero)) == 0
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@_transparent
|
||||
public static func sqrt(_ x: Self) -> Self {
|
||||
return x.squareRoot()
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
//===--- RealFunctions.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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
public protocol RealFunctions: ElementaryFunctions {
|
||||
/// `atan(y/x)`, with sign selected according to the quadrant of `(x, y)`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `atan()`
|
||||
static func atan2(y: Self, x: Self) -> Self
|
||||
|
||||
/// The error function evaluated at `x`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `erfc()`
|
||||
static func erf(_ x: Self) -> Self
|
||||
|
||||
/// The complimentary error function evaluated at `x`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `erf()`
|
||||
static func erfc(_ x: Self) -> Self
|
||||
|
||||
/// 2^x
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `exp()`
|
||||
/// - `expMinusOne()`
|
||||
/// - `exp10()`
|
||||
/// - `log2()`
|
||||
/// - `pow()`
|
||||
static func exp2(_ x: Self) -> Self
|
||||
|
||||
/// 10^x
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `exp()`
|
||||
/// - `expMinusOne()`
|
||||
/// - `exp2()`
|
||||
/// - `log10()`
|
||||
/// - `pow()`
|
||||
static func exp10(_ x: Self) -> Self
|
||||
|
||||
/// `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()`
|
||||
static func gamma(_ x: Self) -> Self
|
||||
|
||||
/// The base-2 logarithm of `x`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `exp2()`
|
||||
/// - `log()`
|
||||
/// - `log(onePlus:)`
|
||||
/// - `log10()`
|
||||
static func log2(_ x: Self) -> Self
|
||||
|
||||
/// The base-10 logarithm of `x`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `exp10()`
|
||||
/// - `log()`
|
||||
/// - `log(onePlus:)`
|
||||
/// - `log2()`
|
||||
static func log10(_ x: Self) -> Self
|
||||
|
||||
#if !os(Windows)
|
||||
/// The logarithm of the absolute value of the gamma function, log(|Γ(x)|).
|
||||
///
|
||||
/// Not available on Windows targets.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `gamma()`
|
||||
/// - `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.
|
||||
///
|
||||
/// 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()`
|
||||
static func signGamma(_ x: Self) -> FloatingPointSign
|
||||
#endif
|
||||
}
|
||||
@@ -1,222 +0,0 @@
|
||||
//===--- ScalarConformances.swift -----------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// In theory we might be able to get away with using @_silgen_name for these
|
||||
// instead of NumericShims and remove a level of (source-only) indirection.
|
||||
// However, at present if we do that we get a compiler crash when this module
|
||||
// and the Swift platform module are both imported (<rdar://problem/53821031>).
|
||||
import NumericsShims
|
||||
|
||||
// MARK: Float + Real
|
||||
extension Float: Real {
|
||||
@_transparent public static func cos(_ x: Float) -> Float { return libm_cosf(x) }
|
||||
@_transparent public static func sin(_ x: Float) -> Float { return libm_sinf(x) }
|
||||
@_transparent public static func tan(_ x: Float) -> Float { return libm_tanf(x) }
|
||||
@_transparent public static func acos(_ x: Float) -> Float { return libm_acosf(x) }
|
||||
@_transparent public static func asin(_ x: Float) -> Float { return libm_asinf(x) }
|
||||
@_transparent public static func atan(_ x: Float) -> Float { return libm_atanf(x) }
|
||||
@_transparent public static func cosh(_ x: Float) -> Float { return libm_coshf(x) }
|
||||
@_transparent public static func sinh(_ x: Float) -> Float { return libm_sinhf(x) }
|
||||
@_transparent public static func tanh(_ x: Float) -> Float { return libm_tanhf(x) }
|
||||
@_transparent public static func acosh(_ x: Float) -> Float { return libm_acoshf(x) }
|
||||
@_transparent public static func asinh(_ x: Float) -> Float { return libm_asinhf(x) }
|
||||
@_transparent public static func atanh(_ x: Float) -> Float { return libm_atanhf(x) }
|
||||
@_transparent public static func exp(_ x: Float) -> Float { return libm_expf(x) }
|
||||
@_transparent public static func expMinusOne(_ x: Float) -> Float { return libm_expm1f(x) }
|
||||
@_transparent public static func log(_ x: Float) -> Float { return libm_logf(x) }
|
||||
@_transparent public static func log(onePlus x: Float) -> Float { return libm_log1pf(x) }
|
||||
@_transparent public static func erf(_ x: Float) -> Float { return libm_erff(x) }
|
||||
@_transparent public static func erfc(_ x: Float) -> Float { return libm_erfcf(x) }
|
||||
@_transparent public static func exp2(_ x: Float) -> Float { return libm_exp2f(x) }
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
@_transparent public static func exp10(_ x: Float) -> Float { return libm_exp10f(x) }
|
||||
#endif
|
||||
@_transparent public static func hypot(_ x: Float, _ y: Float) -> Float { return libm_hypotf(x, y) }
|
||||
@_transparent public static func gamma(_ x: Float) -> Float { return libm_tgammaf(x) }
|
||||
@_transparent public static func log2(_ x: Float) -> Float { return libm_log2f(x) }
|
||||
@_transparent public static func log10(_ x: Float) -> Float { return libm_log10f(x) }
|
||||
|
||||
@_transparent public static func pow(_ x: Float, _ y: Float) -> Float {
|
||||
guard x >= 0 else { return .nan }
|
||||
return libm_powf(x, y)
|
||||
}
|
||||
|
||||
@_transparent public static func pow(_ x: Float, _ n: Int) -> Float {
|
||||
// TODO: this implementation is not quite correct, because n may be
|
||||
// rounded in conversion to Float. This only effects very extreme cases,
|
||||
// so we'll leave it alone for now; however, it gets the sign wrong if
|
||||
// it rounds an odd number to an even number, so we should fix it soon.
|
||||
return libm_powf(x, Float(n))
|
||||
}
|
||||
|
||||
@_transparent public static func root(_ x: Float, _ n: Int) -> Float {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// Workaround the issue mentioned below for the specific case of n = 3
|
||||
// where we can fallback on cbrt.
|
||||
if n == 3 { return libm_cbrtf(x) }
|
||||
// TODO: this implementation is not quite correct, because either n or
|
||||
// 1/n may be not be representable as Float.
|
||||
return Float(signOf: x, magnitudeOf: libm_powf(x.magnitude, 1/Float(n)))
|
||||
}
|
||||
|
||||
@_transparent public static func atan2(y: Float, x: Float) -> Float {
|
||||
return libm_atan2f(y, x)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_transparent public static func logGamma(_ x: Float) -> Float {
|
||||
var dontCare: Int32 = 0
|
||||
return libm_lgammaf(x, &dontCare)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: Double + Real
|
||||
extension Double: Real {
|
||||
@_transparent public static func cos(_ x: Double) -> Double { return libm_cos(x) }
|
||||
@_transparent public static func sin(_ x: Double) -> Double { return libm_sin(x) }
|
||||
@_transparent public static func tan(_ x: Double) -> Double { return libm_tan(x) }
|
||||
@_transparent public static func acos(_ x: Double) -> Double { return libm_acos(x) }
|
||||
@_transparent public static func asin(_ x: Double) -> Double { return libm_asin(x) }
|
||||
@_transparent public static func atan(_ x: Double) -> Double { return libm_atan(x) }
|
||||
@_transparent public static func cosh(_ x: Double) -> Double { return libm_cosh(x) }
|
||||
@_transparent public static func sinh(_ x: Double) -> Double { return libm_sinh(x) }
|
||||
@_transparent public static func tanh(_ x: Double) -> Double { return libm_tanh(x) }
|
||||
@_transparent public static func acosh(_ x: Double) -> Double { return libm_acosh(x) }
|
||||
@_transparent public static func asinh(_ x: Double) -> Double { return libm_asinh(x) }
|
||||
@_transparent public static func atanh(_ x: Double) -> Double { return libm_atanh(x) }
|
||||
@_transparent public static func exp(_ x: Double) -> Double { return libm_exp(x) }
|
||||
@_transparent public static func expMinusOne(_ x: Double) -> Double { return libm_expm1(x) }
|
||||
@_transparent public static func log(_ x: Double) -> Double { return libm_log(x) }
|
||||
@_transparent public static func log(onePlus x: Double) -> Double { return libm_log1p(x) }
|
||||
@_transparent public static func erf(_ x: Double) -> Double { return libm_erf(x) }
|
||||
@_transparent public static func erfc(_ x: Double) -> Double { return libm_erfc(x) }
|
||||
@_transparent public static func exp2(_ x: Double) -> Double { return libm_exp2(x) }
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
@_transparent public static func exp10(_ x: Double) -> Double { return libm_exp10(x) }
|
||||
#endif
|
||||
#if os(macOS) && arch(x86_64)
|
||||
// Workaround for macOS bug (<rdar://problem/56844150>) where hypot can
|
||||
// overflow for values very close to the overflow boundary of the naive
|
||||
// algorithm. Since this is only for macOS, we can just unconditionally
|
||||
// use Float80, which makes the implementation trivial.
|
||||
public static func hypot(_ x: Double, _ y: Double) -> Double {
|
||||
if x.isInfinite || y.isInfinite { return .infinity }
|
||||
let x80 = Float80(x)
|
||||
let y80 = Float80(y)
|
||||
return Double(Float80.sqrt(x80*x80 + y80*y80))
|
||||
}
|
||||
#else
|
||||
@_transparent public static func hypot(_ x: Double, _ y: Double) -> Double {
|
||||
return libm_hypot(x, y)
|
||||
}
|
||||
#endif
|
||||
@_transparent public static func gamma(_ x: Double) -> Double { return libm_tgamma(x) }
|
||||
@_transparent public static func log2(_ x: Double) -> Double { return libm_log2(x) }
|
||||
@_transparent public static func log10(_ x: Double) -> Double { return libm_log10(x) }
|
||||
|
||||
@_transparent public static func pow(_ x: Double, _ y: Double) -> Double {
|
||||
guard x >= 0 else { return .nan }
|
||||
return libm_pow(x, y)
|
||||
}
|
||||
|
||||
@_transparent public static func pow(_ x: Double, _ n: Int) -> Double {
|
||||
// TODO: this implementation is not quite correct, because n may be
|
||||
// rounded in conversion to Double. This only effects very extreme cases,
|
||||
// so we'll leave it alone for now; however, it gets the sign wrong if
|
||||
// it rounds an odd number to an even number, so we should fix it soon.
|
||||
return libm_pow(x, Double(n))
|
||||
}
|
||||
|
||||
@_transparent public static func root(_ x: Double, _ n: Int) -> Double {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// Workaround the issue mentioned below for the specific case of n = 3
|
||||
// where we can fallback on cbrt.
|
||||
if n == 3 { return libm_cbrt(x) }
|
||||
// TODO: this implementation is not quite correct, because either n or
|
||||
// 1/n may be not be representable as Double.
|
||||
return Double(signOf: x, magnitudeOf: libm_pow(x.magnitude, 1/Double(n)))
|
||||
}
|
||||
|
||||
@_transparent public static func atan2(y: Double, x: Double) -> Double {
|
||||
return libm_atan2(y, x)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_transparent public static func logGamma(_ x: Double) -> Double {
|
||||
var dontCare: Int32 = 0
|
||||
return libm_lgamma(x, &dontCare)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: Float80 + Real
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
extension Float80: Real {
|
||||
@_transparent public static func cos(_ x: Float80) -> Float80 { return libm_cosl(x) }
|
||||
@_transparent public static func sin(_ x: Float80) -> Float80 { return libm_sinl(x) }
|
||||
@_transparent public static func tan(_ x: Float80) -> Float80 { return libm_tanl(x) }
|
||||
@_transparent public static func acos(_ x: Float80) -> Float80 { return libm_acosl(x) }
|
||||
@_transparent public static func asin(_ x: Float80) -> Float80 { return libm_asinl(x) }
|
||||
@_transparent public static func atan(_ x: Float80) -> Float80 { return libm_atanl(x) }
|
||||
@_transparent public static func cosh(_ x: Float80) -> Float80 { return libm_coshl(x) }
|
||||
@_transparent public static func sinh(_ x: Float80) -> Float80 { return libm_sinhl(x) }
|
||||
@_transparent public static func tanh(_ x: Float80) -> Float80 { return libm_tanhl(x) }
|
||||
@_transparent public static func acosh(_ x: Float80) -> Float80 { return libm_acoshl(x) }
|
||||
@_transparent public static func asinh(_ x: Float80) -> Float80 { return libm_asinhl(x) }
|
||||
@_transparent public static func atanh(_ x: Float80) -> Float80 { return libm_atanhl(x) }
|
||||
@_transparent public static func exp(_ x: Float80) -> Float80 { return libm_expl(x) }
|
||||
@_transparent public static func expMinusOne(_ x: Float80) -> Float80 { return libm_expm1l(x) }
|
||||
@_transparent public static func log(_ x: Float80) -> Float80 { return libm_logl(x) }
|
||||
@_transparent public static func log(onePlus x: Float80) -> Float80 { return libm_log1pl(x) }
|
||||
@_transparent public static func erf(_ x: Float80) -> Float80 { return libm_erfl(x) }
|
||||
@_transparent public static func erfc(_ x: Float80) -> Float80 { return libm_erfcl(x) }
|
||||
@_transparent public static func exp2(_ x: Float80) -> Float80 { return libm_exp2l(x) }
|
||||
@_transparent public static func hypot(_ x: Float80, _ y: Float80) -> Float80 { return libm_hypotl(x, y) }
|
||||
@_transparent public static func gamma(_ x: Float80) -> Float80 { return libm_tgammal(x) }
|
||||
@_transparent public static func log2(_ x: Float80) -> Float80 { return libm_log2l(x) }
|
||||
@_transparent public static func log10(_ x: Float80) -> Float80 { return libm_log10l(x) }
|
||||
|
||||
@_transparent public static func pow(_ x: Float80, _ y: Float80) -> Float80 {
|
||||
guard x >= 0 else { return .nan }
|
||||
return libm_powl(x, y)
|
||||
}
|
||||
|
||||
@_transparent public static func pow(_ x: Float80, _ n: Int) -> Float80 {
|
||||
// TODO: this implementation is not quite correct, because n may be
|
||||
// rounded in conversion to Float80. This only effects very extreme cases,
|
||||
// so we'll leave it alone for now; however, it gets the sign wrong if
|
||||
// it rounds an odd number to an even number, so we should fix it soon.
|
||||
return libm_powl(x, Float80(n))
|
||||
}
|
||||
|
||||
@_transparent public static func root(_ x: Float80, _ n: Int) -> Float80 {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// Workaround the issue mentioned below for the specific case of n = 3
|
||||
// where we can fallback on cbrt.
|
||||
if n == 3 { return libm_cbrtl(x) }
|
||||
// TODO: this implementation is not quite correct, because either n or
|
||||
// 1/n may be not be representable as Float80.
|
||||
return Float80(signOf: x, magnitudeOf: libm_powl(x.magnitude, 1/Float80(n)))
|
||||
}
|
||||
|
||||
@_transparent public static func atan2(y: Float80, x: Float80) -> Float80 {
|
||||
return libm_atan2l(y, x)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_transparent public static func logGamma(_ x: Float80) -> Float80 {
|
||||
var dontCare: Int32 = 0
|
||||
return libm_lgammal(x, &dontCare)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,132 @@
|
||||
//===--- AlgebraicField.swift ---------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 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 Swift's `SignedNumeric`, `Numeric` and `AdditiveArithmetic`
|
||||
/// protocols.
|
||||
///
|
||||
/// [field]: https://en.wikipedia.org/wiki/Field_(mathematics)
|
||||
public protocol AlgebraicField: SignedNumeric where Magnitude: AlgebraicField {
|
||||
|
||||
/// 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,247 @@
|
||||
//===--- ApproximateEquality.swift ----------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2020-2025 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 occurred, 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
|
||||
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,148 @@
|
||||
//===--- AugmentedArithmetic.swift ----------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2020-2025 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 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:FloatingPoint>(
|
||||
_ 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`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - a: The summand with larger magnitude.
|
||||
/// - b: The summand with smaller magnitude.
|
||||
///
|
||||
/// `head` is the correctly rounded value of `a + b`. `tail` is the
|
||||
/// error from that computation rounded to the closest representable
|
||||
/// value.
|
||||
///
|
||||
/// > Note:
|
||||
/// > `tail` is guaranteed to be the best approximation to the error of
|
||||
/// the sum only if `large.magnitude` >= `small.magnitude`. If this is
|
||||
/// not the case, then `head` is the correctly rounded sum, but `tail`
|
||||
/// is not guaranteed to be the exact error. If you do not know a priori
|
||||
/// how the magnitudes of `a` and `b` compare, you likely want to use
|
||||
/// ``sum(_:_:)`` instead.
|
||||
///
|
||||
/// Unlike ``product(_:_:)``, the rounding error of `sum` never underflows.
|
||||
///
|
||||
/// This operation is sometimes called ["fastTwoSum"].
|
||||
///
|
||||
/// > Note:
|
||||
/// > Classical fastTwoSum does not work when `radix` is 10. This function
|
||||
/// will fall back on another algorithm for decimal floating-point types
|
||||
/// to ensure correct results.
|
||||
///
|
||||
/// 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: FloatingPoint>(
|
||||
large a: T, small b: T
|
||||
) -> (head: T, tail: T) {
|
||||
// Fall back on 2Sum if radix != 2. Future implementations might use an
|
||||
// cheaper algorithm specialized for decimal FP, but must deliver a
|
||||
// correct result if the preconditions are satisfied.
|
||||
guard T.radix == 2 else { return sum(a, b) }
|
||||
// Fast2Sum:
|
||||
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.
|
||||
///
|
||||
/// The magnitude of the summands does not change the result of this
|
||||
/// operation. If you know statically that `a.magnitude >= b.magnitude`,
|
||||
/// you may want to consider using ``sum(large:small:)`` to get the same
|
||||
/// result somewhat more efficiently. If you do not have such a static
|
||||
/// bound, you usually want to use this function instead.
|
||||
///
|
||||
/// Unlike ``product(_:_:)``, the rounding error of `sum` never underflows.
|
||||
///
|
||||
/// This operation is sometimes called ["twoSum"].
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - a: One of the summands
|
||||
/// - 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: FloatingPoint>(
|
||||
_ 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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
@@ -0,0 +1,37 @@
|
||||
# ``Augmented``
|
||||
|
||||
A namespace for a family of algorithms that compute the results of floating-
|
||||
point arithmetic using multiple values such that either the error is minimized
|
||||
or the result is exact.
|
||||
|
||||
## Overview
|
||||
|
||||
Consider multiplying two Doubles. A Double has 53 significand bits, so their
|
||||
product could be up to 106 bits wide before it is rounded to a Double result.
|
||||
So up to 53 of those 106 bits will be "lost" in that process:
|
||||
|
||||
```swift
|
||||
let a = 1.0 + .ulpOfOne // 1 + 2⁻⁵²
|
||||
let b = 1.0 - .ulpOfOne // 1 - 2⁻⁵²
|
||||
let c = a * b // 1 - 2⁻¹⁰⁴ before rounding, rounds to 1.0
|
||||
```
|
||||
|
||||
Sometimes it is necessary to preserve some or all of those low-order bits;
|
||||
maybe a subsequent subtraction cancels most of the high-order bits, and so
|
||||
the low-order part of the product suddenly becomes significant:
|
||||
|
||||
```swift
|
||||
let result = 1 - c // exactly zero, but "should be" 2⁻¹⁰⁴
|
||||
```
|
||||
|
||||
Augmented arithmetic is a building-block that library writers can use to
|
||||
handle cases like this more carefully. For the example above, one might
|
||||
compute:
|
||||
|
||||
```swift
|
||||
let (head, tail) = Augmented.product(a,b)
|
||||
```
|
||||
|
||||
`head` is then 1.0 and `tail` is -2⁻¹⁰⁴, so no information has been lost.
|
||||
Of course, the result is now split across two Doubles instead of one, but the
|
||||
information in `tail` can be carried forward into future computations.
|
||||
@@ -0,0 +1,68 @@
|
||||
# ``ElementaryFunctions``
|
||||
|
||||
A type that has elementary functions (`sin`, `cos`, etc.) available.
|
||||
|
||||
## Overview
|
||||
|
||||
An ["elementary function"][elfn] is a function built up from powers, roots,
|
||||
exponentials, logarithms, trigonometric functions (sin, cos, tan) and
|
||||
their inverses, and the hyperbolic functions (sinh, cosh, tanh) and their
|
||||
inverses.
|
||||
|
||||
Conformance to this protocol means that all of these building blocks are
|
||||
available as static functions on the type.
|
||||
|
||||
```swift
|
||||
let x: Float = 1
|
||||
let y = Float.sin(x) // 0.84147096
|
||||
```
|
||||
|
||||
`ElementaryFunctions` conformance implies `AdditiveArithmetic`, so addition
|
||||
and subtraction and the `zero` property are also available.
|
||||
|
||||
``RealFunctions`` refines this protocol and adds additional functions that
|
||||
are primarily used with real numbers, such as ``RealFunctions/atan2(y:x:)``
|
||||
and ``RealFunctions/exp10(_:)``.
|
||||
|
||||
``Real`` conforms to `RealFunctions` and `FloatingPoint`, and is the
|
||||
protocol that you will use most often for generic code.
|
||||
|
||||
## Topics
|
||||
|
||||
There are a few families of functions defined by `ElementaryFunctions`:
|
||||
|
||||
### Exponential functions
|
||||
- ``exp(_:)``
|
||||
- ``expMinusOne(_:)``
|
||||
|
||||
### Logarithmetic functions
|
||||
- ``log(_:)``
|
||||
- ``log(onePlus:)``
|
||||
|
||||
### Power and root functions:
|
||||
- ``pow(_:_:)-9imp6``
|
||||
- ``pow(_:_:)-2qmul``
|
||||
- ``sqrt(_:)``
|
||||
- ``root(_:_:)``
|
||||
|
||||
### Trigonometric functions
|
||||
- ``cos(_:)``
|
||||
- ``sin(_:)``
|
||||
- ``tan(_:)``
|
||||
|
||||
### Inverse trigonometric functions
|
||||
- ``acos(_:)``
|
||||
- ``asin(_:)``
|
||||
- ``atan(_:)``
|
||||
|
||||
### Hyperbolic functions
|
||||
- ``cosh(_:)``
|
||||
- ``sinh(_:)``
|
||||
- ``tanh(_:)``
|
||||
|
||||
### Inverse hyperbolic functions
|
||||
- ``acosh(_:)``
|
||||
- ``asinh(_:)``
|
||||
- ``atanh(_:)``
|
||||
|
||||
[elfn]: http://en.wikipedia.org/wiki/Elementary_function
|
||||
@@ -0,0 +1,27 @@
|
||||
# ``RealFunctions``
|
||||
|
||||
A type that extends ``ElementaryFunctions`` with additional operations that
|
||||
are primarily used with real numbers.
|
||||
|
||||
## Topics
|
||||
|
||||
### Exponential functions
|
||||
- ``exp2(_:)``
|
||||
- ``exp10(_:)``
|
||||
|
||||
### Logarithmetic functions
|
||||
- ``log2(_:)``
|
||||
- ``log10(_:)``
|
||||
|
||||
### Plane geometry
|
||||
- ``atan2(y:x:)``
|
||||
- ``hypot(_:_:)``
|
||||
|
||||
### Gamma function
|
||||
- ``gamma(_:)``
|
||||
- ``logGamma(_:)``
|
||||
- ``signGamma(_:)``
|
||||
|
||||
### Error function
|
||||
- ``erf(_:)``
|
||||
- ``erfc(_:)``
|
||||
@@ -0,0 +1,28 @@
|
||||
# ``RealModule``
|
||||
|
||||
Extensions on the Swift standard library that provide functionality for
|
||||
floating-point types.
|
||||
|
||||
## Overview
|
||||
|
||||
``RealModule`` provides four protocols that extend the standard library's
|
||||
numeric protocol hierarchy: AlgebraicField, ElementaryFunctions,
|
||||
RealFunctions, and Real.
|
||||
|
||||
Types conforming to AlgebraicField represent
|
||||
[fields](https://en.wikipedia.org/wiki/Field_(mathematics)). These are the
|
||||
mathematical structures that typically form the elements of vectors and
|
||||
matrices, so this protocol is appropriate for writing generic code to do
|
||||
linear-algebra-type operations.
|
||||
|
||||
ElementaryFunctions provides bindings for the "math functions": the logarithm
|
||||
and exponential functions, sine, cosine and tangent as well as their inverses,
|
||||
and other functions that you may be familiar with from trigonometry and
|
||||
calculus. RealFunctions refines ElementaryFunctions and provides functions that
|
||||
are primarily used with the real numbers, such as atan2, erf and gamma, and
|
||||
the base-2 and -10 logarithm and exponential funtions.
|
||||
|
||||
The Real protocol is a convenient name for the intersection of `FloatingPoint`,
|
||||
`RealFunctions`, and `AlgebraicField`; this is the protocol that you are most
|
||||
likely to want to constrain to when writing generic "math" code that works
|
||||
with floating-point types.
|
||||
@@ -0,0 +1,53 @@
|
||||
# ``Relaxed``
|
||||
|
||||
A namespace for a family of operations that "relax" the usual rules for
|
||||
floating-point to allow reassociation of arithmetic and FMA formation.
|
||||
|
||||
## Overview
|
||||
|
||||
Because of rounding, and the arithmetic rules for infinity and NaN values,
|
||||
floating-point addition and multiplication are not associative:
|
||||
|
||||
```swift
|
||||
let ε = Double.leastNormalMagnitude
|
||||
let sumLeft = (-1 + 1) + ε // 0 + ε = ε
|
||||
let sumRight = -1 + (1 + ε) // -1 + 1 = 0
|
||||
|
||||
let ∞ = Double.infinity
|
||||
let productLeft = (ε * ε) * ∞ // 0 * ∞ = .nan
|
||||
let productRight = ε * (ε * ∞) // ε * ∞ = ∞
|
||||
```
|
||||
|
||||
For some algorithms, the distinction between these results is incidental; for
|
||||
some others it is critical to their correct function. Because of this,
|
||||
compilers cannot freely change the order of reductions, which prevents some
|
||||
important optimizations: extraction of instruction-level parallelism and
|
||||
vectorization.
|
||||
|
||||
If you know that you are in a case where the order of elements being summed
|
||||
or multiplied is incidental, the Relaxed operations give you a mechanism
|
||||
to communicate that to the compiler and unlock these optimizations. For
|
||||
example, consider the following two functions:
|
||||
|
||||
```swift
|
||||
func sum(array: [Float]) -> Float {
|
||||
array.reduce(0, +)
|
||||
}
|
||||
|
||||
func relaxedSum(array: [Float]) -> Float {
|
||||
array.reduce(0, Relaxed.sum)
|
||||
}
|
||||
```
|
||||
|
||||
when called on an array with 1000 elements in a Release build, `relaxedSum`
|
||||
is about 8x faster than `sum` on Apple M2, with a similar speedup on Intel
|
||||
processors, without the need for any unsafe code or flags.
|
||||
|
||||
### multiplyAdd
|
||||
|
||||
In addition to `sum` and `product`, `Relaxed` provides the
|
||||
``multiplyAdd(_:_:_:)`` operation, which communciates to the compiler that
|
||||
it is allowed to replace separate multiply and add operations with a single
|
||||
_fused multiply-add_ instruction if its cost model indicates that it would
|
||||
be advantageous to do so. When targeting processors that support this
|
||||
instruction, this may be a significant performance advantage.
|
||||
@@ -0,0 +1,232 @@
|
||||
//===--- Double+Real.swift ------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 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)
|
||||
}
|
||||
}
|
||||
+63
-160
@@ -2,86 +2,42 @@
|
||||
//
|
||||
// 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-2025 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 has elementary functions available.
|
||||
///
|
||||
/// An ["elementary function"][elfn] is a function built up from powers, roots,
|
||||
/// exponentials, logarithms, trigonometric functions (sin, cos, tan) and
|
||||
/// their inverses, and the hyperbolic functions (sinh, cosh, tanh) and their
|
||||
/// inverses.
|
||||
///
|
||||
/// Conformance to this protocol means that all of these building blocks are
|
||||
/// available as static functions on the type.
|
||||
///
|
||||
/// ```swift
|
||||
/// let x: Float = 1
|
||||
/// let y = Float.sin(x) // 0.84147096
|
||||
/// ```
|
||||
///
|
||||
/// 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`.
|
||||
/// - 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:
|
||||
///
|
||||
/// `RealFunctions` refines `ElementaryFunctions` and includes
|
||||
/// additional functions specific to real number types.
|
||||
///
|
||||
/// `Real` conforms to `RealFunctions` and `FloatingPoint`, and is the
|
||||
/// 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`)
|
||||
/// For types that conform to ``RealFunctions`` see
|
||||
/// ``RealFunctions/exp2(_:)`` and ``RealFunctions/exp10(_:)``.
|
||||
///
|
||||
/// [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`)
|
||||
/// For types that conform to ``RealFunctions`` see
|
||||
/// ``RealFunctions/exp2(_:)`` and ``RealFunctions/exp10(_:)``.
|
||||
static func expMinusOne(_ x: Self) -> Self
|
||||
|
||||
/// The [hyperbolic cosine][wiki] of `x`.
|
||||
@@ -91,11 +47,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
/// 2
|
||||
/// ```
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `sinh()`
|
||||
/// - `tanh()`
|
||||
/// - `acosh()`
|
||||
/// See also ``acosh(_:)``.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
|
||||
static func cosh(_ x: Self) -> Self
|
||||
@@ -107,11 +59,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
/// 2
|
||||
/// ```
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `cosh()`
|
||||
/// - `tanh()`
|
||||
/// - `asinh()`
|
||||
/// See also ``asinh(_:)``.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
|
||||
static func sinh(_ x: Self) -> Self
|
||||
@@ -123,11 +71,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
/// cosh(x)
|
||||
/// ```
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `cosh()`
|
||||
/// - `sinhh()`
|
||||
/// - `atanh()`
|
||||
/// See also ``atanh(_:)``.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
|
||||
static func tanh(_ x: Self) -> Self
|
||||
@@ -136,11 +80,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 ``acos(_:)``.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Cosine
|
||||
static func cos(_ x: Self) -> Self
|
||||
@@ -150,11 +90,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 ``asin(_:)``.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Sine
|
||||
static func sin(_ x: Self) -> Self
|
||||
@@ -163,159 +99,126 @@ 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 ``atan(_:)``.
|
||||
///
|
||||
/// [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`)
|
||||
/// For types that conform to ``RealFunctions`` see also
|
||||
/// ``RealFunctions/log2(_:)`` and ``RealFunctions/log10(_:)``.
|
||||
///
|
||||
/// [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`)
|
||||
/// For types that conform to ``RealFunctions`` see also
|
||||
/// ``RealFunctions/log2(_:)`` and ``RealFunctions/log10(_:)``.
|
||||
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 ``cosh(_:)``.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
|
||||
static func acosh(_ x: Self) -> Self
|
||||
|
||||
/// The [inverse hyperbolic sine][wiki] of `x`.
|
||||
///
|
||||
/// ```
|
||||
/// sinh(asinh(x)) ≅ x
|
||||
/// ```
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `acosh()`
|
||||
/// - `atanh()`
|
||||
/// - `sinh()`
|
||||
///
|
||||
/// See also ``sinh(_:)``.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
|
||||
static func asinh(_ x: Self) -> Self
|
||||
|
||||
/// The [inverse hyperbolic tangent][wiki] of `x`.
|
||||
///
|
||||
/// ```
|
||||
/// tanh(atanh(x)) ≅ x
|
||||
/// ```
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `acosh()`
|
||||
/// - `asinh()`
|
||||
/// - `tanh()`
|
||||
///
|
||||
/// See also ``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 ``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 ``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 ``tan(_:)``.
|
||||
/// For types that conform to ``RealFunctions``, you will sometimes want
|
||||
/// to use ``RealFunctions/atan2(y:x:)`` instead.
|
||||
///
|
||||
/// [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
|
||||
/// <doc:/documentation/RealModule/ElementaryFunctions/pow(_:_:)-9imp6>,
|
||||
/// whose behavior is defined in terms of repeated multiplication.
|
||||
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.
|
||||
static func pow(_ x: Self, _ n: Int) -> Self
|
||||
|
||||
/// The [square root][wiki] of `x`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `pow()`
|
||||
/// - `root()`
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Square_root
|
||||
static func sqrt(_ x: Self) -> Self
|
||||
|
||||
/// The nth root of `x`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `pow()`
|
||||
/// - `sqrt()`
|
||||
///
|
||||
static func root(_ x: Self, _ n: Int) -> Self
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//===--- 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
|
||||
|
||||
#if !arch(wasm32)
|
||||
// WASM doesn't have _Float16 on the C side, so we can't define the C hooks
|
||||
// that these use. TODO: implement these as Swift builtins instead.
|
||||
|
||||
@_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
|
||||
@@ -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
|
||||
[SE-0246]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0246-mathable.md
|
||||
[Sigmoid]: https://en.wikipedia.org/wiki/Sigmoid_function
|
||||
@@ -0,0 +1,150 @@
|
||||
//===--- Real.swift -------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 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. This is not a great one (if the underlying math
|
||||
// library does not have a sub-ulp accurate pow, this will not get
|
||||
// exact powers of ten right), but suffices in the short term.
|
||||
@_transparent
|
||||
public static func exp10(_ x: Self) -> Self {
|
||||
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 {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//===--- RealFunctions.swift ----------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 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 protocol RealFunctions: ElementaryFunctions {
|
||||
/// The signed angle formed in the plane between the vector `(x,y)` and the
|
||||
/// positive real axis, measured in radians.
|
||||
///
|
||||
/// The result is in the interval `[-π, π]`.
|
||||
///
|
||||
/// The argument order to `atan2` may be surprising to new programmers.
|
||||
/// The convention of `y` being the first argument goes back at least to
|
||||
/// Fortran IV in 1961 and is generally followed in computing with a few
|
||||
/// notable exceptions (e.g. Mathematica and Excel). This convention was
|
||||
/// originally chosen because of the mathematical definition of the
|
||||
/// function:
|
||||
///
|
||||
/// ```
|
||||
/// atan2(y,x) = atan(y/x) if x > 0
|
||||
/// ```
|
||||
///
|
||||
/// See also ``ElementaryFunctions/atan(_:)``, as well as the `phase` and
|
||||
/// `polar` properties defined on the `Complex` type.
|
||||
static func atan2(y: Self, x: Self) -> Self
|
||||
|
||||
/// The [error function](https://en.wikipedia.org/wiki/Error_function)
|
||||
/// evaluated at `x`.
|
||||
static func erf(_ x: Self) -> Self
|
||||
|
||||
/// The complimentary [error function](https://en.wikipedia.org/wiki/Error_function)
|
||||
/// evaluated at `x`.
|
||||
static func erfc(_ x: Self) -> Self
|
||||
|
||||
/// 2 raised to the power x.
|
||||
///
|
||||
/// See also ``log2(_:)``, ``ElementaryFunctions/exp(_:)``,
|
||||
/// ``ElementaryFunctions/expMinusOne(_:)``
|
||||
/// and ``ElementaryFunctions/pow(_:_:)-2qmul``.
|
||||
static func exp2(_ x: Self) -> Self
|
||||
|
||||
/// 10 raised to the power x.
|
||||
///
|
||||
/// See also ``log10(_:)``, ``ElementaryFunctions/exp(_:)``,
|
||||
/// ``ElementaryFunctions/expMinusOne(_:)``
|
||||
/// and ``ElementaryFunctions/pow(_:_:)-2qmul``.
|
||||
static func exp10(_ x: Self) -> Self
|
||||
|
||||
/// The length of the vector `(x,y)`, computed in a manner that avoids
|
||||
/// spurious overflow or underflow.
|
||||
///
|
||||
/// See also the `length` and `polar` properties defined on the `Complex`
|
||||
/// type.
|
||||
static func hypot(_ x: Self, _ y: Self) -> Self
|
||||
|
||||
/// The [gamma function](https://en.wikipedia.org/wiki/Gamma_function) Γ(x).
|
||||
static func gamma(_ x: Self) -> Self
|
||||
|
||||
/// The base-2 logarithm of `x`.
|
||||
///
|
||||
/// See also ``exp2(_:)``, ``ElementaryFunctions/log(_:)``,
|
||||
/// and ``ElementaryFunctions/log(onePlus:)``.
|
||||
static func log2(_ x: Self) -> Self
|
||||
|
||||
/// The base-10 logarithm of `x`.
|
||||
///
|
||||
/// See also ``exp10(_:)``, ``ElementaryFunctions/log(_:)``,
|
||||
/// and ``ElementaryFunctions/log(onePlus:)``.
|
||||
static func log10(_ x: Self) -> Self
|
||||
|
||||
#if !os(Windows)
|
||||
/// The logarithm of the absolute value of the
|
||||
/// [gamma function](https://en.wikipedia.org/wiki/Gamma_function),
|
||||
/// log(|Γ(x)|).
|
||||
///
|
||||
/// Not available on Windows targets.
|
||||
static func logGamma(_ x: Self) -> Self
|
||||
|
||||
/// The sign of the
|
||||
/// [gamma function](https://en.wikipedia.org/wiki/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.
|
||||
///
|
||||
/// 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.
|
||||
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-2025 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
|
||||
|
||||
public enum Relaxed { }
|
||||
|
||||
extension Relaxed {
|
||||
/// a+b, but grants the optimizer permission 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, but grants the optimizer permission 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))
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
+88
-19
@@ -2,17 +2,35 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define HEADER_SHIM static inline __attribute__((__always_inline__))
|
||||
|
||||
// MARK: - math functions for float
|
||||
// This header uses most of the libm functions, but we don't want to end up
|
||||
// exporting the libm declarations to modules that include NumericsShims, so
|
||||
// we don't want to actually #include <math.h>.
|
||||
//
|
||||
// For most of the functions, we can get around this by using __builtin_func
|
||||
// instead of func, since the compiler knows about these operations, but for
|
||||
// the non-standard extensions, we need to include our own declarations. This
|
||||
// is a little bit risky, in that we might end up missing an attribute that
|
||||
// gets added and effects calling conventions, etc, but that's expected to be
|
||||
// exceedingly rare.
|
||||
//
|
||||
// Still, we'll eventually want to find a better solution to this problem,
|
||||
// especially if people start using this package on systems that are not
|
||||
// Darwin or Ubuntu.
|
||||
|
||||
// MARK: - math functions for float
|
||||
HEADER_SHIM float libm_cosf(float x) {
|
||||
return __builtin_cosf(x);
|
||||
}
|
||||
@@ -131,9 +149,7 @@ HEADER_SHIM float libm_log10f(float x) {
|
||||
|
||||
#if !defined _WIN32
|
||||
HEADER_SHIM float libm_lgammaf(float x, int *signp) {
|
||||
#if __APPLE__
|
||||
extern float lgammaf_r(float, int *);
|
||||
#endif
|
||||
return lgammaf_r(x, signp);
|
||||
}
|
||||
#endif
|
||||
@@ -253,9 +269,7 @@ HEADER_SHIM double libm_log10(double x) {
|
||||
|
||||
#if !defined _WIN32
|
||||
HEADER_SHIM double libm_lgamma(double x, int *signp) {
|
||||
#if __APPLE__
|
||||
extern double lgamma_r(double, int *);
|
||||
#endif
|
||||
return lgamma_r(x, signp);
|
||||
}
|
||||
#endif
|
||||
@@ -372,20 +386,75 @@ 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 !defined __wasm__ // No _Float16 on wasm
|
||||
/// 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
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,3 @@
|
||||
module _NumericsShims {
|
||||
header "_NumericsShims.h"
|
||||
}
|
||||
@@ -1,12 +1,19 @@
|
||||
//===--- LinuxMain.swift --------------------------------------*- swift -*-===//
|
||||
//===--- BlackHole.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) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
fatalError("Use --enable-test-discovery to run Swift Numerics tests on Linux.")
|
||||
import _NumericsShims
|
||||
|
||||
@_transparent
|
||||
public func blackHole<T>(_ thing: T) {
|
||||
withUnsafePointer(to: thing) {
|
||||
_numerics_optimization_barrier($0)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
@@ -0,0 +1,782 @@
|
||||
//===--- DoubleWidth.swift ------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2017-2024 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 partialValue = DoubleWidth(truncatingIfNeeded: product)
|
||||
// Overflow has occured if carry is not just the sign-extension of
|
||||
// partialValue (which is zero when Base is unsigned).
|
||||
let overflow = carry != (partialValue >> DoubleWidth.bitWidth)
|
||||
return (partialValue, overflow)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// When using a pre-Swift 6.0 runtime, `&*` is not a protocol requirement of
|
||||
// FixedWidthInteger, which results in the default implementation of this
|
||||
// operation ending up recursively calling itself forever. In order to avoid
|
||||
// this, we keep the concrete implementation around.
|
||||
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 {
|
||||
let bits = DoubleWidth(DoubleWidth.bitWidth)
|
||||
if DoubleWidth.bitWidth.nonzeroBitCount == 1 {
|
||||
return self & (bits &- 1)
|
||||
}
|
||||
let reduced = self % bits
|
||||
// bitWidth is always positive, but the value being reduced might have
|
||||
// been negative, in which case reduced will also be negative. We need
|
||||
// the representative in [0, bitWidth), so conditionally add the count
|
||||
// to get the positive residue.
|
||||
if Base.isSigned && reduced < 0 { return reduced &+ bits }
|
||||
return reduced
|
||||
}
|
||||
|
||||
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 static func &+(
|
||||
lhs: DoubleWidth, rhs: DoubleWidth
|
||||
) -> DoubleWidth {
|
||||
let (low, carry) = lhs.low.addingReportingOverflow(rhs.low)
|
||||
let high = lhs.high &+ rhs.high &+ (carry ? 1 : 0)
|
||||
return DoubleWidth(high, low)
|
||||
}
|
||||
|
||||
public static func &-(
|
||||
lhs: DoubleWidth, rhs: DoubleWidth
|
||||
) -> DoubleWidth {
|
||||
let (low, borrow) = lhs.low.subtractingReportingOverflow(rhs.low)
|
||||
let high = lhs.high &- rhs.high &- (borrow ? 1 : 0)
|
||||
return DoubleWidth(high, low)
|
||||
}
|
||||
|
||||
public static func &*(
|
||||
lhs: DoubleWidth, rhs: DoubleWidth
|
||||
) -> DoubleWidth {
|
||||
let p00 = lhs.low.multipliedFullWidth(by: rhs.low)
|
||||
let p10 = lhs.high &* Base(truncatingIfNeeded: rhs.low)
|
||||
let p01 = Base(truncatingIfNeeded: lhs.low) &* rhs.high
|
||||
return DoubleWidth(p10 &+ p01 &+ Base(truncatingIfNeeded: p00.high), p00.low)
|
||||
}
|
||||
|
||||
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 {}
|
||||
@@ -0,0 +1,32 @@
|
||||
//===--- Error.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
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//===--- Interval.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
|
||||
// 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)!
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
//===--- ApproximateEqualityTests.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
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -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-2024 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,14 +10,26 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Complex
|
||||
import Real
|
||||
import ComplexModule
|
||||
import RealModule
|
||||
|
||||
func ulpsFromInfinity<T: Real>(_ a: T) -> T {
|
||||
(.greatestFiniteMagnitude - a) / .greatestFiniteMagnitude.ulp + 1
|
||||
}
|
||||
|
||||
// TODO: improve this to be a general-purpose complex comparison with tolerance
|
||||
func relativeError<T>(_ a: Complex<T>, _ b: Complex<T>) -> T {
|
||||
if a == b { return 0 }
|
||||
let scale = max(a.magnitude, b.magnitude, T.leastNormalMagnitude).ulp
|
||||
return (a - b).magnitude / scale
|
||||
if a.isFinite && b.isFinite {
|
||||
let scale = max(a.magnitude, b.magnitude, T.leastNormalMagnitude).ulp
|
||||
return (a - b).magnitude / scale
|
||||
} else {
|
||||
if a.isFinite {
|
||||
return ulpsFromInfinity(a.magnitude)
|
||||
} else {
|
||||
return ulpsFromInfinity(b.magnitude)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func closeEnough<T: Real>(_ a: T, _ b: T, ulps allowed: T) -> Bool {
|
||||
@@ -29,11 +41,15 @@ func checkMultiply<T>(
|
||||
_ a: Complex<T>, _ b: Complex<T>, expected: Complex<T>, ulps allowed: T
|
||||
) -> Bool {
|
||||
let observed = a*b
|
||||
if observed == expected { return false }
|
||||
// Even if the expected result is finite, we allow overflow if
|
||||
// the two-norm of the expected result overflows.
|
||||
if !observed.isFinite && !expected.length.isFinite { return false }
|
||||
let rel = relativeError(observed, expected)
|
||||
if rel > allowed {
|
||||
guard rel <= allowed else {
|
||||
print("Over-large error in \(a)*\(b)")
|
||||
print("Expected: \(expected)\nObserved: \(observed)")
|
||||
print("Relative error was \(rel) (tolerance: \(allowed).")
|
||||
print("Relative error was \(rel) (tolerance: \(allowed)).")
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -43,11 +59,15 @@ func checkDivide<T>(
|
||||
_ a: Complex<T>, _ b: Complex<T>, expected: Complex<T>, ulps allowed: T
|
||||
) -> Bool {
|
||||
let observed = a/b
|
||||
if observed == expected { return false }
|
||||
// Even if the expected result is finite, we allow overflow if
|
||||
// the two-norm of the expected result overflows.
|
||||
if !observed.isFinite && !expected.length.isFinite { return false }
|
||||
let rel = relativeError(observed, expected)
|
||||
if rel > allowed {
|
||||
guard rel <= allowed else {
|
||||
print("Over-large error in \(a)/\(b)")
|
||||
print("Expected: \(expected)\nObserved: \(observed)")
|
||||
print("Relative error was \(rel) (tolerance: \(allowed).")
|
||||
print("Relative error was \(rel) (tolerance: \(allowed)).")
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -63,7 +83,6 @@ 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.
|
||||
@@ -76,10 +95,9 @@ final class ArithmeticTests: XCTestCase {
|
||||
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
|
||||
T.leastNormalMagnitude.exponent ... T.greatestFiniteMagnitude.exponent
|
||||
let inputs = (0..<100).map { _ in
|
||||
Polar(length: T(
|
||||
sign: .plus,
|
||||
@@ -136,20 +154,29 @@ 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)
|
||||
var product = Complex(length: p.length, phase: p.phase + q.phase)
|
||||
product.real *= q.length
|
||||
product.imaginary *= q.length
|
||||
if checkMultiply(z, w, expected: product, ulps: 16) { XCTFail() }
|
||||
let quotient = Complex(length: p.length / q.length, phase: p.phase - q.phase)
|
||||
var quotient = Complex(length: p.length, phase: p.phase - q.phase)
|
||||
quotient.real /= q.length
|
||||
quotient.imaginary /= q.length
|
||||
if checkDivide(z, w, expected: quotient, ulps: 16) { XCTFail() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testPolar() {
|
||||
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64)) && LONG_TESTS
|
||||
if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
|
||||
testPolar(Float16.self)
|
||||
}
|
||||
#endif
|
||||
testPolar(Float.self)
|
||||
testPolar(Double.self)
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
testPolar(Float80.self)
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
func testBaudinSmith() {
|
||||
@@ -165,12 +192,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
|
||||
@@ -193,16 +218,38 @@ final class ArithmeticTests: XCTestCase {
|
||||
Complex(1.02951151789360578e-84, 6.97145987515076231e-220)),
|
||||
]
|
||||
for test in vectors {
|
||||
if checkDivide(test.a, test.b, expected: test.c, ulps: 0.5) { XCTFail() }
|
||||
if checkDivide(test.a, test.b, expected: test.c, ulps: 1.0) { XCTFail() }
|
||||
if checkDivide(test.a, test.c, expected: test.b, ulps: 1.0) { XCTFail() }
|
||||
if checkMultiply(test.b, test.c, expected: test.a, ulps: 1.0) { XCTFail() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testDivisionByZero() {
|
||||
XCTAssertFalse((Complex(0, 0) / Complex(0, 0)).isFinite)
|
||||
XCTAssertFalse((Complex(1, 1) / Complex(0, 0)).isFinite)
|
||||
XCTAssertFalse((Complex.infinity / Complex(0, 0)).isFinite)
|
||||
XCTAssertFalse((Complex.i / Complex(0, 0)).isFinite)
|
||||
|
||||
}
|
||||
|
||||
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64)) && LONG_TESTS
|
||||
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
|
||||
func testFloat16DivisionSemiExhaustive() {
|
||||
func complex(bitPattern: UInt32) -> Complex<Float16> {
|
||||
Complex(
|
||||
Float16(bitPattern: UInt16(truncatingIfNeeded: bitPattern)),
|
||||
Float16(bitPattern: UInt16(truncatingIfNeeded: bitPattern >> 16))
|
||||
)
|
||||
}
|
||||
for bits in 0 ... UInt32.max {
|
||||
let a = complex(bitPattern: bits)
|
||||
if bits & 0xfffff == 0 { print(a) }
|
||||
let b = complex(bitPattern: UInt32.random(in: 0 ... .max))
|
||||
var q = Complex<Float>(a)/Complex<Float>(b)
|
||||
if checkDivide(a, b, expected: Complex<Float16>(q), ulps: 4) { XCTFail() }
|
||||
q = Complex<Float>(b)/Complex<Float>(a)
|
||||
if checkDivide(b, a, expected: Complex<Float16>(q), ulps: 4) { XCTFail() }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -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 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
|
||||
// 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
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -10,8 +10,8 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Complex
|
||||
import Real
|
||||
import ComplexModule
|
||||
import RealModule
|
||||
|
||||
final class PropertyTests: XCTestCase {
|
||||
|
||||
@@ -102,4 +102,31 @@ final class PropertyTests: XCTestCase {
|
||||
testEquatableHashable(Float80.self)
|
||||
#endif
|
||||
}
|
||||
|
||||
func testCodable<T: Codable & Real>(_ type: T.Type) throws {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.nonConformingFloatEncodingStrategy = .convertToString(
|
||||
positiveInfinity: "inf",
|
||||
negativeInfinity: "-inf",
|
||||
nan: "nan")
|
||||
|
||||
let decoder = JSONDecoder()
|
||||
decoder.nonConformingFloatDecodingStrategy = .convertFromString(
|
||||
positiveInfinity: "inf",
|
||||
negativeInfinity: "-inf",
|
||||
nan: "nan")
|
||||
|
||||
for expected: Complex<T> in [.zero, .one, .i, .infinity] {
|
||||
let data = try encoder.encode(expected)
|
||||
// print("*** \(String(decoding: data, as: Unicode.UTF8.self)) ***")
|
||||
let actual = try decoder.decode(Complex<T>.self, from: data)
|
||||
XCTAssertEqual(actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func testCodable() throws {
|
||||
try testCodable(Float32.self)
|
||||
try testCodable(Float64.self)
|
||||
// Float80 doesn't conform to Codable.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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,484 @@
|
||||
//===--- DivideTests.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
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IntegerUtilities
|
||||
import _TestSupport
|
||||
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)) failed the division rule.
|
||||
a - qb was \(ref), but r is \(r).
|
||||
""")
|
||||
return false
|
||||
}
|
||||
if r.magnitude >= b.magnitude {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b)) 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)
|
||||
let justq = a.divided(by: b, rounding: .down)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .down) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
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)
|
||||
let justq = a.divided(by: b, rounding: .up)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .up) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
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)
|
||||
let justq = a.divided(by: b, rounding: .towardZero)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .towardZero) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
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)
|
||||
let justq = a.divided(by: b, rounding: .awayFromZero)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .awayFromZero) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
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 testDivideToNearestOrDown<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: .toNearestOrDown)
|
||||
let justq = a.divided(by: b, rounding: .toNearestOrDown)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrDown) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
|
||||
XCTAssertEqual(q, justq)
|
||||
if divisionRuleHolds(a, b, q, r) {
|
||||
// We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2
|
||||
// with equality only if q rounded down.
|
||||
if 2*r.magnitude > b.magnitude {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrDown) 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() != b.signum() {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrDown) failed check:
|
||||
If |remainder| equals |divisor|/2, remainder must have same sign as divisor, but was \(r).
|
||||
""")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDivideToNearestOrUp<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: .toNearestOrUp)
|
||||
let justq = a.divided(by: b, rounding: .toNearestOrUp)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrUp) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
if divisionRuleHolds(a, b, q, r) {
|
||||
// We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2
|
||||
// with equality only if q rounded up.
|
||||
if 2*r.magnitude > b.magnitude {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrUp) 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() == b.signum() {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrUp) failed check:
|
||||
If |remainder| equals |divisor|/2, remainder must have opposite sign of divisor, but was \(r).
|
||||
""")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDivideToNearestOrZero<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: .toNearestOrZero)
|
||||
let justq = a.divided(by: b, rounding: .toNearestOrZero)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrZero) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
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: .toNearestOrZero) 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: .toNearestOrZero) failed check:
|
||||
If |remainder| equals |divisor|/2, remainder must match sign of dividend, but 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: .toNearestOrAway)
|
||||
let justq = a.divided(by: b, rounding: .toNearestOrAway)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrAway) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
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: .toNearestOrAway) 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: .toNearestOrAway) 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)
|
||||
let justq = a.divided(by: b, rounding: .toNearestOrEven)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrEven) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
if divisionRuleHolds(a, b, q, r) {
|
||||
// We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2
|
||||
// with equality only if q is even.
|
||||
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 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)
|
||||
let justq = a.divided(by: b, rounding: .toOdd)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toOdd) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
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 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)
|
||||
testDivideToNearestOrDown(values)
|
||||
testDivideToNearestOrUp(values)
|
||||
testDivideToNearestOrZero(values)
|
||||
testDivideToNearestOrAway(values)
|
||||
testDivideToNearestOrEven(values)
|
||||
testDivideToOdd(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)
|
||||
testDivideToNearestOrDown(values)
|
||||
testDivideToNearestOrUp(values)
|
||||
testDivideToNearestOrZero(values)
|
||||
testDivideToNearestOrAway(values)
|
||||
testDivideToNearestOrEven(values)
|
||||
testDivideToOdd(values)
|
||||
testDivideExact(values)
|
||||
}
|
||||
|
||||
func testDivideInt128() {
|
||||
var values = [DoubleWidth<Int64>](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)
|
||||
testDivideToNearestOrDown(values)
|
||||
testDivideToNearestOrUp(values)
|
||||
testDivideToNearestOrZero(values)
|
||||
testDivideToNearestOrAway(values)
|
||||
testDivideToNearestOrEven(values)
|
||||
testDivideToOdd(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: .toNearestOrDown)
|
||||
divideUInt8(a, b, rounding: .toNearestOrUp)
|
||||
divideUInt8(a, b, rounding: .toNearestOrZero)
|
||||
divideUInt8(a, b, rounding: .toNearestOrAway)
|
||||
divideUInt8(a, b, rounding: .toNearestOrEven)
|
||||
divideUInt8(a, b, rounding: .toOdd)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
//===--- DoubleWidthTests.swift -------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2017-2024 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)
|
||||
}
|
||||
|
||||
func testMultiplyOverflow() {
|
||||
XCTAssertFalse(_Int128(-1).multipliedReportingOverflow(by: 0).overflow)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//===--- GCDTests.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
|
||||
// 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 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
|
||||
// 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,243 @@
|
||||
//===--- RoundingTests.swift ----------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2024 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
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IntegerUtilities
|
||||
import _TestSupport
|
||||
import XCTest
|
||||
|
||||
final class IntegerUtilitiesRoundingTests: XCTestCase {
|
||||
func testRoundingDirected<T: BinaryFloatingPoint>(_ type: T.Type) {
|
||||
let inf = T.infinity
|
||||
let gfm = T.greatestFiniteMagnitude
|
||||
let big: T = 1 / .ulpOfOne
|
||||
let two: T = 2
|
||||
let threeHalves: T = 1.5
|
||||
let one: T = 1
|
||||
let half: T = 0.5
|
||||
let nrm = T.leastNormalMagnitude
|
||||
let lnm = T.leastNonzeroMagnitude
|
||||
let vectors: [(input: T, down: T, up: T, zero: T, away: T)] = [
|
||||
(-inf, -inf, -inf, -inf, -inf),
|
||||
(-gfm, -gfm, -gfm, -gfm, -gfm),
|
||||
(-big.nextUp, -big-1, -big-1, -big-1, -big-1),
|
||||
(-big, -big, -big, -big, -big),
|
||||
(-big.nextDown, -big, -big+1, -big+1, -big),
|
||||
(-two, -two, -two, -two, -two),
|
||||
(-two.nextDown, -two, -one, -one, -two),
|
||||
(-threeHalves.nextUp, -two, -one, -one, -two),
|
||||
(-threeHalves, -two, -one, -one, -two),
|
||||
(-threeHalves.nextDown, -two, -one, -one, -two),
|
||||
(-one.nextUp, -two, -one, -one, -two),
|
||||
(-one, -one, -one, -one, -one),
|
||||
(-one.nextDown, -one, 0, 0, -one),
|
||||
(-half.nextUp, -one, 0, 0, -one),
|
||||
(-half, -one, 0, 0, -one),
|
||||
(-half.nextDown, -one, 0, 0, -one),
|
||||
(-nrm, -one, 0, 0, -one),
|
||||
(-lnm, -one, 0, 0, -one),
|
||||
(-.zero, 0, 0, 0, 0),
|
||||
( .zero, 0, 0, 0, 0),
|
||||
( lnm, 0, one, 0, one),
|
||||
( nrm, 0, one, 0, one),
|
||||
( half.nextDown, 0, one, 0, one),
|
||||
( half, 0, one, 0, one),
|
||||
( half.nextUp, 0, one, 0, one),
|
||||
( one.nextDown, 0, one, 0, one),
|
||||
( one, one, one, one, one),
|
||||
( one.nextUp, one, two, one, two),
|
||||
( threeHalves.nextDown, one, two, one, two),
|
||||
( threeHalves, one, two, one, two),
|
||||
( threeHalves.nextUp, one, two, one, two),
|
||||
( two.nextDown, one, two, one, two),
|
||||
( two, two, two, two, two),
|
||||
( big.nextDown, big-1, big, big-1, big),
|
||||
( big, big, big, big, big),
|
||||
( big.nextUp, big+1, big+1, big+1, big+1),
|
||||
( gfm, gfm, gfm, gfm, gfm),
|
||||
( inf, inf, inf, inf, inf),
|
||||
]
|
||||
for vector in vectors {
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.down), vector.down)
|
||||
if vector.down == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.down).sign, vector.input.sign)
|
||||
}
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.up), vector.up)
|
||||
if vector.up == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.up).sign, vector.input.sign)
|
||||
}
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.towardZero), vector.zero)
|
||||
if vector.zero == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.towardZero).sign, vector.input.sign)
|
||||
}
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.awayFromZero), vector.away)
|
||||
if vector.away == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.awayFromZero).sign, vector.input.sign)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testRoundingDirected() {
|
||||
testRoundingDirected(Float.self)
|
||||
testRoundingDirected(Double.self)
|
||||
}
|
||||
|
||||
func testRoundingNearest<T: BinaryFloatingPoint>(_ type: T.Type) {
|
||||
let inf = T.infinity
|
||||
let gfm = T.greatestFiniteMagnitude
|
||||
let big: T = 1 / .ulpOfOne
|
||||
let two: T = 2
|
||||
let threeHalves: T = 1.5
|
||||
let one: T = 1
|
||||
let half: T = 0.5
|
||||
let nrm = T.leastNormalMagnitude
|
||||
let lnm = T.leastNonzeroMagnitude
|
||||
let vectors: [(input: T, down: T, up: T, zero: T, away: T, even: T)] = [
|
||||
(-inf, -inf, -inf, -inf, -inf, -inf),
|
||||
(-gfm, -gfm, -gfm, -gfm, -gfm, -gfm),
|
||||
(-big.nextUp, -big-1, -big-1, -big-1, -big-1, -big-1),
|
||||
(-big, -big, -big, -big, -big, -big),
|
||||
(-big.nextDown, -big, -big+1, -big+1, -big, -big),
|
||||
(-two, -two, -two, -two, -two, -two),
|
||||
(-two.nextDown, -two, -two, -two, -two, -two),
|
||||
(-threeHalves.nextUp, -two, -two, -two, -two, -two),
|
||||
(-threeHalves, -two, -one, -one, -two, -two),
|
||||
(-threeHalves.nextDown, -one, -one, -one, -one, -one),
|
||||
(-one.nextUp, -one, -one, -one, -one, -one),
|
||||
(-one, -one, -one, -one, -one, -one),
|
||||
(-one.nextDown, -one, -one, -one, -one, -one),
|
||||
(-half.nextUp, -one, -one, -one, -one, -one),
|
||||
(-half, -one, 0, 0, -one, 0),
|
||||
(-half.nextDown, 0, 0, 0, 0, 0),
|
||||
(-nrm, 0, 0, 0, 0, 0),
|
||||
(-lnm, 0, 0, 0, 0, 0),
|
||||
(-.zero, 0, 0, 0, 0, 0),
|
||||
( .zero, 0, 0, 0, 0, 0),
|
||||
( lnm, 0, 0, 0, 0, 0),
|
||||
( nrm, 0, 0, 0, 0, 0),
|
||||
( half.nextDown, 0, 0, 0, 0, 0),
|
||||
( half, 0, one, 0, one, 0),
|
||||
( half.nextUp, one, one, one, one, one),
|
||||
( one.nextDown, one, one, one, one, one),
|
||||
( one, one, one, one, one, one),
|
||||
( one.nextUp, one, one, one, one, one),
|
||||
( threeHalves.nextDown, one, one, one, one, one),
|
||||
( threeHalves, one, two, one, two, two),
|
||||
( threeHalves.nextUp, two, two, two, two, two),
|
||||
( two.nextDown, two, two, two, two, two),
|
||||
( two, two, two, two, two, two),
|
||||
( big.nextDown, big-1, big, big-1, big, big),
|
||||
( big, big, big, big, big, big),
|
||||
( big.nextUp, big+1, big+1, big+1, big+1, big+1),
|
||||
( gfm, gfm, gfm, gfm, gfm, gfm),
|
||||
( inf, inf, inf, inf, inf, inf),
|
||||
]
|
||||
for vector in vectors {
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrDown), vector.down, "\(vector.input).rounding(.toNearestOrDown)")
|
||||
if vector.down == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrDown).sign, vector.input.sign, "\(vector.input).rounding(.toNearestOrDown)")
|
||||
}
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrUp), vector.up, "\(vector.input).rounding(.toNearestOrUp)")
|
||||
if vector.up == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrUp).sign, vector.input.sign, "\(vector.input).rounding(.toNearestOrUp)")
|
||||
}
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrZero), vector.zero, "\(vector.input).rounding(.toNearestOrZero)")
|
||||
if vector.zero == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrZero).sign, vector.input.sign, "\(vector.input).rounding(.toNearestOrZero)")
|
||||
}
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrAway), vector.away, "\(vector.input).rounding(.toNearestOrAway)")
|
||||
if vector.away == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrAway).sign, vector.input.sign, "\(vector.input).rounding(.toNearestOrAway)")
|
||||
}
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrEven), vector.even, "\(vector.input).rounding(.toNearestOrEven)")
|
||||
if vector.even == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrEven).sign, vector.input.sign, "\(vector.input).rounding(.toNearestOrEven)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testRoundingNearest() {
|
||||
testRoundingNearest(Float.self)
|
||||
testRoundingNearest(Double.self)
|
||||
}
|
||||
|
||||
func testRoundingOdd<T: BinaryFloatingPoint>(_ type: T.Type) {
|
||||
let inf = T.infinity
|
||||
let gfm = T.greatestFiniteMagnitude
|
||||
let big: T = 1 / .ulpOfOne
|
||||
let two: T = 2
|
||||
let threeHalves: T = 1.5
|
||||
let one: T = 1
|
||||
let half: T = 0.5
|
||||
let nrm = T.leastNormalMagnitude
|
||||
let lnm = T.leastNonzeroMagnitude
|
||||
let vectors: [(input: T, odd: T)] = [
|
||||
(-inf, -inf),
|
||||
(-gfm, -gfm),
|
||||
(-big.nextUp, -big-1),
|
||||
(-big, -big),
|
||||
(-big.nextDown, -big+1),
|
||||
(-two, -two),
|
||||
(-two.nextDown, -one),
|
||||
(-threeHalves.nextUp, -one),
|
||||
(-threeHalves, -one),
|
||||
(-threeHalves.nextDown, -one),
|
||||
(-one.nextUp, -one),
|
||||
(-one, -one),
|
||||
(-one.nextDown, -one),
|
||||
(-half.nextUp, -one),
|
||||
(-half, -one),
|
||||
(-half.nextDown, -one),
|
||||
(-nrm, -one),
|
||||
(-lnm, -one),
|
||||
(-.zero, 0),
|
||||
( .zero, 0),
|
||||
( lnm, one),
|
||||
( nrm, one),
|
||||
( half.nextDown, one),
|
||||
( half, one),
|
||||
( half.nextUp, one),
|
||||
( one.nextDown, one),
|
||||
( one, one),
|
||||
( one.nextUp, one),
|
||||
( threeHalves.nextDown, one),
|
||||
( threeHalves, one),
|
||||
( threeHalves.nextUp, one),
|
||||
( two.nextDown, one),
|
||||
( two, two),
|
||||
( big.nextDown, big-1),
|
||||
( big, big),
|
||||
( big.nextUp, big+1),
|
||||
( gfm, gfm),
|
||||
( inf, inf)
|
||||
]
|
||||
for vector in vectors {
|
||||
XCTAssertEqual(vector.input.rounding(.toOdd), vector.odd, "\(vector.input).rounding(.toOdd)")
|
||||
if vector.odd == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.toOdd).sign, vector.input.sign, "\(vector.input).rounding(.toOdd)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testRoundingOdd() {
|
||||
testRoundingOdd(Float.self)
|
||||
testRoundingOdd(Double.self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//===--- SaturatingArithmeticTests.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
|
||||
// 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,155 @@
|
||||
//===--- ShiftTests.swift -------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2021-2024 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
|
||||
// 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
|
||||
if exact { expected = floor }
|
||||
else {
|
||||
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 .toNearestOrDown:
|
||||
let step = value.shifted(rightBy: count - 2, rounding: .toOdd)
|
||||
switch step & 0b11 {
|
||||
case 0b01: expected = floor
|
||||
case 0b10: expected = floor
|
||||
case 0b11: expected = ceiling
|
||||
default: preconditionFailure()
|
||||
}
|
||||
case .toNearestOrUp:
|
||||
let step = value.shifted(rightBy: count - 2, rounding: .toOdd)
|
||||
switch step & 0b11 {
|
||||
case 0b01: expected = floor
|
||||
case 0b10: expected = ceiling
|
||||
case 0b11: expected = ceiling
|
||||
default: preconditionFailure()
|
||||
}
|
||||
case .toNearestOrZero:
|
||||
let step = value.shifted(rightBy: count - 2, rounding: .toOdd)
|
||||
switch step & 0b11 {
|
||||
case 0b01: expected = floor
|
||||
case 0b10: expected = value > 0 ? floor : ceiling
|
||||
case 0b11: expected = ceiling
|
||||
default: preconditionFailure()
|
||||
}
|
||||
case .toNearestOrAway:
|
||||
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:
|
||||
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 .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: 2))")
|
||||
print("Expected: \(String(expected, radix: 2))")
|
||||
print("Observed: \(String(observed, radix: 2))")
|
||||
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: .toNearestOrUp)
|
||||
testRoundingShift(Int8.self, rounding: .toNearestOrDown)
|
||||
testRoundingShift(Int8.self, rounding: .toNearestOrZero)
|
||||
testRoundingShift(Int8.self, rounding: .toNearestOrAway)
|
||||
testRoundingShift(Int8.self, rounding: .toNearestOrEven)
|
||||
testRoundingShift(Int8.self, rounding: .toOdd)
|
||||
|
||||
testRoundingShift(UInt8.self, rounding: .down)
|
||||
testRoundingShift(UInt8.self, rounding: .up)
|
||||
testRoundingShift(UInt8.self, rounding: .towardZero)
|
||||
testRoundingShift(UInt8.self, rounding: .awayFromZero)
|
||||
testRoundingShift(UInt8.self, rounding: .toNearestOrUp)
|
||||
testRoundingShift(UInt8.self, rounding: .toNearestOrDown)
|
||||
testRoundingShift(UInt8.self, rounding: .toNearestOrZero)
|
||||
testRoundingShift(UInt8.self, rounding: .toNearestOrAway)
|
||||
testRoundingShift(UInt8.self, rounding: .toNearestOrEven)
|
||||
testRoundingShift(UInt8.self, rounding: .toOdd)
|
||||
|
||||
testRoundingShift(Int.self, rounding: .down)
|
||||
testRoundingShift(Int.self, rounding: .up)
|
||||
testRoundingShift(Int.self, rounding: .towardZero)
|
||||
testRoundingShift(Int.self, rounding: .awayFromZero)
|
||||
testRoundingShift(Int.self, rounding: .toNearestOrUp)
|
||||
testRoundingShift(Int.self, rounding: .toNearestOrDown)
|
||||
testRoundingShift(Int.self, rounding: .toNearestOrZero)
|
||||
testRoundingShift(Int.self, rounding: .toNearestOrAway)
|
||||
testRoundingShift(Int.self, rounding: .toNearestOrEven)
|
||||
testRoundingShift(Int.self, rounding: .toOdd)
|
||||
|
||||
testRoundingShift(UInt.self, rounding: .down)
|
||||
testRoundingShift(UInt.self, rounding: .up)
|
||||
testRoundingShift(UInt.self, rounding: .towardZero)
|
||||
testRoundingShift(UInt.self, rounding: .awayFromZero)
|
||||
testRoundingShift(UInt.self, rounding: .toNearestOrUp)
|
||||
testRoundingShift(UInt.self, rounding: .toNearestOrDown)
|
||||
testRoundingShift(UInt.self, rounding: .toNearestOrZero)
|
||||
testRoundingShift(UInt.self, rounding: .toNearestOrAway)
|
||||
testRoundingShift(UInt.self, rounding: .toNearestOrEven)
|
||||
testRoundingShift(UInt.self, rounding: .toOdd)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//===--- ArithmeticTests.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 XCTest
|
||||
import RealModule
|
||||
|
||||
@testable import QuaternionModule
|
||||
|
||||
final class ArithmeticTests: XCTestCase {
|
||||
|
||||
func testMultiplication<T: Real & SIMDScalar>(_ type: T.Type) {
|
||||
for value: T in [-3, -2, -1, +1, +2, +3] {
|
||||
let q = Quaternion<T>(real: value, imaginary: value, value, value)
|
||||
XCTAssertEqual(q * .one, q)
|
||||
XCTAssertEqual(q * 1, q)
|
||||
XCTAssertEqual(1 * q, q)
|
||||
}
|
||||
}
|
||||
|
||||
func testMultiplication() {
|
||||
testMultiplication(Float32.self)
|
||||
testMultiplication(Float64.self)
|
||||
}
|
||||
|
||||
func testDivision<T: Real & SIMDScalar>(_ type: T.Type) {
|
||||
for value: T in [-3, -2, -1, +1, +2, +3] {
|
||||
let q = Quaternion<T>(real: value, imaginary: value, value, value)
|
||||
XCTAssertEqual(q/q, .one)
|
||||
XCTAssertEqual(0/q, .zero)
|
||||
|
||||
for q2: Quaternion<T> in [-3, -2, -1, 0, +1, +2, +3] {
|
||||
XCTAssertEqual(q2/q, q2 * q.reciprocal!)
|
||||
}
|
||||
|
||||
for q2: T in [-3, -2, -1, +1, +2, +3] {
|
||||
XCTAssertEqual(q.divided(by: q2), q.multiplied(by: 1/q2))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDivision() {
|
||||
testDivision(Float32.self)
|
||||
testDivision(Float64.self)
|
||||
}
|
||||
|
||||
func testDivisionByZero<T: Real & SIMDScalar>(_ type: T.Type) {
|
||||
XCTAssertFalse((Quaternion<T>(real: 0, imaginary: 0, 0, 0) / Quaternion<T>(real: 0, imaginary: 0, 0, 0)).isFinite)
|
||||
XCTAssertFalse((Quaternion<T>(real: 1, imaginary: 1, 1, 1) / Quaternion<T>(real: 0, imaginary: 0, 0, 0)).isFinite)
|
||||
XCTAssertFalse((Quaternion<T>.infinity / Quaternion<T>(real: 0, imaginary: 0, 0, 0)).isFinite)
|
||||
XCTAssertFalse((Quaternion<T>.i / Quaternion<T>(real: 0, imaginary: 0, 0, 0)).isFinite)
|
||||
XCTAssertFalse((Quaternion<T>.j / Quaternion<T>(real: 0, imaginary: 0, 0, 0)).isFinite)
|
||||
XCTAssertFalse((Quaternion<T>.k / Quaternion<T>(real: 0, imaginary: 0, 0, 0)).isFinite)
|
||||
}
|
||||
|
||||
func testDivisionByZero() {
|
||||
testDivisionByZero(Float32.self)
|
||||
testDivisionByZero(Float64.self)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user