85 Commits
Author SHA1 Message Date
Stephen Canon e4b6b631fb Cleanup some swift 6 warnings. 2025-08-15 16:13:56 -04:00
Markus Winter 9a726a793e Remove AlgebraicField conformance on quaternions
Replace the (incorrect) conformance on AlgebraicField with a conformance to SignedNumeric
2025-08-14 21:50:12 -04:00
Markus Winter 98b9088b4c Replace argument with halfAngle 2025-08-14 21:50:11 -04:00
Markus Winter bb31091fdc Simplify implementation of halfAngle 2025-08-14 21:50:10 -04:00
Markus Winter 8a9ad438cb Rename halfAngle to argument and make it public 2025-08-14 21:50:08 -04:00
Joe SchulteandMarkus Winter 1bab0de693 Update Sources/QuaternionModule/README.md
Co-authored-by: Markus Winter <markus@wntr.me>
2025-08-14 21:50:07 -04:00
Joe Schulte 0b6cdc3844 Update Quaternions README.md 2025-08-14 21:50:05 -04:00
Joe Schulte c2184941ab Update README.md for importing Quaternions 2025-08-14 21:50:04 -04:00
Markus Winter e5ed4ac651 Fix header documentation 2025-08-14 21:50:02 -04:00
Markus Winter eeff10ed00 Sync quaternion module structure with complex module 2025-08-14 21:49:57 -04:00
Markus Winter aa376839bf Remove log and pow functions 2025-08-14 21:49:21 -04:00
Markus Winter bc944e79f0 Update trig tests 2025-08-14 21:49:20 -04:00
Markus Winter ff9f52fc92 Update implementations of sin/cos/tan 2025-08-14 21:49:19 -04:00
Markus Winter 360b914e9c First stab at log1p 2025-08-14 21:49:18 -04:00
Markus Winter e7c68b70b7 Add norms to imaginary helper 2025-08-14 21:49:17 -04:00
Markus Winter c142bcedfe Add more comments to pow like functions 2025-08-14 21:49:15 -04:00
Markus Winter e8940b786e Fix sign of tan special case and add more comments 2025-08-14 21:49:13 -04:00
Markus Winter 5ea4f613d3 Fix todos and update comments 2025-08-14 21:49:12 -04:00
Markus Winter f99c42cacb Fix a typo in the comments 2025-08-14 21:49:10 -04:00
Markus Winter 9d7b668a10 Add log to quaternion 2025-08-14 21:49:09 -04:00
Markus Winter 42c26ee85d Add pow, sqrt and root to quaternions 2025-08-14 21:49:07 -04:00
Markus Winter 844aff56c5 Add cos, sin and tan to quaternions 2025-08-14 21:49:06 -04:00
Markus Winter b197152494 Add cosh, sinh and tanh to quaternions 2025-08-14 21:49:04 -04:00
Markus Winter 85281cc937 Add expMinusOne to quaternions 2025-08-14 21:49:03 -04:00
Markus Winter 52bb20ad8f Add more comments and clean up comments and variable names 2025-08-14 21:49:02 -04:00
Markus Winter af266bb9d9 Add an early skip when calculating the length in exp 2025-08-14 21:49:00 -04:00
Markus Winter 92af6727ee Add exponential function to quaternions 2025-08-14 21:48:58 -04:00
Markus Winter e9dfc766be Move imaginary helper functions into a distinct file 2025-08-14 21:48:56 -04:00
Markus Winter 211b94fb16 Add isReal to quaternion and refined comments on isPure 2025-08-14 21:48:51 -04:00
Markus Winter ea46df54b9 Account for over and underflow in quaternion length 2025-08-14 21:48:17 -04:00
Markus Winter fda8513ec0 Prevents infinite loop in quaternion act on zero lanes 2025-08-14 21:48:13 -04:00
Markus Winter 1b541a1581 Update transformation APIs to use the new SIMD initializer on quaternion 2025-08-14 21:47:29 -04:00
Markus Winter acbdeeaa3d Update Transformation.md of quaternions 2025-08-14 21:47:27 -04:00
Markus Winter 4b8ae5dd44 Update underflow tests for quaternions 2025-08-14 21:47:26 -04:00
Markus Winter daff65f930 Account for underflow in quaternion rotation 2025-08-14 21:47:24 -04:00
Markus Winter 22f1901206 Account for over/underflow on halfAngle and axis calculations 2025-08-14 21:47:23 -04:00
Markus Winter 46a25b6d61 Update angle/axis tests on quaternion 2025-08-14 21:47:21 -04:00
Markus Winter 111d482833 Update polar initializer to assume a unit axis parameter 2025-08-14 21:47:19 -04:00
Markus Winter 5c4bce2635 Add length parameter to angle/axis initializer 2025-08-14 21:47:18 -04:00
Markus Winter 31bf80751a Update documentation of act(on:) 2025-08-14 21:47:17 -04:00
Markus Winter bd99cdeffb Add links to documentation and fix typo in comment 2025-08-14 21:47:15 -04:00
Markus Winter 5b96cba10e Rename half angle with phase to make it more distinct 2025-08-14 21:47:15 -04:00
Markus Winter e99724f03b Add transformation documentation 2025-08-14 21:47:13 -04:00
Markus Winter 015c9bd961 Add transformation tests to quaternion 2025-08-14 21:47:11 -04:00
Markus Winter 896142fc32 Add method to rotate a vector by a quaternion 2025-08-14 21:47:10 -04:00
Markus Winter 528fb9daf1 Add transformation representations 2025-08-14 21:47:08 -04:00
Markus Winter ab8c3d9ddb Exposes QuaternionModule as part of the Numerics module 2025-08-14 21:47:02 -04:00
Markus Winter 1fe4ce7b1f Update documentation on 3D transformations 2025-08-14 21:46:37 -04:00
Markus Winter e50371b030 Rename transformEquals to equals(as3DTransform:) 2025-08-14 21:46:35 -04:00
Markus Winter 39bd408dad Remove duplicated comment on equatable 2025-08-14 21:46:33 -04:00
Markus Winter 06341f3bea Fix invalid canonicalizedTransform for quaternions with negative real 2025-08-14 21:46:33 -04:00
Markus Winter 1ded0b7c56 Update transformation hashing and equality tests 2025-08-14 21:46:31 -04:00
Markus Winter fb718d6f74 Rename transformCanonicalized to canonicalizedTransform 2025-08-14 21:46:30 -04:00
Markus Winter a5c6f27f26 Rename rotationEquals to transformationEquals on Quaternion 2025-08-14 21:46:29 -04:00
Markus Winter a5478a7885 Change hashing behavior of Quaternion to use the canonical form 2025-08-14 21:46:28 -04:00
Markus Winter 1b1c7cddf5 Add canonicalized transform representation to Quaternion 2025-08-14 21:46:27 -04:00
Markus Winter e7aa60d838 Add canonicalized quaternion representation 2025-08-14 21:46:25 -04:00
Markus Winter 7896ee2eef Update rotation documentation on Quaternion 2025-08-14 21:46:24 -04:00
Markus Winter e5b84606f5 Update rotation equals documentation on Quaternion 2025-08-14 21:46:23 -04:00
Markus Winter 273c6f7e54 Refine Hashable and Equatable on Quaternion 2025-08-14 21:46:23 -04:00
Markus Winter 8ec29a889b Change initializer on quaternion to be more explicit 2025-08-14 21:46:22 -04:00
Markus Winter 03e1f5ba6b Split static imaginary units on quaternion 2025-08-14 21:46:20 -04:00
Markus Winter 4188358cb4 Change quaternion initializer to more explicit variants 2025-08-14 21:46:19 -04:00
Markus Winter fcab66685d Use shorthand isZero operator on SIMD storage of quaternion 2025-08-14 21:46:17 -04:00
Markus Winter bb05e58135 Fix isNormal on quaternion 2025-08-14 21:46:15 -04:00
Markus Winter 5e1de5d8e0 Change the conjugate implementation on quaternion 2025-08-14 21:46:13 -04:00
Markus Winter 9b7cbcdb4a Flip storage order on quaternion to real part last
This commit will also replace references to a,b,c,d with r,x,y,z respectivly.
2025-08-14 21:46:12 -04:00
Markus Winter 43932b1cfe Fix parameter on multiplication header 2025-08-14 21:46:11 -04:00
Markus Winter 09c038ed3b Replace imaginary setter on quaternion with SIMD variant 2025-08-14 21:46:09 -04:00
Markus Winter 69100e86b4 Update documentation on quaternions 2025-08-14 21:46:07 -04:00
Markus Winter 2bf3285bde Make type casts explicit in quaternion tests 2025-08-14 21:46:06 -04:00
Markus Winter 4dd08f1c10 Remove debug print in quaternion tests 2025-08-14 21:46:05 -04:00
Markus Winter 00e141fb19 Update quaternion documentation 2025-08-14 21:46:04 -04:00
Markus Winter 000df70c1b Update quaternion tests 2025-08-14 21:46:02 -04:00
Markus Winter bdd9b2f4bc Update README for inclusion of quaternioin module 2025-08-14 21:45:56 -04:00
Markus Winter 2f438bd6c9 Add more basic arithmetic tests to quaternions 2025-08-14 21:45:03 -04:00
Markus Winter 57fc357bfc Fix invalid multiplication of quaternions 2025-08-14 21:45:01 -04:00
Markus Winter 7fb314a581 Update header documentation on quaternion 2025-08-14 21:45:00 -04:00
Markus Winter f1e353ec03 Split quaternion norms from polar implementation 2025-08-14 21:44:59 -04:00
Markus Winter e2ad631369 Update README in quaaternion module 2025-08-14 21:44:57 -04:00
Markus Winter e29fa04051 Add first quaternion arithmetic tests 2025-08-14 21:44:56 -04:00
Markus Winter 22ec1b960b Add property tests on quaternions 2025-08-14 21:44:54 -04:00
Markus Winter 99a7c6113d Fix typo in Quaternion Documentation 2025-08-14 21:44:52 -04:00
Markus Winter 15fee28c1f Update quaternions 2025-08-14 21:44:50 -04:00
Markus Winter dd731f3362 Add quaternion module 2025-08-14 21:44:45 -04:00
41 changed files with 2524 additions and 507 deletions

No files matched your search

-5
View File
@@ -1,8 +1,5 @@
name: Pull request
permissions:
contents: read
on:
pull_request:
types: [opened, reopened, synchronize]
@@ -12,11 +9,9 @@ jobs:
name: Test
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
with:
enable_macos_checks: true
windows_exclude_swift_versions: '[{"swift_version": "5.9"}]'
enable_wasm_sdk_build: true
wasm_sdk_build_command: swift build --target Numerics
enable_freebsd_checks: true
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
+1 -1
View File
@@ -7,7 +7,7 @@ Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
#]]
cmake_minimum_required(VERSION 3.29)
cmake_minimum_required(VERSION 3.16)
project(swift-numerics
LANGUAGES Swift)
+21 -7
View File
@@ -20,11 +20,22 @@ let package = Package(
products: [
.library(name: "ComplexModule", targets: ["ComplexModule"]),
.library(name: "Numerics", targets: ["Numerics"]),
.library(name: "QuaternionModule", targets: ["QuaternionModule"]),
.library(name: "RealModule", targets: ["RealModule"]),
],
targets: [
// MARK: - Public API
.target(
name: "Numerics",
dependencies: [
"ComplexModule",
"IntegerUtilities",
"QuaternionModule",
"RealModule"],
exclude: excludedFilenames
),
.target(
name: "ComplexModule",
dependencies: ["RealModule"],
@@ -38,18 +49,15 @@ let package = Package(
),
.target(
name: "Numerics",
dependencies: ["ComplexModule", "IntegerUtilities", "RealModule"],
exclude: excludedFilenames
name: "QuaternionModule",
dependencies: ["RealModule"],
exclude: ["README.md", "Transformation.md"]
),
.target(
name: "RealModule",
dependencies: ["_NumericsShims"],
exclude: excludedFilenames,
swiftSettings: [
.enableExperimentalFeature("BuiltinModule")
],
linkerSettings: [
.linkedLibrary("m", .when(platforms: [.linux, .android]))
]
@@ -76,7 +84,7 @@ let package = Package(
.testTarget(
name: "IntegerUtilitiesTests",
dependencies: ["IntegerUtilities", "_TestSupport"],
dependencies: ["_TestSupport"],
exclude: ["CMakeLists.txt"]
),
@@ -84,6 +92,12 @@ let package = Package(
name: "RealTests",
dependencies: ["_TestSupport"],
exclude: ["CMakeLists.txt"]
),
.testTarget(
name: "QuaternionTests",
dependencies: ["_TestSupport"],
exclude: ["CMakeLists.txt"]
)
]
)
+3 -2
View File
@@ -42,7 +42,7 @@ To use Swift Numerics in a SwiftPM project:
1. Add the following line to the dependencies in your `Package.swift` file:
```swift
.package(url: "https://github.com/apple/swift-numerics", from: "1.0.0"),
.package(url: "https://github.com/apple/swift-numerics", branch: "Quaternions"),
```
2. Add `Numerics` as a dependency for your target:
@@ -105,7 +105,8 @@ Questions about how to use Swift Numerics modules, or issues that are not clearl
1. [`RealModule`](Sources/RealModule/README.md)
2. [`ComplexModule`](Sources/ComplexModule/README.md)
3. [`IntegerUtilities`](Sources/IntegerUtilities/README.md) (on main only, not yet present in a released tag)
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
@@ -155,17 +155,9 @@ extension Complex: AlgebraicField {
///
/// Error Bounds:
///
/// Unlike real types, with Complex types, _if no underflow occurs in
/// computing the reciprocal_, replacing division with multiplication by
/// this value does not perturb the result. Note that this condition is
/// not the same as `reciprocal` returning a non-nil value. If the `real`
/// and `imaginary` components are poorly scaled with respect to each other,
/// one component of `reciprocal` may underflow while the other component
/// is normal, resulting in a non-nil `reciprocal`.
///
/// We return a non-nil reciprocal in this case because it still
/// satisfies the accuracy expectations of `reciprocal` in any Complex
/// norm (but not componentwise).
/// 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
@@ -12,9 +12,6 @@
import RealModule
// FloatingPoint does not refine Codable, so this is a conditional conformance.
#if compiler(>=6.0)
@_unavailableInEmbedded
#endif
extension Complex: Decodable where RealType: Decodable {
public init(from decoder: Decoder) throws {
var unkeyedContainer = try decoder.unkeyedContainer()
@@ -24,9 +21,6 @@ extension Complex: Decodable where RealType: Decodable {
}
}
#if compiler(>=6.0)
@_unavailableInEmbedded
#endif
extension Complex: Encodable where RealType: Encodable {
public func encode(to encoder: Encoder) throws {
var unkeyedContainer = encoder.unkeyedContainer()
@@ -32,6 +32,12 @@
// 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
@@ -141,10 +147,7 @@ extension Complex: ElementaryFunctions {
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(signOf: z.x, magnitudeOf: 1) * RealType.sin(z.y)
)
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)
@@ -174,12 +177,9 @@ extension Complex: ElementaryFunctions {
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(signOf: z.x, magnitudeOf: RealType.cos(z.y)),
RealType.sin(z.y)
)
let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))
let firstScale = RealType.exp(z.x.magnitude/2)
let secondScale = firstScale/2
let secondScale = RealType(signOf: z.x, magnitudeOf: firstScale/2)
return phase.multiplied(by: firstScale).multiplied(by: secondScale)
}
return Complex(
@@ -16,9 +16,6 @@ extension Complex: CustomStringConvertible {
}
}
#if compiler(>=6.0)
@_unavailableInEmbedded
#endif
extension Complex: CustomDebugStringConvertible {
public var debugDescription: String {
"Complex<\(RealType.self)>(\(String(reflecting: x)), \(String(reflecting: y)))"
@@ -1,140 +0,0 @@
# Notes on Complex Division
A discussion of the algorithms used to implement complex division
## Overview
How does compute the quotient of two complex numbers z/w? The naïve schoolbook
answer is to turn it into complex multiplication by scaling both numerator and
denominator by the conjugate of w: z/w = (zw̅)/(ww̅) = (zw̅)/|w|². Translated
directly into swift, this expression would become:
```swift
extension Complex {
func naïveDivision(_ z: Complex, _ w: Complex) -> Complex {
(z * w.conjugate).divded(by: w.lengthSquared)
}
}
```
If both z and w are both "well-scaled" (i.e. their exponents are neither very
large nor very small), then this expression works reasonably well when
evaluated in floating-point. Cancellation may occur in the computation of
either the real or the imaginary part of the zw̅ term, but not in both
simultaneously, so the relative error in any vector norm is bounded by a
small multiple of machine epsilon.
However, if z or w is not well-scaled, then either zw̅ or |w|² or both may
underflow or overflow, even when the actual quotient may be perfectly
representable. For example, if we have
```swift
let a: Float = 1.84467441E+19 // large, but not outrageously large
let z = Complex(a, a)
let w = z
```
then both `(z * w.conjugate)` and `w.lengthSquared` overflow, and the result
of `naïveDivision` is `(NaN, NaN)` even though the actual mathematical quotient
is 1.
At least `(NaN, NaN)` is obviously wrong; when intermediate results underflow
instead of overflow, we can instead get bogus results that are not obvious at
all. For example:
```swift
let z = Complex<Float>(imaginary: 6.6174449e-24)
let w = Complex<Float>(5.29395592e-23, 3.97046694e-23)
let q = naïveDivision(z, w)
```
`q` is computed as `(0.666666686, 0.666666686)`, which looks like a reasonable
result, but the exact `z/w` would be `(0.6, 0.8)`; both the phase and magnitude
of the computed result have large errors, and there is no indication that
anything went wrong.
## Complex division in Swift Numerics
### Goals
Programming languages and libraries have developed a variety of approaches to
handle this problem. Swift Numerics' approach is somewhat novel, so I will
first lay out the considerations that lead us to it.
1. Division should be reasonably fast, and permit compiler optimizations that
make it faster. So long as all inputs are well-scaled, it should not be
much slower than multiplication.
2. Division should have the same error characteristics as multiplication;
componentwise error bounds and correct rounding are non-goals. Good error
bounds in a complex norm are what matters.
3. Division should not be any more sensitive to undue overflow or underflow
than multiplication is (i.e. it is OK for results very near the boundaries
to overflow or underflow even though the exact result would be
representable, but results that are far from those boundaries should always
be computed with good accuracy).
### Fast path
These considerations lead us to a first draft of our implementation; since we
want division to be roughly like multiplication, we will "simply" turn it into
a multiplication via the naïve formula:
```swift
public static func /(z: Complex, w: Complex) -> Complex {
let lenSq = w.lengthSquared
guard lenSq.isNormal else { /* naive formula will not work */ }
return z * w.conjugate.divided(by: lenSq)
}
```
if `lenSq` can be computed without overflow or underflow, then
`w.conjugate.divided(by: lenSq)` is a (rounded) reciprocal `1/w`, and so
multiplying that by `z` satisfies the goals that we laid out above. Note
in particular that if we are dividing multiple values by a single divisor,
the reciprocal is a constant, and this check only has to happen once.
That leaves us just needing to figure out what to do when the reciprocal
is not well-scaled.
### Slow path
When an approximate reciprocal for the divisor is not representable, we use
a scaling algorithm adapted from Doug Priest's "Efficient Scaling for
Complex Division". In hand-wavy form, Priest's idea is:
1. choose a scale factor s ~ |w|^(-¾)
2. let wʹ ← sw
2. let zʹ ← sz
Note that we _can_ compute a reciprocal for wʹ without overflow or underflow,
because |wʹ| ~ |w|^(¼), so |wʹ²| ~ |w|^(½) and so |w̅ʹ/wʹ²| ~ |w|^(-¼).¹
To compute z/w, we compute zʹ/wʹ. sz might overflow or underflow, but only
if the final computation would overflow or underflow anyway. This is because
division by w is a dilation combined with a rotation; because |w| is bounded
away from 1, the multiplication by s is a dilation if and only if division
by w is also dilation (this is where we diverge from Priest; because he
doesn't have a fast-path for well-scaled w, he has to handle this case
carefully).
Like Priest, we arrange for s to be a power of the radix with the desired
scale, which makes the computation of wʹ and zʹ exact (unless zʹ over- or
underflows). This achieves one more desirable property: barring underflow,
rescaling both w and z by the radix does not change results when we move
between the fast and slow algorithms.
Instead of `zʹ/wʹ = zʹ(w̅ʹ/|wʹ|²)`, Priest uses `(zw″)/|wʹ|²`. There isn't
a strong reason to favor one or the other numerically, but our formulation
lets us preserve `z/w = z * w.reciprocal` under scaling by powers of the
radix (up to the underflow boundary), which is somewhat nice to have, and
allows us to extract a little bit more ILP in some cases.
----
### Notes
¹ This analysis fails for types like Float16 where the number of
significand bits is on the order of the greatest exponent because the desired
s may not be representable if w is subnormal. Note that the problem is _only_
in the representation of s, so we can handle this case by rescaling in two
steps.
+1 -1
View File
@@ -163,7 +163,7 @@ public enum RoundingRule {
/// - `(-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 `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
@@ -27,8 +27,9 @@ extension BinaryInteger {
/// // is odd.
/// 3.shifted(rightBy: 1, rounding: .toOdd)
///
/// // 6/4 = 1.5, so the tie is broken in favor of the even value 2.
/// 6.shifted(rightBy: 2, rounding: .toNearestOrEven)
/// // 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)
@@ -152,8 +153,9 @@ extension BinaryInteger {
/// // is odd.
/// 3.shifted(rightBy: 1, rounding: .toOdd)
///
/// // 6/4 = 1.5, so the tie is broken in favor of the even value 2.
/// 6.shifted(rightBy: 2, rounding: .toNearestOrEven)
/// // 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)
+1
View File
@@ -13,3 +13,4 @@
@_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])
}
}
+201
View File
@@ -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))"
}
}
+302
View File
@@ -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))
}
}
+30
View File
@@ -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.
+39
View File
@@ -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 dvantages 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,228 +0,0 @@
# Approximate Equality
Test whether two values agree within a specified tolerance.
## Overview
In numerical computing, mathematical equality often diverges from computed
equality. Rounding in floating-point arithmetic is one common cause, but many
nontrivial numerical algorithms also have inherent truncation or discretization
errors, and empirical measurements carry uncertainty to begin with. In these
scenarios, exact equality (`==`) may be too strict or inappropriate, and an
approximate equality comparison is needed instead. Conversely, exact equality
remains entirely appropriate when checking for identical values, sentinel states,
or integers.
`RealModule` provides a family of `isApproximatelyEqual` methods that test
whether two values are within a tolerance of one another. They are available
on any `Numeric` type whose `Magnitude` is a `FloatingPoint` type (including
`Float`, `Double`, and `Complex`), and a more general form is available on any
`AdditiveArithmetic` type for which you can supply a norm.
```swift
import Numerics
let x = 0.1 + 0.2
x == 0.3 // false
x.isApproximatelyEqual(to: 0.3) // true
```
### Comparing non-Numeric types with a custom norm
The approximate equality API is not limited to scalar numbers or `Numeric`
types. Any type conforming to `AdditiveArithmetic` can be compared once you
supply a suitable norm function mapping differences to a `FloatingPoint`
magnitude.
For example, consider a 2D geometric vector or point type representing spatial
displacements:
```swift
struct Vector2D: AdditiveArithmetic, Equatable {
var x: Double
var y: Double
static var zero: Vector2D {
Vector2D(x: 0, y: 0)
}
static func + (lhs: Vector2D, rhs: Vector2D) -> Vector2D {
Vector2D(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
static func - (lhs: Vector2D, rhs: Vector2D) -> Vector2D {
Vector2D(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
}
// Compare vectors using the Euclidean distance (L2 norm):
let v1 = Vector2D(x: 1.0, y: 2.0)
let v2 = Vector2D(x: 1.000000001, y: 1.999999999)
let areClose = v1.isApproximatelyEqual(
to: v2,
absoluteTolerance: 1e-6,
norm: { v in (v.x * v.x + v.y * v.y).squareRoot() }
)
// areClose == true
```
Because `Vector2D` is not `Numeric` (it does not define multiplication of
vectors to produce a vector), it cannot use the standard `Numeric.isApproximatelyEqual`
overload. However, because vector subtraction forms a difference vector in an
additive space, the general `AdditiveArithmetic` overload evaluates the custom
norm directly.
### Choosing a tolerance
The simplest method uses a _relative_ tolerance:
```swift
public func isApproximatelyEqual(
to other: Self,
relativeTolerance: Magnitude = Magnitude.ulpOfOne.squareRoot(),
norm: (Self) -> Magnitude = \.magnitude
) -> Bool
```
Two finite values compare equal when
```
norm(self - other) <= relativeTolerance * scale
```
where `scale` is `max(norm(self), norm(other), .leastNormalMagnitude)`.
Because the bound grows with the size of the operands, a single relative
tolerance works across a wide range of magnitudes.
The default tolerance is `.ulpOfOne.squareRoot()`, which corresponds to
expecting about half of the available digits in the result to be correct. This
is the usual rule of thumb in numerical analysis when you have no other
information about the computation, but it is not appropriate for every use
case, so you should pass an explicit value when you can estimate how much error
your computation introduces.
#### Absolute versus relative tolerance
A relative tolerance scales with the magnitude of the operands, making it
effective across numbers of very small or very large scale. However, a pure
relative tolerance fails when comparing against zero or numbers much smaller
than the surrounding computation, because `scale` approaches zero and shrinks
the allowable difference to near zero.
To handle values near zero, use the overload that also accepts an _absolute_
tolerance:
```swift
public func isApproximatelyEqual(
to other: Self,
absoluteTolerance: Magnitude,
relativeTolerance: Magnitude = 0
) -> Bool
```
Two finite values compare equal when _either_ the absolute or the relative
bound is satisfied:
```
(self - other).magnitude <= absoluteTolerance
```
or
```
(self - other).magnitude <= relativeTolerance * scale
```
where `scale` is `max(self.magnitude, other.magnitude)`.
When choosing values:
- Use **relative tolerance** when the allowed error is proportional to the
magnitude of the values being computed (e.g. general floating-point arithmetic).
- Use **absolute tolerance** when values can be near zero, or when the error
is independent of the scale of the inputs (e.g. fixed measurement resolution).
- Supplying both allows the absolute tolerance to govern comparisons near
zero, while the relative tolerance takes over once values grow beyond
`absoluteTolerance / relativeTolerance`.
Setting `absoluteTolerance == relativeTolerance` is typically appropriate only
when values are expected to lie on an integral or unit-spaced grid due to
algorithmic considerations (where `1.0` represents the base unit scale). For
general computations, the two tolerances should be chosen independently based on
the scale of the problem and the expected precision.
### Special values
The comparison follows the same conventions as `FloatingPoint`:
```swift
Double.nan.isApproximatelyEqual(to: .nan) // false
Double.infinity.isApproximatelyEqual(to: .infinity) // true
(0.0).isApproximatelyEqual(to: -0.0) // true
```
A NaN is never approximately equal to anything, including itself, and a finite
value is never approximately equal to an infinity. Equal values always compare
approximately equal regardless of the tolerance, so infinities compare equal to
themselves and `+0` compares equal to `-0`.
### Comparing other types with a custom norm
The methods above measure the difference between two values using the
`.magnitude` property. Sometimes you want to use a different
[norm](https://en.wikipedia.org/wiki/Norm_(mathematics)). The most general
overload, defined on `AdditiveArithmetic`, lets you supply one:
```swift
public func isApproximatelyEqual<Magnitude>(
to other: Self,
absoluteTolerance: Magnitude,
relativeTolerance: Magnitude = 0,
norm: (Self) -> Magnitude
) -> Bool
where Magnitude: FloatingPoint
```
#### Complex magnitude vs other norms
For complex numbers, the default norm is `\.magnitude`, which computes the
infinity-norm (`max(abs(real), abs(imaginary))`).
A major numerical advantage of `\.magnitude` for complex values is that it is
finite and non-zero for any finite non-zero value:
- Unlike Euclidean length (`\.length`, $\sqrt{x^2 + y^2}$), which can overflow
to infinity if $x^2 + y^2$ exceeds the maximum representable finite value or
underflow if both components are tiny, `\.magnitude` never overflows or underflows
for finite numbers.
- It avoids intermediate squaring, square roots, or the complex scaling logic of
`hypot`, making it robust even when handling very poorly scaled values.
If you specifically need to test whether a complex number lies inside a circular
disk of radius `0.001` centered at `1 + 0i` rather than a square box, you can
pass the Euclidean length as the norm:
```swift
import ComplexModule
z.isApproximatelyEqual(
to: 1,
absoluteTolerance: 0.001,
norm: \.length
)
```
## Mathematical properties
For any fixed tolerance, approximate equality is _reflexive_ on
non-exceptional values and _symmetric_: if `a` is approximately equal to `b`,
then `b` is approximately equal to `a`.
It is **not transitive**. `a` can be approximately equal to `b`, and `b` to
`c`, while `a` and `c` differ by more than the tolerance. Approximate equality
is therefore **not** an equivalence relation, even when restricted to
non-exceptional values. For this reason you must not use it to implement a
conformance to `Equatable`: doing so would violate the invariants that generic
code written against `Equatable` relies on.
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).
@@ -26,7 +26,3 @@ 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.
``RealModule`` also provides `isApproximatelyEqual` methods for comparing
floating-point values up to a tolerance, which is almost always what you want
instead of an exact `==` comparison. See <doc:ApproximateEquality> for details.
-9
View File
@@ -10,7 +10,6 @@
//===----------------------------------------------------------------------===//
import _NumericsShims
import Builtin
extension Double: Real {
@_transparent
@@ -223,19 +222,11 @@ extension Double: Real {
@_transparent
public static func _relaxedAdd(_ a: Double, _ b: Double) -> Double {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Double(Builtin.fadd_relaxed_FPIEEE64(a._value, b._value))
#else
_numerics_relaxed_add(a, b)
#endif
}
@_transparent
public static func _relaxedMul(_ a: Double, _ b: Double) -> Double {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Double(Builtin.fmul_relaxed_FPIEEE64(a._value, b._value))
#else
_numerics_relaxed_mul(a, b)
#endif
}
}
-9
View File
@@ -10,7 +10,6 @@
//===----------------------------------------------------------------------===//
import _NumericsShims
import Builtin
extension Float: Real {
@_transparent
@@ -196,19 +195,11 @@ extension Float: Real {
@_transparent
public static func _relaxedAdd(_ a: Float, _ b: Float) -> Float {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Float(Builtin.fadd_relaxed_FPIEEE32(a._value, b._value))
#else
_numerics_relaxed_addf(a, b)
#endif
}
@_transparent
public static func _relaxedMul(_ a: Float, _ b: Float) -> Float {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Float(Builtin.fmul_relaxed_FPIEEE32(a._value, b._value))
#else
_numerics_relaxed_mulf(a, b)
#endif
}
}
+2 -12
View File
@@ -10,7 +10,6 @@
//===----------------------------------------------------------------------===//
import _NumericsShims
import Builtin
// Float16 is only available on macOS when targeting arm64.
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
@@ -174,27 +173,18 @@ extension Float16: Real {
}
#endif
#if !arch(wasm32) || hasFeature(BuiltinRelaxedFP)
#if !arch(wasm32)
// WASM doesn't have _Float16 on the C side, so we can't define the C hooks
// that these use. However, if we have BuiltinRelaxedFP we can use builtins
// to do this directly without needing the C hooks.
// that these use. TODO: implement these as Swift builtins instead.
@_transparent
public static func _relaxedAdd(_ a: Float16, _ b: Float16) -> Float16 {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Float16(Builtin.fadd_relaxed_FPIEEE16(a._value, b._value))
#else
_numerics_relaxed_addf16(a, b)
#endif
}
@_transparent
public static func _relaxedMul(_ a: Float16, _ b: Float16) -> Float16 {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Float16(Builtin.fmul_relaxed_FPIEEE16(a._value, b._value))
#else
_numerics_relaxed_mulf16(a, b)
#endif
}
#endif
}
-9
View File
@@ -10,7 +10,6 @@
//===----------------------------------------------------------------------===//
import _NumericsShims
import Builtin
// Restrict extension to platforms for which Float80 exists.
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
@@ -169,20 +168,12 @@ extension Float80: Real {
@_transparent
public static func _relaxedAdd(_ a: Float80, _ b: Float80) -> Float80 {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Float80(Builtin.fadd_relaxed_FPIEEE80(a._value, b._value))
#else
_numerics_relaxed_addl(a, b)
#endif
}
@_transparent
public static func _relaxedMul(_ a: Float80, _ b: Float80) -> Float80 {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Float80(Builtin.fmul_relaxed_FPIEEE80(a._value, b._value))
#else
_numerics_relaxed_mull(a, b)
#endif
}
}
#endif
-21
View File
@@ -68,30 +68,9 @@ This gives us an implementation that works for `Float`, `Double`, and `Float80`
When new basic floating-point types are added to Swift, like `Float16` or `Float128`, it will work for them as well.
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.
## Approximate equality
`RealModule` provides a family of `isApproximatelyEqual` methods that test
whether two values agree up to a relative or absolute tolerance:
```swift
import Numerics
let x = 0.1 + 0.2
x == 0.3 // false
x.isApproximatelyEqual(to: 0.3) // true
```
These methods are available on any `Numeric` type whose `Magnitude` is a
`FloatingPoint` type, with a more general form on `AdditiveArithmetic` that
takes a custom norm.
See the [Approximate Equality][ApproximateEquality] article for a discussion of
how to choose a tolerance, how special values are handled, and why approximate
equality must not be used to implement `Equatable`.
### Dependencies:
- The C standard math library (`libm`) via the `_NumericsShims` target.
[ApproximateEquality]: Documentation.docc/ApproximateEquality.md
[ErrorFunction]: https://en.wikipedia.org/wiki/Error_function
[GammaFunction]: https://en.wikipedia.org/wiki/Gamma_function
[SE-0246]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0246-mathable.md
@@ -180,13 +180,7 @@ final class ElementaryFunctionTests: XCTestCase {
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))
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) {
@@ -218,12 +212,6 @@ final class ElementaryFunctionTests: XCTestCase {
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))
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
@@ -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)
}
}
@@ -0,0 +1,252 @@
//===--- ElementaryFunctionTests.swift ------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
import RealModule
import _TestSupport
@testable import QuaternionModule
final class ElementaryFunctionTests: XCTestCase {
// MARK: - exp-like functions
func testExp<T: Real & FixedWidthFloatingPoint & SIMDScalar>(_ type: T.Type) {
// exp(0) = 1
XCTAssertEqual(1, Quaternion<T>.exp(Quaternion(real: 0, imaginary: 0, 0, 0)))
XCTAssertEqual(1, Quaternion<T>.exp(Quaternion(real:-0, imaginary: 0, 0, 0)))
XCTAssertEqual(1, Quaternion<T>.exp(Quaternion(real:-0, imaginary:-0,-0,-0)))
XCTAssertEqual(1, Quaternion<T>.exp(Quaternion(real: 0, imaginary:-0,-0,-0)))
// In general, exp(Quaternion(r,0,0,0)) should be exp(r), but that breaks
// down when r is infinity or NaN, because we want all non-finite
// quaternions to be semantically a single point at infinity. This is fine
// for most inputs, but exp(Quaternion(-.infinity, 0, 0, 0)) would produce
// 0 if we evaluated it in the usual way.
XCTAssertFalse(Quaternion<T>.exp(Quaternion(real: .infinity, imaginary: .zero)).isFinite)
XCTAssertFalse(Quaternion<T>.exp(Quaternion(real: .infinity, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.exp(Quaternion(real: 0, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.exp(Quaternion(real: -.infinity, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.exp(Quaternion(real: -.infinity, imaginary: .zero)).isFinite)
XCTAssertFalse(Quaternion<T>.exp(Quaternion(real: -.infinity, imaginary: -.infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.exp(Quaternion(real: 0, imaginary: -.infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.exp(Quaternion(real: .infinity, imaginary: -.infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.exp(Quaternion(real: .nan, imaginary: .nan)).isFinite)
XCTAssertFalse(Quaternion<T>.exp(Quaternion(real: .infinity, imaginary: .nan)).isFinite)
XCTAssertFalse(Quaternion<T>.exp(Quaternion(real: .nan, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.exp(Quaternion(real: -.infinity, imaginary: .nan)).isFinite)
XCTAssertFalse(Quaternion<T>.exp(Quaternion(real: .nan, imaginary: -.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 = Quaternion<T>.exp(Quaternion(real: x, imaginary: SIMD3(.pi/4, 0, 0)))
let mag = T.greatestFiniteMagnitude/T.sqrt(2) * (9/8)
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
XCTAssert(huge.imaginary.x.isApproximatelyEqual(to: mag))
XCTAssertEqual(huge.imaginary.y, .zero)
XCTAssertEqual(huge.imaginary.z, .zero)
// 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: [Quaternion<T>] = (0..<100).map { _ in
Quaternion(
real: T.random(in: -1 ... 1, using: &g),
imaginary: SIMD3(repeating: T.random(in: -.pi ... .pi, using: &g) / 3))
}
for z in values {
for w in values {
let p = Quaternion.exp(z) * Quaternion.exp(w)
let q = Quaternion.exp(z) / Quaternion.exp(w)
XCTAssert(Quaternion.exp(z + w).isApproximatelyEqual(to: p))
XCTAssert(Quaternion.exp(z - w).isApproximatelyEqual(to: q))
}
}
}
func testExpMinusOne<T: Real & FixedWidthFloatingPoint & SIMDScalar>(_ type: T.Type) {
// expMinusOne(0) = 0
XCTAssertEqual(0, Quaternion<T>.expMinusOne(Quaternion(real: 0, imaginary: 0, 0, 0)))
XCTAssertEqual(0, Quaternion<T>.expMinusOne(Quaternion(real:-0, imaginary: 0, 0, 0)))
XCTAssertEqual(0, Quaternion<T>.expMinusOne(Quaternion(real:-0, imaginary:-0,-0,-0)))
XCTAssertEqual(0, Quaternion<T>.expMinusOne(Quaternion(real: 0, imaginary:-0,-0,-0)))
// In general, expMinusOne(Quaternion(r,0,0,0)) should be expMinusOne(r),
// but that breaks down when r is infinity or NaN, because we want all non-
// finite Quaternion values to be semantically a single point at infinity.
// This is fine for most inputs, but expMinusOne(Quaternion(-.infinity,0,0,0))
// would produce 0 if we evaluated it in the usual way.
XCTAssertFalse(Quaternion<T>.expMinusOne(Quaternion(real: .infinity, imaginary: .zero)).isFinite)
XCTAssertFalse(Quaternion<T>.expMinusOne(Quaternion(real: .infinity, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.expMinusOne(Quaternion(real: 0, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.expMinusOne(Quaternion(real: -.infinity, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.expMinusOne(Quaternion(real: -.infinity, imaginary: .zero)).isFinite)
XCTAssertFalse(Quaternion<T>.expMinusOne(Quaternion(real: -.infinity, imaginary: -.infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.expMinusOne(Quaternion(real: 0, imaginary: -.infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.expMinusOne(Quaternion(real: .infinity, imaginary: -.infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.expMinusOne(Quaternion(real: .nan, imaginary: .nan)).isFinite)
XCTAssertFalse(Quaternion<T>.expMinusOne(Quaternion(real: .infinity, imaginary: .nan)).isFinite)
XCTAssertFalse(Quaternion<T>.expMinusOne(Quaternion(real: .nan, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.expMinusOne(Quaternion(real: -.infinity, imaginary: .nan)).isFinite)
XCTAssertFalse(Quaternion<T>.expMinusOne(Quaternion(real: .nan, imaginary: -.infinity)).isFinite)
// Near-overflow test, same as exp() above.
let x = T.log(.greatestFiniteMagnitude) + T.log(9/8)
let huge = Quaternion<T>.expMinusOne(Quaternion(real: x, imaginary: SIMD3(.pi/4, 0, 0)))
let mag = T.greatestFiniteMagnitude/T.sqrt(2) * (9/8)
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
XCTAssert(huge.imaginary.x.isApproximatelyEqual(to: mag))
XCTAssertEqual(huge.imaginary.y, .zero)
XCTAssertEqual(huge.imaginary.z, .zero)
// For small values, expMinusOne should be approximately the identity.
var g = SystemRandomNumberGenerator()
let small = T.ulpOfOne
for _ in 0 ..< 100 {
let q = Quaternion<T>(
real: T.random(in: -small ... small, using: &g),
imaginary:
T.random(in: -small ... small, using: &g),
T.random(in: -small ... small, using: &g),
T.random(in: -small ... small, using: &g)
)
XCTAssert(q.isApproximatelyEqual(to: Quaternion.expMinusOne(q), relativeTolerance: 16 * .ulpOfOne))
}
}
func testCosh<T: Real & FixedWidthFloatingPoint & SIMDScalar>(_ type: T.Type) {
// cosh(0) = 1
XCTAssertEqual(1, Quaternion<T>.cosh(Quaternion(real: 0, imaginary: 0, 0, 0)))
XCTAssertEqual(1, Quaternion<T>.cosh(Quaternion(real:-0, imaginary: 0, 0, 0)))
XCTAssertEqual(1, Quaternion<T>.cosh(Quaternion(real:-0, imaginary:-0,-0,-0)))
XCTAssertEqual(1, Quaternion<T>.cosh(Quaternion(real: 0, imaginary:-0,-0,-0)))
// cosh is the identity at infinity.
XCTAssertFalse(Quaternion<T>.cosh(Quaternion(real: .infinity, imaginary: .zero)).isFinite)
XCTAssertFalse(Quaternion<T>.cosh(Quaternion(real: .infinity, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.cosh(Quaternion(real: 0, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.cosh(Quaternion(real: -.infinity, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.cosh(Quaternion(real: -.infinity, imaginary: .zero)).isFinite)
XCTAssertFalse(Quaternion<T>.cosh(Quaternion(real: -.infinity, imaginary: -.infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.cosh(Quaternion(real: 0, imaginary: -.infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.cosh(Quaternion(real: .infinity, imaginary: -.infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.cosh(Quaternion(real: .nan, imaginary: .nan)).isFinite)
XCTAssertFalse(Quaternion<T>.cosh(Quaternion(real: .infinity, imaginary: .nan)).isFinite)
XCTAssertFalse(Quaternion<T>.cosh(Quaternion(real: .nan, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.cosh(Quaternion(real: -.infinity, imaginary: .nan)).isFinite)
XCTAssertFalse(Quaternion<T>.cosh(Quaternion(real: .nan, imaginary: -.infinity)).isFinite)
// Near-overflow test, same as exp() above, but it happens later, because
// for large x, cosh(x + v) ~ exp(x + v)/2.
let x = T.log(.greatestFiniteMagnitude) + T.log(18/8)
let mag = T.greatestFiniteMagnitude/T.sqrt(2) * (9/8)
var huge = Quaternion<T>.cosh(Quaternion(real: x, imaginary: SIMD3(.pi/4, 0, 0)))
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
XCTAssert(huge.imaginary.x.isApproximatelyEqual(to: mag))
XCTAssertEqual(huge.imaginary.y, .zero)
XCTAssertEqual(huge.imaginary.z, .zero)
huge = Quaternion<T>.cosh(Quaternion(real: -x, imaginary: SIMD3(.pi/4, 0, 0)))
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
XCTAssert(huge.imaginary.x.isApproximatelyEqual(to: mag))
XCTAssertEqual(huge.imaginary.y, .zero)
XCTAssertEqual(huge.imaginary.z, .zero)
}
func testSinh<T: Real & FixedWidthFloatingPoint & SIMDScalar>(_ type: T.Type) {
// sinh(0) = 0
XCTAssertEqual(0, Quaternion<T>.sinh(Quaternion(real: 0, imaginary: 0, 0, 0)))
XCTAssertEqual(0, Quaternion<T>.sinh(Quaternion(real:-0, imaginary: 0, 0, 0)))
XCTAssertEqual(0, Quaternion<T>.sinh(Quaternion(real:-0, imaginary:-0,-0,-0)))
XCTAssertEqual(0, Quaternion<T>.sinh(Quaternion(real: 0, imaginary:-0,-0,-0)))
// sinh is the identity at infinity.
XCTAssertFalse(Quaternion<T>.sinh(Quaternion(real: .infinity, imaginary: .zero)).isFinite)
XCTAssertFalse(Quaternion<T>.sinh(Quaternion(real: .infinity, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.sinh(Quaternion(real: 0, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.sinh(Quaternion(real: -.infinity, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.sinh(Quaternion(real: -.infinity, imaginary: .zero)).isFinite)
XCTAssertFalse(Quaternion<T>.sinh(Quaternion(real: -.infinity, imaginary: -.infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.sinh(Quaternion(real: 0, imaginary: -.infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.sinh(Quaternion(real: .infinity, imaginary: -.infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.sinh(Quaternion(real: .nan, imaginary: .nan)).isFinite)
XCTAssertFalse(Quaternion<T>.sinh(Quaternion(real: .infinity, imaginary: .nan)).isFinite)
XCTAssertFalse(Quaternion<T>.sinh(Quaternion(real: .nan, imaginary: .infinity)).isFinite)
XCTAssertFalse(Quaternion<T>.sinh(Quaternion(real: -.infinity, imaginary: .nan)).isFinite)
XCTAssertFalse(Quaternion<T>.sinh(Quaternion(real: .nan, imaginary: -.infinity)).isFinite)
// Near-overflow test, same as exp() above, but it happens later, because
// for large x, sinh(x + v) ~ ±exp(x + v)/2.
let x = T.log(.greatestFiniteMagnitude) + T.log(18/8)
let mag = T.greatestFiniteMagnitude/T.sqrt(2) * (9/8)
var huge = Quaternion<T>.sinh(Quaternion(real: x, imaginary: SIMD3(.pi/4, 0, 0)))
XCTAssert(huge.real.isApproximatelyEqual(to: mag))
XCTAssert(huge.imaginary.x.isApproximatelyEqual(to: mag))
XCTAssertEqual(huge.imaginary.y, .zero)
XCTAssertEqual(huge.imaginary.z, .zero)
huge = Quaternion<T>.sinh(Quaternion(real: -x, imaginary: SIMD3(.pi/4, 0, 0)))
XCTAssert(huge.real.isApproximatelyEqual(to: -mag))
XCTAssert(huge.imaginary.x.isApproximatelyEqual(to: -mag))
XCTAssertEqual(huge.imaginary.y, .zero)
XCTAssertEqual(huge.imaginary.z, .zero)
// 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: [Quaternion<T>] = (0..<1000).map { _ in
Quaternion(
real: T.random(in: -2 ... 2, using: &g),
imaginary:
T.random(in: -2 ... 2, using: &g),
T.random(in: -2 ... 2, using: &g),
T.random(in: -2 ... 2, using: &g)
)
}
for q in values {
let c = Quaternion.cosh(q)
let s = Quaternion.sinh(q)
XCTAssert((c*c - s*s).isApproximatelyEqual(to: .one))
}
}
func testCosSin<T: Real & FixedWidthFloatingPoint & SIMDScalar>(_ type: T.Type) {
var g = SystemRandomNumberGenerator()
let values: [Quaternion<T>] = (0..<1000).map { _ in
Quaternion(
real: T.random(in: -2 ... 2, using: &g),
imaginary:
T.random(in: -2 ... 2, using: &g),
T.random(in: -2 ... 2, using: &g),
T.random(in: -2 ... 2, using: &g)
)
}
for q in values {
// For randomly-chosen well-scaled finite values, we expect to have
// cos² + sin² ≈ 1
let s = Quaternion.sin(q)
let c = Quaternion.cos(q)
XCTAssert((c*c + s*s).isApproximatelyEqual(to: .one))
}
}
func testFloat() {
testExp(Float32.self)
testExpMinusOne(Float32.self)
testCosh(Float32.self)
testSinh(Float32.self)
testCosSin(Float32.self)
}
func testDouble() {
testExp(Float64.self)
testExpMinusOne(Float64.self)
testCosh(Float64.self)
testSinh(Float64.self)
testCosSin(Float64.self)
}
}
+236
View File
@@ -0,0 +1,236 @@
//===--- PropertyTests.swift ----------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
import RealModule
@testable import QuaternionModule
final class PropertyTests: XCTestCase {
func testProperties<T: Real & SIMDScalar>(_ type: T.Type) {
// The real and imaginary parts of a non-finite value should be nan.
XCTAssertTrue(Quaternion<T>.infinity.real.isNaN)
XCTAssertTrue(Quaternion<T>.infinity.imaginary.x.isNaN)
XCTAssertTrue(Quaternion<T>.infinity.imaginary.y.isNaN)
XCTAssertTrue(Quaternion<T>.infinity.imaginary.z.isNaN)
XCTAssertTrue(Quaternion<T>(real: .infinity, imaginary: .nan, .nan, .nan).real.isNaN)
XCTAssertTrue(Quaternion<T>(real: .nan, imaginary: 0, 0, 0).imaginary.x.isNaN)
XCTAssertTrue(Quaternion<T>(real: .nan, imaginary: 0, 0, 0).imaginary.y.isNaN)
XCTAssertTrue(Quaternion<T>(real: .nan, imaginary: 0, 0, 0).imaginary.z.isNaN)
// The length of a non-finite value should be infinity.
XCTAssertEqual(Quaternion<T>.infinity.length, .infinity)
XCTAssertEqual(Quaternion<T>(real: .infinity, imaginary: .nan, .nan, .nan).length, .infinity)
XCTAssertEqual(Quaternion<T>(real: .nan, imaginary: 0, 0, 0).length, .infinity)
// The length of a zero value should be zero.
XCTAssertEqual(Quaternion<T>.zero.length, .zero)
XCTAssertEqual(Quaternion<T>(real: .zero, imaginary: -.zero).length, .zero)
XCTAssertEqual(Quaternion<T>(real: -.zero, imaginary: -.zero).length, .zero)
// Check for overflow and underflow when calculating the length
XCTAssertEqual(Quaternion<T>(real: .greatestFiniteMagnitude, imaginary: 0, 0, 0).length, .greatestFiniteMagnitude)
XCTAssertEqual(Quaternion<T>(real: 0, imaginary: -.greatestFiniteMagnitude, 0, 0).length, .greatestFiniteMagnitude)
XCTAssertEqual(Quaternion<T>(real: 0, imaginary: 0, .leastNormalMagnitude, 0).length, .leastNormalMagnitude)
XCTAssertEqual(Quaternion<T>(real: 0, imaginary: 0, 0, -.leastNormalMagnitude).length, .leastNormalMagnitude)
// The properties of pure and real
XCTAssertTrue(Quaternion<T>.zero.isPure) // zero quaternion is both, pure...
XCTAssertTrue(Quaternion<T>.zero.isReal) // and real
XCTAssertFalse(Quaternion<T>(1).isPure)
XCTAssertTrue(Quaternion<T>(1).isReal)
XCTAssertTrue(Quaternion<T>(real: .zero, imaginary: 1, 0, 0).isPure)
XCTAssertFalse(Quaternion<T>(real: .zero, imaginary: 1, 0, 0).isReal)
XCTAssertFalse(Quaternion<T>(from: SIMD4(repeating: 1)).isPure)
XCTAssertFalse(Quaternion<T>(from: SIMD4(repeating: 1)).isReal)
}
func testProperties() {
testProperties(Float32.self)
testProperties(Float64.self)
}
func testEquatableHashable<T: Real & SIMDScalar>(_ type: T.Type) {
// Validate that all zeros compare and hash equal, and all non-finites
// do too.
let zeros = [
Quaternion<T>(real: .zero, imaginary: .zero, .zero, .zero),
Quaternion<T>(real: .zero, imaginary: -.zero, .zero, .zero),
Quaternion<T>(real: .zero, imaginary: .zero, -.zero, .zero),
Quaternion<T>(real: .zero, imaginary: .zero, .zero, -.zero),
Quaternion<T>(real: .zero, imaginary: -.zero, -.zero, .zero),
Quaternion<T>(real: .zero, imaginary: -.zero, .zero, -.zero),
Quaternion<T>(real: .zero, imaginary: .zero, -.zero, -.zero),
Quaternion<T>(real: .zero, imaginary: -.zero, -.zero, -.zero),
Quaternion<T>(real: -.zero, imaginary: .zero, .zero, .zero),
Quaternion<T>(real: -.zero, imaginary: -.zero, .zero, .zero),
Quaternion<T>(real: -.zero, imaginary: .zero, -.zero, .zero),
Quaternion<T>(real: -.zero, imaginary: .zero, .zero, -.zero),
Quaternion<T>(real: -.zero, imaginary: -.zero, -.zero, .zero),
Quaternion<T>(real: -.zero, imaginary: -.zero, .zero, -.zero),
Quaternion<T>(real: -.zero, imaginary: .zero, -.zero, -.zero),
Quaternion<T>(real: -.zero, imaginary: -.zero, -.zero, -.zero)
]
for z in zeros[1...] {
XCTAssertEqual(zeros[0], z)
XCTAssertEqual(zeros[0].hashValue, z.hashValue)
}
let infs = [
Quaternion<T>(real: .nan, imaginary: .nan, .nan, .nan),
Quaternion<T>(real: -.infinity, imaginary: .nan, .nan, .nan),
Quaternion<T>(real: -.ulpOfOne, imaginary: .nan, .nan, .nan),
Quaternion<T>(real: .zero, imaginary: .nan, .nan, .nan),
Quaternion<T>(real: .pi, imaginary: .nan, .nan, .nan),
Quaternion<T>(real: .infinity, imaginary: .nan, .nan, .nan),
Quaternion<T>(real: .nan, imaginary: -.infinity, -.infinity, -.infinity),
Quaternion<T>(real: -.infinity, imaginary: -.infinity, -.infinity, -.infinity),
Quaternion<T>(real: -.ulpOfOne, imaginary: -.infinity, -.infinity, -.infinity),
Quaternion<T>(real: .zero, imaginary: -.infinity, -.infinity, -.infinity),
Quaternion<T>(real: .pi, imaginary: -.infinity, -.infinity, -.infinity),
Quaternion<T>(real: .infinity, imaginary: -.infinity, -.infinity, -.infinity),
Quaternion<T>(real: .nan, imaginary: -.ulpOfOne, -.ulpOfOne, -.ulpOfOne),
Quaternion<T>(real: -.infinity, imaginary: -.ulpOfOne, -.ulpOfOne, -.ulpOfOne),
Quaternion<T>(real: .infinity, imaginary: -.ulpOfOne, -.ulpOfOne, -.ulpOfOne),
Quaternion<T>(real: .nan, imaginary: .zero, .zero, .zero),
Quaternion<T>(real: -.infinity, imaginary: .zero, .zero, .zero),
Quaternion<T>(real: .infinity, imaginary: .zero, .zero, .zero),
Quaternion<T>(real: .nan, imaginary: .pi, .pi, .pi),
Quaternion<T>(real: -.infinity, imaginary: .pi, .pi, .pi),
Quaternion<T>(real: .infinity, imaginary: .pi, .pi, .pi),
Quaternion<T>(real: .nan, imaginary: .infinity, .infinity, .infinity),
Quaternion<T>(real: -.infinity, imaginary: .infinity, .infinity, .infinity),
Quaternion<T>(real: -.ulpOfOne, imaginary: .infinity, .infinity, .infinity),
Quaternion<T>(real: .zero, imaginary: .infinity, .infinity, .infinity),
Quaternion<T>(real: .pi, imaginary: .infinity, .infinity, .infinity),
Quaternion<T>(real: .infinity, imaginary: .infinity, .infinity, .infinity),
]
for i in infs[1...] {
XCTAssertEqual(infs[0], i)
XCTAssertEqual(infs[0].hashValue, i.hashValue)
}
// Validate that all *normal* values hash their absolute components, so
// that rotations in *R³* of `q` and `-q` will hash to same value.
let pairs: [(lhs: Quaternion<T>, rhs: Quaternion<T>)] = [
(
Quaternion<T>(real: -.pi, imaginary: .pi, .pi, .pi),
Quaternion<T>(real: .pi, imaginary: -.pi, -.pi, -.pi)
), (
Quaternion<T>(real: .pi, imaginary: -.pi, .pi, .pi),
Quaternion<T>(real: -.pi, imaginary: .pi, -.pi, -.pi)
), (
Quaternion<T>(real: .pi, imaginary: .pi, -.pi, .pi),
Quaternion<T>(real: -.pi, imaginary: -.pi, .pi, -.pi)
), (
Quaternion<T>(real: .pi, imaginary: .pi, .pi, -.pi),
Quaternion<T>(real: -.pi, imaginary: -.pi, -.pi, .pi)
), (
Quaternion<T>(real: -.pi, imaginary: -.pi, .pi, .pi),
Quaternion<T>(real: .pi, imaginary: .pi, -.pi, -.pi)
), (
Quaternion<T>(real: .pi, imaginary: -.pi, -.pi, .pi),
Quaternion<T>(real: -.pi, imaginary: .pi, .pi, -.pi)
), (
Quaternion<T>(real: .pi, imaginary: .pi, -.pi, -.pi),
Quaternion<T>(real: -.pi, imaginary: -.pi, .pi, .pi)
), (
Quaternion<T>(real: .pi, imaginary: .pi, .pi, .pi),
Quaternion<T>(real: -.pi, imaginary: -.pi, -.pi, -.pi)
)
]
for pair in pairs {
XCTAssertEqual(pair.lhs.hashValue, pair.rhs.hashValue)
}
}
func testEquatableHashable() {
testEquatableHashable(Float32.self)
testEquatableHashable(Float64.self)
}
func testTransformationEquals<T: Real & SIMDScalar>(_ type: T.Type) {
let rotations: [(lhs: Quaternion<T>, rhs: Quaternion<T>)] = [
(
Quaternion<T>(real: -.pi, imaginary: -.pi, -.pi, -.pi),
Quaternion<T>(real: .pi, imaginary: .pi, .pi, .pi)
), (
Quaternion<T>(real: .ulpOfOne, imaginary: .ulpOfOne, .ulpOfOne, .ulpOfOne),
Quaternion<T>(real: -.ulpOfOne, imaginary: -.ulpOfOne, -.ulpOfOne, -.ulpOfOne)
), (
Quaternion<T>(real: .pi, imaginary: -.pi, .pi, -.pi),
Quaternion<T>(real: -.pi, imaginary: .pi, -.pi, .pi)
), (
Quaternion<T>(real: -.ulpOfOne, imaginary: -.ulpOfOne, .ulpOfOne, .ulpOfOne),
Quaternion<T>(real: .ulpOfOne, imaginary: .ulpOfOne, -.ulpOfOne, -.ulpOfOne)
),
// Zero and infinity must have equal rotations too
(
Quaternion<T>.zero,
-Quaternion<T>.zero
), (
-Quaternion<T>.infinity,
Quaternion<T>.infinity
),
]
for (lhs, rhs) in rotations {
XCTAssertTrue(lhs.equals(as3DTransform: rhs))
}
let signDifferentAxis: [(lhs: Quaternion<T>, rhs: Quaternion<T>)] = [
(
Quaternion<T>(real: -.pi, imaginary: -.pi, -.pi, -.pi),
Quaternion<T>(real: -.pi, imaginary: .pi, .pi, .pi)
), (
Quaternion<T>(real: -.ulpOfOne, imaginary: .ulpOfOne, .ulpOfOne, .ulpOfOne),
Quaternion<T>(real: -.ulpOfOne, imaginary: -.ulpOfOne, -.ulpOfOne, -.ulpOfOne)
), (
Quaternion<T>(real: -.pi, imaginary: -.pi, .pi, -.pi),
Quaternion<T>(real: -.pi, imaginary: .pi, -.pi, .pi)
), (
Quaternion<T>(real: -.ulpOfOne, imaginary: -.ulpOfOne, .ulpOfOne, .ulpOfOne),
Quaternion<T>(real: -.ulpOfOne, imaginary: .ulpOfOne, -.ulpOfOne, -.ulpOfOne)
)
]
for (lhs, rhs) in signDifferentAxis {
XCTAssertFalse(lhs.equals(as3DTransform: rhs))
}
}
func testTransformationEquals() {
testTransformationEquals(Float32.self)
testTransformationEquals(Float64.self)
}
func testCodable<T: Real & SIMDScalar>(_ 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: Quaternion<T> in [.zero, .one, .i, .infinity] {
let data = try encoder.encode(expected)
let actual = try decoder.decode(Quaternion<T>.self, from: data)
XCTAssertEqual(actual, expected)
}
}
func testCodable() throws {
try testCodable(Float32.self)
try testCodable(Float64.self)
}
}
@@ -0,0 +1,379 @@
//===--- TransformationTests.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 XCTest
import RealModule
@testable import QuaternionModule
final class TransformationTests: XCTestCase {
// MARK: Angle/Axis
func testAngleAxis<T: Real & SIMDScalar>(_ type: T.Type) {
let xAxis = SIMD3<T>(1,0,0)
// Positive angle, positive axis
XCTAssertEqual(Quaternion<T>(angle: .pi, axis: xAxis).angle, .pi)
XCTAssertEqual(Quaternion<T>(angle: .pi, axis: xAxis).axis, xAxis)
// Negative angle, positive axis
XCTAssertEqual(Quaternion<T>(angle: -.pi, axis: xAxis).angle, .pi)
XCTAssertEqual(Quaternion<T>(angle: -.pi, axis: xAxis).axis, -xAxis)
// Positive angle, negative axis
XCTAssertEqual(Quaternion<T>(angle: .pi, axis: -xAxis).angle, .pi)
XCTAssertEqual(Quaternion<T>(angle: .pi, axis: -xAxis).axis, -xAxis)
// Negative angle, negative axis
XCTAssertEqual(Quaternion<T>(angle: -.pi, axis: -xAxis).angle, .pi)
XCTAssertEqual(Quaternion<T>(angle: -.pi, axis: -xAxis).axis, xAxis)
}
func testAngleAxis() {
testAngleAxis(Float32.self)
testAngleAxis(Float64.self)
}
func testAngleAxisMultipleOfPi<T: Real & SIMDScalar>(_ type: T.Type) {
let xAxis = SIMD3<T>(1,0,0)
// 2π
let pi2 = Quaternion<T>(angle: .pi * 2, axis: xAxis)
XCTAssertEqual(pi2.angle, .pi * 2)
XCTAssertEqual(pi2.axis, xAxis)
// 3π - axis inverted
let pi3 = Quaternion<T>(angle: .pi * 3, axis: xAxis)
XCTAssertTrue(closeEnough(pi3.angle, .pi, ulps: 1))
XCTAssertEqual(pi3.axis, -xAxis)
// 5π - axis restored
let pi5 = Quaternion<T>(angle: .pi * 5, axis: xAxis)
XCTAssertTrue(closeEnough(pi5.angle, .pi, ulps: 5))
XCTAssertEqual(pi5.axis, xAxis)
}
func testAngleAxisMultipleOfPi() {
testAngleAxisMultipleOfPi(Float32.self)
testAngleAxisMultipleOfPi(Float64.self)
}
func testAngleAxisEdgeCases<T: Real & SIMDScalar>(_ type: T.Type) {
// Zero/Zero
XCTAssertTrue(Quaternion<T>(length: .zero, angle: .zero, axis: .zero).axis.isNaN)
XCTAssertTrue(Quaternion<T>(length: .zero, angle: .zero, axis: .zero).angle.isNaN)
XCTAssertEqual(Quaternion<T>(length: .zero, angle: .zero, axis: .zero), .zero)
// Inf/Zero
XCTAssertTrue(Quaternion<T>(length: .zero, angle: .infinity, axis: .infinity).axis.isNaN)
XCTAssertTrue(Quaternion<T>(length: .zero, angle: .infinity, axis: .infinity).angle.isNaN)
XCTAssertEqual(Quaternion<T>(length: .zero, angle: .infinity, axis: .infinity), .zero)
// -Inf/Zero
XCTAssertTrue(Quaternion<T>(length: .zero, angle: -.infinity, axis: -.infinity).axis.isNaN)
XCTAssertTrue(Quaternion<T>(length: .zero, angle: -.infinity, axis: -.infinity).angle.isNaN)
XCTAssertEqual(Quaternion<T>(length: .zero, angle: -.infinity, axis: -.infinity), .zero)
// NaN/Zero
XCTAssertTrue(Quaternion<T>(length: .zero, angle: .nan, axis: .nan).axis.isNaN)
XCTAssertTrue(Quaternion<T>(length: .zero, angle: .nan, axis: .nan).angle.isNaN)
XCTAssertEqual(Quaternion<T>(length: .zero, angle: .nan, axis: .nan), .zero)
// Zero/Inf
XCTAssertTrue(Quaternion<T>(length: .infinity, angle: .zero, axis: .zero).axis.isNaN)
XCTAssertTrue(Quaternion<T>(length: .infinity, angle: .zero, axis: .zero).angle.isNaN)
XCTAssertEqual(Quaternion<T>(length: .infinity, angle: .zero, axis: .zero), .infinity)
// Inf/Inf
XCTAssertTrue(Quaternion<T>(length: .infinity, angle: .infinity, axis: .infinity).axis.isNaN)
XCTAssertTrue(Quaternion<T>(length: .infinity, angle: .infinity, axis: .infinity).angle.isNaN)
XCTAssertEqual(Quaternion<T>(length: .infinity, angle: .infinity, axis: .infinity), .infinity)
// -Inf/Inf
XCTAssertTrue(Quaternion<T>(length: .infinity, angle: -.infinity, axis: -.infinity).axis.isNaN)
XCTAssertTrue(Quaternion<T>(length: .infinity, angle: -.infinity, axis: -.infinity).angle.isNaN)
XCTAssertEqual(Quaternion<T>(length: .infinity, angle: -.infinity, axis: -.infinity), .infinity)
// NaN/Inf
XCTAssertTrue(Quaternion<T>(length: .infinity, angle: .nan, axis: .nan).axis.isNaN)
XCTAssertTrue(Quaternion<T>(length: .infinity, angle: .nan, axis: .nan).angle.isNaN)
XCTAssertEqual(Quaternion<T>(length: .infinity, angle: .nan, axis: .nan), .infinity)
// Zero/-Inf
XCTAssertTrue(Quaternion<T>(length: -.infinity, angle: .zero, axis: .zero).axis.isNaN)
XCTAssertTrue(Quaternion<T>(length: -.infinity, angle: .zero, axis: .zero).angle.isNaN)
XCTAssertEqual(Quaternion<T>(length: -.infinity, angle: .zero, axis: .zero), .infinity)
// Inf/-Inf
XCTAssertTrue(Quaternion<T>(length: -.infinity, angle: .infinity, axis: .infinity).axis.isNaN)
XCTAssertTrue(Quaternion<T>(length: -.infinity, angle: .infinity, axis: .infinity).angle.isNaN)
XCTAssertEqual(Quaternion<T>(length: -.infinity, angle: .infinity, axis: .infinity), .infinity)
// -Inf/-Inf
XCTAssertTrue(Quaternion<T>(length: -.infinity, angle: -.infinity, axis: -.infinity).axis.isNaN)
XCTAssertTrue(Quaternion<T>(length: -.infinity, angle: -.infinity, axis: -.infinity).angle.isNaN)
XCTAssertEqual(Quaternion<T>(length: -.infinity, angle: -.infinity, axis: -.infinity), .infinity)
// NaN/-Inf
XCTAssertTrue(Quaternion<T>(length: -.infinity, angle: .nan, axis: .nan).axis.isNaN)
XCTAssertTrue(Quaternion<T>(length: -.infinity, angle: .nan, axis: .nan).angle.isNaN)
XCTAssertEqual(Quaternion<T>(length: -.infinity, angle: .nan, axis: .nan), .infinity)
}
func testAngleAxisEdgeCases() {
testAngleAxisEdgeCases(Float32.self)
testAngleAxisEdgeCases(Float64.self)
}
func testHalfAngleAndAxisOverflow<T: Real & SIMDScalar>(_ type: T.Type) {
let unscaled = Quaternion<T>(real: 1, imaginary: .one)
let scaled = Quaternion<T>(
real: .greatestFiniteMagnitude,
imaginary: SIMD3(repeating: .greatestFiniteMagnitude)
)
XCTAssertEqual(scaled.angle, unscaled.angle)
XCTAssertEqual(scaled.axis, unscaled.axis)
}
func testHalfAngleAndAxisOverflow() {
testHalfAngleAndAxisOverflow(Float32.self)
testHalfAngleAndAxisOverflow(Float64.self)
}
func testHalfAngleAndAxisUnderflow<T: Real & SIMDScalar>(_ type: T.Type) {
let unscaled = Quaternion<T>(real: 1, imaginary: .one)
let scaled = Quaternion<T>(
real: .leastNormalMagnitude,
imaginary: SIMD3(repeating: .leastNormalMagnitude)
)
XCTAssertEqual(scaled.angle, unscaled.angle)
XCTAssertEqual(scaled.axis, unscaled.axis)
}
func testHalfAngleAndAxisUnderflow() {
testHalfAngleAndAxisUnderflow(Float32.self)
testHalfAngleAndAxisUnderflow(Float64.self)
}
// MARK: Rotation Vector
func testRotationVector<T: Real & SIMDScalar>(_ type: T.Type) {
let vector = SIMD3<T>(0,-1,0) * .pi
XCTAssertEqual(Quaternion<T>(rotation: vector).rotationVector.x, .zero)
XCTAssertEqual(Quaternion<T>(rotation: vector).rotationVector.y, -.pi)
XCTAssertEqual(Quaternion<T>(rotation: vector).rotationVector.z, .zero)
XCTAssertEqual(Quaternion<T>(rotation: vector).axis, SIMD3(0,-1,0))
XCTAssertEqual(Quaternion<T>(rotation: vector).angle, .pi)
}
func testRotationVector() {
testRotationVector(Float32.self)
testRotationVector(Float64.self)
}
func testRotationVectorEdgeCases<T: Real & SIMDScalar>(_ type: T.Type) {
XCTAssertEqual(Quaternion<T>(rotation: .zero), .zero)
XCTAssertEqual(Quaternion<T>(rotation: .infinity), .infinity)
XCTAssertEqual(Quaternion<T>(rotation: -.infinity), .infinity)
XCTAssertTrue(Quaternion<T>(rotation: .nan).real.isNaN)
XCTAssertTrue(Quaternion<T>(rotation: .nan).imaginary.isNaN)
}
func testRotationVectorEdgeCases() {
testRotationVectorEdgeCases(Float32.self)
testRotationVectorEdgeCases(Float64.self)
}
// MARK: Polar Decomposition
func testPolarDecomposition<T: Real & SIMDScalar>(_ type: T.Type) {
let axis = SIMD3<T>(0,-1,0)
let q = Quaternion<T>(length: 5, halfAngle: .pi, axis: axis)
XCTAssertEqual(q.axis, axis)
XCTAssertEqual(q.angle, .pi * 2)
XCTAssertEqual(q.polar.length, 5)
XCTAssertEqual(q.polar.halfAngle, .pi)
XCTAssertEqual(q.polar.axis, axis)
}
func testPolarDecomposition() {
testPolarDecomposition(Float32.self)
testPolarDecomposition(Float64.self)
}
func testPolarDecompositionEdgeCases<T: Real & SIMDScalar>(_ type: T.Type) {
XCTAssertEqual(Quaternion<T>(length: .zero, halfAngle: .zero, axis: .zero), .zero)
XCTAssertEqual(Quaternion<T>(length: .zero, halfAngle: .infinity, axis: .infinity), .zero)
XCTAssertEqual(Quaternion<T>(length: .zero, halfAngle:-.infinity, axis:-.infinity), .zero)
XCTAssertEqual(Quaternion<T>(length: .zero, halfAngle: .nan, axis: .nan), .zero)
XCTAssertEqual(Quaternion<T>(length: .infinity, halfAngle: .zero, axis: .zero), .infinity)
XCTAssertEqual(Quaternion<T>(length: .infinity, halfAngle: .infinity, axis: .infinity), .infinity)
XCTAssertEqual(Quaternion<T>(length: .infinity, halfAngle:-.infinity, axis:-.infinity), .infinity)
XCTAssertEqual(Quaternion<T>(length: .infinity, halfAngle: .nan, axis: .infinity), .infinity)
XCTAssertEqual(Quaternion<T>(length:-.infinity, halfAngle: .zero, axis: .zero), .infinity)
XCTAssertEqual(Quaternion<T>(length:-.infinity, halfAngle: .infinity, axis: .infinity), .infinity)
XCTAssertEqual(Quaternion<T>(length:-.infinity, halfAngle:-.infinity, axis:-.infinity), .infinity)
XCTAssertEqual(Quaternion<T>(length:-.infinity, halfAngle: .nan, axis: .infinity), .infinity)
}
func testPolarDecompositionEdgeCases() {
testPolarDecompositionEdgeCases(Float32.self)
testPolarDecompositionEdgeCases(Float64.self)
}
// MARK: Act on Vector
func testActOnVector<T: Real & SIMDScalar>(_ type: T.Type) {
let vector = SIMD3<T>(1,1,1)
let xAxis = SIMD3<T>(1,0,0)
let singleAxis = Quaternion<T>(angle: .pi/2, axis: SIMD3(0, 1, 0))
XCTAssertTrue(singleAxis.act(on: xAxis).x.isApproximatelyEqual(
to: .zero, absoluteTolerance: T.ulpOfOne.squareRoot()
))
XCTAssertTrue(singleAxis.act(on: xAxis).y.isApproximatelyEqual(
to: .zero, absoluteTolerance: T.ulpOfOne.squareRoot()
))
XCTAssertEqual(singleAxis.act(on: xAxis).z, -1)
let piHalf = Quaternion<T>(angle: .pi/2, axis: xAxis)
XCTAssertTrue(closeEnough(piHalf.act(on: vector).x, 1, ulps: 0))
XCTAssertTrue(closeEnough(piHalf.act(on: vector).y, -1, ulps: 1))
XCTAssertTrue(closeEnough(piHalf.act(on: vector).z, 1, ulps: 1))
let pi = Quaternion<T>(angle: .pi, axis: xAxis)
XCTAssertTrue(closeEnough(pi.act(on: vector).x, 1, ulps: 0))
XCTAssertTrue(closeEnough(pi.act(on: vector).y, -1, ulps: 2))
XCTAssertTrue(closeEnough(pi.act(on: vector).z, -1, ulps: 2))
let twoPi = Quaternion<T>(angle: .pi * 2, axis: xAxis)
XCTAssertTrue(closeEnough(twoPi.act(on: vector).x, 1, ulps: 0))
XCTAssertTrue(closeEnough(twoPi.act(on: vector).y, 1, ulps: 3))
XCTAssertTrue(closeEnough(twoPi.act(on: vector).z, 1, ulps: 3))
}
func testActOnVector() {
testActOnVector(Float32.self)
testActOnVector(Float64.self)
}
func testActOnVectorRandom<T>(_ type: T.Type)
where T: Real, T: BinaryFloatingPoint, T: SIMDScalar,
T.Exponent: FixedWidthInteger, T.RawSignificand: FixedWidthInteger
{
// Generate random angles, axis and vector to test rotation properties
// - angle are selected from range -π to π
// - axis values are selected from -1 to 1; axis length is unity
// - vector values are selected from 10 to 10000
let inputs: [(angle: T, axis: SIMD3<T>, vector: SIMD3<T>)] = (0..<100).map { _ in
let angle = T.random(in: -.pi ... .pi)
var axis = SIMD3<T>.random(in: -1 ... 1)
axis /= .sqrt((axis * axis).sum()) // Normalize
var vector = SIMD3<T>.random(in: -1 ... 1)
vector /= .sqrt((vector * vector).sum()) // Normalize
vector *= T.random(in: 10 ... 10000) // Scale
return (angle, axis, vector)
}
for (angle, axis, vector) in inputs {
let q = Quaternion(angle: angle, axis: axis)
// The following equation in the form of v' = qvq⁻¹ is the mathmatical
// definition for how a quaternion rotates a vector (by promoting it to
// a quaternion) and goes "the full and long way" to calculate the
// rotation of vector by a quaternion. The result is used to test the
// rotation properties of "act(on:)"
let vrot = (q // q
* Quaternion(imaginary: vector) // v (pure quaternion)
* q.conjugate // q⁻¹ (as q is of unit length, q⁻¹ == q*)
).imaginary // the result is a pure quaternion with v' == imaginary
XCTAssertTrue(q.act(on: vector).x.isFinite)
XCTAssertTrue(q.act(on: vector).y.isFinite)
XCTAssertTrue(q.act(on: vector).z.isFinite)
// Test for sign equality on the components to see if the vector rotated
// to the correct quadrant and if the vector is of equal length, instead
// of testing component equality – as they are hard to compare with
// proper tolerance
XCTAssertEqual(q.act(on: vector).x.sign, vrot.x.sign)
XCTAssertEqual(q.act(on: vector).y.sign, vrot.y.sign)
XCTAssertEqual(q.act(on: vector).z.sign, vrot.z.sign)
XCTAssertTrue(closeEnough(q.act(on: vector).lengthSquared, vrot.lengthSquared, ulps: 16))
}
}
func testActOnVectorRandom() {
testActOnVectorRandom(Float32.self)
testActOnVectorRandom(Float64.self)
}
func testActOnVectorEdgeCase<T: Real & SIMDScalar>(_ type: T.Type) {
/// Test for zero, infinity
let q = Quaternion(angle: .pi, axis: SIMD3(1,0,0))
XCTAssertEqual(q.act(on: .zero), .zero)
XCTAssertEqual(q.act(on: -.zero), .zero)
XCTAssertEqual(q.act(on: .nan ), .infinity)
XCTAssertEqual(q.act(on: .infinity), .infinity)
XCTAssertEqual(q.act(on: -.infinity), .infinity)
}
func testActOnVectorEdgeCase() {
testActOnVectorEdgeCase(Float32.self)
testActOnVectorEdgeCase(Float64.self)
}
func testActOnVectorOverflow<T: Real & ExpressibleByFloatLiteral & SIMDScalar>(_ type: T.Type) {
// Create a vector (somewhat) close to greatestFiniteMagnitude on all lanes.
// We can not use greatestFiniteMagnitude here to test the careful rotation
// path, as we lose some precision in the process and it will overflow after
// rescaling the vector.
let scalar = T(
sign: .plus, exponent: T.greatestFiniteMagnitude.exponent,
significand: 1.999999
)
let closeToBounds = SIMD3<T>(repeating: scalar)
// An axis perpendicular to the vector, so all lanes change equally
let axis = SIMD3<T>(1,0,-1) / .sqrt(2)
// Perform a 180° rotation on all components
let pi = Quaternion(angle: .pi, axis: axis).act(on: closeToBounds)
// Must be finite after the rotation
XCTAssertTrue(pi.x.isFinite)
XCTAssertTrue(pi.y.isFinite)
XCTAssertTrue(pi.z.isFinite)
XCTAssertTrue(closeEnough(pi.x, -scalar, ulps: 4))
XCTAssertTrue(closeEnough(pi.y, -scalar, ulps: 4))
XCTAssertTrue(closeEnough(pi.z, -scalar, ulps: 4))
}
func testActOnVectorOverflow() {
testActOnVectorOverflow(Float32.self)
testActOnVectorOverflow(Float64.self)
}
func testActOnVectorUnderflow<T: Real & ExpressibleByFloatLiteral & SIMDScalar>(_ type: T.Type) {
let scalar = T.leastNormalMagnitude
let closeToZero = SIMD3<T>(repeating: scalar)
// An axis perpendicular to the vector, so all lanes change equally
let axis = SIMD3<T>(1,0,-1) / .sqrt(2)
// Perform a 180° rotation on all components
let pi = Quaternion(angle: .pi, axis: axis).act(on: closeToZero)
// Must be finite after the rotation
XCTAssertTrue(!pi.x.isZero)
XCTAssertTrue(!pi.y.isZero)
XCTAssertTrue(!pi.z.isZero)
XCTAssertTrue(closeEnough(pi.x, -scalar, ulps: 2))
XCTAssertTrue(closeEnough(pi.y, -scalar, ulps: 2))
XCTAssertTrue(closeEnough(pi.z, -scalar, ulps: 2))
}
func testActOnVectorUnderflow() {
testActOnVectorUnderflow(Float32.self)
testActOnVectorUnderflow(Float64.self)
}
}
// MARK: - Helper
extension SIMD3 where Scalar: FloatingPoint {
fileprivate var isNaN: Bool { x.isNaN && y.isNaN && z.isNaN }
}
// TODO: replace with approximately equals
func closeEnough<T: Real>(_ a: T, _ b: T, ulps allowed: T) -> Bool {
let scale = max(a.magnitude, b.magnitude, T.leastNormalMagnitude).ulp
return (a - b).magnitude <= allowed * scale
}
@@ -31,11 +31,6 @@ internal extension Real where Self: FixedWidthFloatingPoint {
XCTAssertEqual(Self.pow(-1, Int.max), -1)
XCTAssertEqual(Self.pow(-1, -Int.max), -1)
XCTAssertEqual(Self.pow(-1, Int.min), 1)
}
static func testIntegerExponentOverflowAndUnderflow() {
// TODO: replace with seedable generator, print seed.
var g = SystemRandomNumberGenerator()
// Generate some random test values that definitely overflow or
// underflow; we want to be sure that we get the right ±0 or ±∞
// result.
@@ -87,7 +82,6 @@ internal extension Real where Self: FixedWidthFloatingPoint {
extension Float16 {
static func testIntegerExponent() {
testIntegerExponentCommon()
testIntegerExponentOverflowAndUnderflow()
testIntegerExponentDoubleAndSmaller()
let u = Float16(1).nextUp
let d = Float16(1).nextDown
@@ -115,7 +109,6 @@ extension Float16 {
extension Float {
static func testIntegerExponent() {
testIntegerExponentCommon()
testIntegerExponentOverflowAndUnderflow()
testIntegerExponentDoubleAndSmaller()
let u = Float(1).nextUp
let d = Float(1).nextDown
@@ -142,7 +135,6 @@ extension Float {
extension Double {
static func testIntegerExponent() {
testIntegerExponentCommon()
testIntegerExponentOverflowAndUnderflow()
// Following tests only make sense (and are only necessary) on 64b platforms.
#if arch(arm64) || arch(x86_64)
testIntegerExponentDoubleAndSmaller()
@@ -201,10 +193,6 @@ final class IntegerExponentTests: XCTestCase {
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
func testFloat80() {
Float80.testIntegerExponentCommon()
// FreeBSD's powl(3) has a bug where a minus sign is not perserved on overflow/underflow.
#if !os(FreeBSD)
Float80.testIntegerExponentOverflowAndUnderflow()
#endif
}
#endif
}
+2 -2
View File
@@ -23,9 +23,9 @@ function(get_swift_host_arch result_var_name)
else()
set("${result_var_name}" "aarch64" PARENT_SCOPE)
endif()
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64" OR "${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "powerpc64")
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64")
set("${result_var_name}" "powerpc64" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64le" OR "${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "powerpc64le")
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64le")
set("${result_var_name}" "powerpc64le" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "s390x")
set("${result_var_name}" "s390x" PARENT_SCOPE)