mirror of
https://github.com/apple/swift-numerics
synced 2026-11-22 04:30:45 +00:00
Compare commits
107
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0098c438eb | ||
|
|
349fdf1e01 | ||
|
|
0d48ff5a98 | ||
|
|
1c90bdc9a9 | ||
|
|
fd9722e609 | ||
|
|
f11ce9b248 | ||
|
|
935eac199c | ||
|
|
2f60891517 | ||
|
|
5ea7711e02 | ||
|
|
b74c1ce133 | ||
|
|
cd88f161eb | ||
|
|
aaeb9029e9 | ||
|
|
52e7e70caf | ||
|
|
caeeaaa9dd | ||
|
|
cc5f7e5d18 | ||
|
|
feeac39506 | ||
|
|
19951768df | ||
|
|
87900161d6 | ||
|
|
6e0f0094dc | ||
|
|
7d6e5cda3e | ||
|
|
e4f5257d0a | ||
|
|
9e1a1f5e8a | ||
|
|
7026eb4085 | ||
|
|
1a29830c82 | ||
|
|
5919d3f48f | ||
|
|
e3d01dd680 | ||
|
|
90d5ddd1f6 | ||
|
|
e41c631052 | ||
|
|
6e85aa2bbd | ||
|
|
ceee280ebe | ||
|
|
3501fa7c61 | ||
|
|
ca75d2d124 | ||
|
|
ffdaf86868 | ||
|
|
bf9afea2eb | ||
|
|
4c425513cd | ||
|
|
fc7b3bf44f | ||
|
|
0dee6d0927 | ||
|
|
cfc63e8adc | ||
|
|
01c30961ef | ||
|
|
05a45984d9 | ||
|
|
cfc2cd7c97 | ||
|
|
98023c3575 | ||
|
|
506ea36331 | ||
|
|
1b733de54a | ||
|
|
937c292898 | ||
|
|
49121f353a | ||
|
|
e632de88c4 | ||
|
|
b03af80076 | ||
|
|
6f4374cd99 | ||
|
|
d36d9ce02e | ||
|
|
fac716fdb2 | ||
|
|
7ca51a3e50 | ||
|
|
1ddbbfe0d1 | ||
|
|
eab5a94499 | ||
|
|
a6ecb7442a | ||
|
|
2410717a17 | ||
|
|
7ae61f775b | ||
|
|
fe212356fd | ||
|
|
830927ecbb | ||
|
|
fd8049e481 | ||
|
|
0b121fd774 | ||
|
|
72f1cb3554 | ||
|
|
0e58379b4f | ||
|
|
ddaf8be1a2 | ||
|
|
9ddc664ef1 | ||
|
|
b39dd05db3 | ||
|
|
1cb69383a5 | ||
|
|
c9d72fc3ae | ||
|
|
4ec520a726 | ||
|
|
8c378528de | ||
|
|
3cf0b0cf74 | ||
|
|
f6a3d2d4e4 | ||
|
|
036ab5fe94 | ||
|
|
7c6e2ce0d8 | ||
|
|
3a4cc1c623 | ||
|
|
4d7e4e9b97 | ||
|
|
3c916262e0 | ||
|
|
831f06ac78 | ||
|
|
d15400e6ab | ||
|
|
5be3b4e526 | ||
|
|
acd8568864 | ||
|
|
11d5225f3b | ||
|
|
19d3491df4 | ||
|
|
819ebd90c4 | ||
|
|
5b84051f2a | ||
|
|
cb5e7f3c7a | ||
|
|
5cb9b95ce8 | ||
|
|
5db4a69e57 | ||
|
|
2419741a7c | ||
|
|
368caf5b3f | ||
|
|
a799618103 | ||
|
|
dbf743b314 | ||
|
|
2f40de6195 | ||
|
|
38073d2ab5 | ||
|
|
2863c44182 | ||
|
|
e490f1fc66 | ||
|
|
67858690eb | ||
|
|
cced27a6c0 | ||
|
|
821fcbd6a4 | ||
|
|
b46dcf96c6 | ||
|
|
eceae6d7bd | ||
|
|
ac50a90a60 | ||
|
|
524dc69ae1 | ||
|
|
ea2b6f8deb | ||
|
|
cb56525312 | ||
|
|
bc2f9fb7c6 | ||
|
|
96d41bcf9f |
No files matched your search
@@ -1,23 +0,0 @@
|
||||
name: Pull request
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
|
||||
jobs:
|
||||
tests:
|
||||
name: Test
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
|
||||
with:
|
||||
windows_exclude_swift_versions: '[{"swift_version": "5.9"}]'
|
||||
enable_wasm_sdk_build: true
|
||||
wasm_sdk_build_command: swift build --target Numerics
|
||||
soundness:
|
||||
name: Soundness
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
|
||||
with:
|
||||
license_header_check_project_name: "Swift Numerics"
|
||||
# https://github.com/apple/swift-numerics/issues/303
|
||||
license_header_check_enabled: false
|
||||
# https://github.com/apple/swift-numerics/issues/302
|
||||
format_check_enabled: false
|
||||
@@ -1,4 +1,4 @@
|
||||
version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [Numerics, RealModule, ComplexModule]
|
||||
- documentation_targets: [Numerics, RealModule, ComplexModule, BigIntModule]
|
||||
+4
-1
@@ -11,7 +11,7 @@ cmake_minimum_required(VERSION 3.16)
|
||||
project(swift-numerics
|
||||
LANGUAGES Swift)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules)
|
||||
list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/modules)
|
||||
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
@@ -22,6 +22,9 @@ include(CTest)
|
||||
include(SwiftSupport)
|
||||
|
||||
add_subdirectory(Sources)
|
||||
if(BUILD_TESTING)
|
||||
add_subdirectory(Tests)
|
||||
endif()
|
||||
|
||||
get_property(SWIFT_NUMERICS_EXPORTS GLOBAL PROPERTY SWIFT_NUMERICS_EXPORTS)
|
||||
export(TARGETS ${SWIFT_NUMERICS_EXPORTS}
|
||||
|
||||
+25
-17
@@ -1,9 +1,9 @@
|
||||
// swift-tools-version:5.9
|
||||
// swift-tools-version:5.5
|
||||
//===--- Package.swift ----------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// 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
|
||||
@@ -18,21 +18,17 @@ let package = Package(
|
||||
|
||||
name: "swift-numerics",
|
||||
products: [
|
||||
.library(name: "BigIntModule", targets: ["BigIntModule"]),
|
||||
.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"],
|
||||
name: "BigIntModule",
|
||||
dependencies: [],
|
||||
exclude: excludedFilenames
|
||||
),
|
||||
|
||||
@@ -49,9 +45,9 @@ let package = Package(
|
||||
),
|
||||
|
||||
.target(
|
||||
name: "QuaternionModule",
|
||||
dependencies: ["RealModule"],
|
||||
exclude: ["README.md", "Transformation.md"]
|
||||
name: "Numerics",
|
||||
dependencies: ["ComplexModule", "IntegerUtilities", "RealModule", "BigIntModule"],
|
||||
exclude: excludedFilenames
|
||||
),
|
||||
|
||||
.target(
|
||||
@@ -76,6 +72,11 @@ let package = Package(
|
||||
),
|
||||
|
||||
// MARK: - Unit test bundles
|
||||
.testTarget(
|
||||
name: "BigIntTests",
|
||||
dependencies: ["BigIntModule"]
|
||||
),
|
||||
|
||||
.testTarget(
|
||||
name: "ComplexTests",
|
||||
dependencies: ["_TestSupport"],
|
||||
@@ -84,7 +85,7 @@ let package = Package(
|
||||
|
||||
.testTarget(
|
||||
name: "IntegerUtilitiesTests",
|
||||
dependencies: ["_TestSupport"],
|
||||
dependencies: ["IntegerUtilities", "_TestSupport"],
|
||||
exclude: ["CMakeLists.txt"]
|
||||
),
|
||||
|
||||
@@ -94,10 +95,17 @@ let package = Package(
|
||||
exclude: ["CMakeLists.txt"]
|
||||
),
|
||||
|
||||
.testTarget(
|
||||
name: "QuaternionTests",
|
||||
dependencies: ["_TestSupport"],
|
||||
exclude: ["CMakeLists.txt"]
|
||||
// MARK: - Test executables
|
||||
.executableTarget(
|
||||
name: "ComplexLog",
|
||||
dependencies: ["Numerics", "_TestSupport"],
|
||||
path: "Tests/Executable/ComplexLog"
|
||||
),
|
||||
|
||||
.executableTarget(
|
||||
name: "ComplexLog1p",
|
||||
dependencies: ["Numerics", "_TestSupport"],
|
||||
path: "Tests/Executable/ComplexLog1p"
|
||||
)
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,111 @@
|
||||
// swift-tools-version:5.4
|
||||
//===--- Package.swift ----------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let excludedFilenames = ["CMakeLists.txt", "README.md"]
|
||||
|
||||
let package = Package(
|
||||
|
||||
name: "swift-numerics",
|
||||
products: [
|
||||
.library(name: "BigIntModule", targets: ["BigIntModule"]),
|
||||
.library(name: "ComplexModule", targets: ["ComplexModule"]),
|
||||
.library(name: "Numerics", targets: ["Numerics"]),
|
||||
.library(name: "RealModule", targets: ["RealModule"]),
|
||||
],
|
||||
|
||||
targets: [
|
||||
// MARK: - Public API
|
||||
.target(
|
||||
name: "BigIntModule",
|
||||
dependencies: [],
|
||||
exclude: excludedFilenames
|
||||
),
|
||||
|
||||
.target(
|
||||
name: "ComplexModule",
|
||||
dependencies: ["RealModule"],
|
||||
exclude: excludedFilenames
|
||||
),
|
||||
|
||||
.target(
|
||||
name: "IntegerUtilities",
|
||||
dependencies: [],
|
||||
exclude: excludedFilenames
|
||||
),
|
||||
|
||||
.target(
|
||||
name: "Numerics",
|
||||
dependencies: ["ComplexModule", "IntegerUtilities", "RealModule", "BigIntModule"],
|
||||
exclude: excludedFilenames
|
||||
),
|
||||
|
||||
.target(
|
||||
name: "RealModule",
|
||||
dependencies: ["_NumericsShims"],
|
||||
exclude: excludedFilenames,
|
||||
linkerSettings: [
|
||||
.linkedLibrary("m", .when(platforms: [.linux, .android]))
|
||||
]
|
||||
),
|
||||
|
||||
// MARK: - Implementation details
|
||||
.target(
|
||||
name: "_NumericsShims",
|
||||
exclude: excludedFilenames
|
||||
),
|
||||
|
||||
.target(
|
||||
name: "_TestSupport",
|
||||
dependencies: ["Numerics"],
|
||||
exclude: ["CMakeLists.txt"]
|
||||
),
|
||||
|
||||
// MARK: - Unit test bundles
|
||||
.testTarget(
|
||||
name: "BigIntTests",
|
||||
dependencies: ["BigIntModule"]
|
||||
),
|
||||
|
||||
.testTarget(
|
||||
name: "ComplexTests",
|
||||
dependencies: ["_TestSupport"],
|
||||
exclude: ["CMakeLists.txt"]
|
||||
),
|
||||
|
||||
.testTarget(
|
||||
name: "IntegerUtilitiesTests",
|
||||
dependencies: ["IntegerUtilities", "_TestSupport"],
|
||||
exclude: ["CMakeLists.txt"]
|
||||
),
|
||||
|
||||
.testTarget(
|
||||
name: "RealTests",
|
||||
dependencies: ["_TestSupport"],
|
||||
exclude: ["CMakeLists.txt"]
|
||||
),
|
||||
|
||||
// MARK: - Test executables
|
||||
.executableTarget(
|
||||
name: "ComplexLog",
|
||||
dependencies: ["Numerics", "_TestSupport"],
|
||||
path: "Tests/Executable/ComplexLog"
|
||||
),
|
||||
|
||||
.executableTarget(
|
||||
name: "ComplexLog1p",
|
||||
dependencies: ["Numerics", "_TestSupport"],
|
||||
path: "Tests/Executable/ComplexLog1p"
|
||||
)
|
||||
]
|
||||
)
|
||||
@@ -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", branch: "Quaternions"),
|
||||
.package(url: "https://github.com/apple/swift-numerics", from: "1.0.0"),
|
||||
```
|
||||
|
||||
2. Add `Numerics` as a dependency for your target:
|
||||
@@ -84,7 +84,7 @@ Swift Numerics uses GitHub issues to track bugs and features. We use pull reques
|
||||
1. Raise an issue with the [new module] tag.
|
||||
2. Raise a PR with an implementation sketch.
|
||||
3. Once you have some consensus, ask an admin to create a feature branch against which PRs can be raised.
|
||||
4. When the design has stabilized and is functional enough to be useful, raise a PR to merge the new module to main.
|
||||
4. When the design has stabilized and is functional enough to be useful, raise a PR to merge the new module to master.
|
||||
|
||||
### How to propose a new feature for an existing module
|
||||
|
||||
@@ -105,8 +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. [`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)
|
||||
3. [`IntegerUtilities`](Sources/IntegerUtilities/README.md) (on main only, not yet present in a released tag)
|
||||
4. [`BigIntModule`](Sources/BigIntModule/README.md) (on branch only)
|
||||
|
||||
## Future expansion
|
||||
|
||||
|
||||
@@ -0,0 +1,810 @@
|
||||
//===--- BigInt.swift -----------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
public struct BigInt: SignedInteger {
|
||||
|
||||
public typealias Words = [UInt]
|
||||
|
||||
public private(set) var words: Words
|
||||
|
||||
@usableFromInline
|
||||
internal init(_uncheckedWords: Words) {
|
||||
self.words = _uncheckedWords
|
||||
}
|
||||
|
||||
public init<T>(bitPattern source: T) where T: BinaryInteger {
|
||||
words = Words(source.words)
|
||||
BigInt._dropExcessWords(words: &words)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal var _isNegative: Bool {
|
||||
words[words.endIndex - 1] > Int.max
|
||||
}
|
||||
|
||||
private static let _digits: [BigInt] = (0 ... 36).map {
|
||||
BigInt(_uncheckedWords: [UInt(bitPattern: $0)])
|
||||
}
|
||||
|
||||
private static let _digitRadix = BigInt(_uncheckedWords: [0, 1])
|
||||
}
|
||||
|
||||
// MARK: - Basic Behaviors
|
||||
|
||||
extension BigInt: Equatable {
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: BigInt, rhs: BigInt) -> Bool {
|
||||
lhs.words == rhs.words
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func != (lhs: BigInt, rhs: BigInt) -> Bool {
|
||||
!(lhs == rhs)
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: Hashable {
|
||||
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(words)
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: Comparable {
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: BigInt, rhs: BigInt) -> Bool {
|
||||
let lhsNegative = lhs._isNegative
|
||||
let rhsNegative = rhs._isNegative
|
||||
|
||||
if lhsNegative && !rhsNegative { return true }
|
||||
if rhsNegative && !lhsNegative { return false }
|
||||
|
||||
if (lhsNegative && rhsNegative) || (!lhsNegative && !rhsNegative) {
|
||||
if lhs.words.count > rhs.words.count {
|
||||
return lhsNegative ? true : false
|
||||
}
|
||||
if lhs.words.count < rhs.words.count {
|
||||
return lhsNegative ? false : true
|
||||
}
|
||||
|
||||
for i in stride(from: lhs.words.count - 1, through: 0, by: -1) {
|
||||
if lhs.words[i] > rhs.words[i] {
|
||||
return false
|
||||
} else if lhs.words[i] < rhs.words[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: LosslessStringConvertible {
|
||||
|
||||
public init?(_ description: String) {
|
||||
self.init(description, radix: 10)
|
||||
}
|
||||
|
||||
public init?<T>(_ description: T, radix: Int = 10) where T: StringProtocol {
|
||||
precondition(2 ... 36 ~= radix, "Radix not in range 2 ... 36")
|
||||
|
||||
self = 0
|
||||
|
||||
let isNegative = description.hasPrefix("-")
|
||||
let hasPrefix = isNegative || description.hasPrefix("+")
|
||||
let utf8 = description.utf8.dropFirst(hasPrefix ? 1 : 0)
|
||||
guard !utf8.isEmpty else { return nil }
|
||||
|
||||
for var byte in utf8 {
|
||||
switch byte {
|
||||
case UInt8(ascii: "0") ... UInt8(ascii: "9"):
|
||||
byte -= UInt8(ascii: "0")
|
||||
case UInt8(ascii: "A") ... UInt8(ascii: "Z"):
|
||||
byte -= UInt8(ascii: "A")
|
||||
byte += 10
|
||||
case UInt8(ascii: "a") ... UInt8(ascii: "z"):
|
||||
byte -= UInt8(ascii: "a")
|
||||
byte += 10
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
guard byte < radix else { return nil }
|
||||
self *= BigInt._digits[radix]
|
||||
self += BigInt._digits[Int(byte)]
|
||||
}
|
||||
|
||||
if isNegative {
|
||||
self.negate()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: Decodable {
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let singleValueContainer = try decoder.singleValueContainer()
|
||||
let description = try singleValueContainer.decode(String.self)
|
||||
guard let result = BigInt(description) else {
|
||||
throw DecodingError.dataCorruptedError(
|
||||
in: singleValueContainer,
|
||||
debugDescription: "BigInt(\(description.debugDescription)) failed")
|
||||
}
|
||||
self = result
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: Encodable {
|
||||
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var singleValueContainer = encoder.singleValueContainer()
|
||||
try singleValueContainer.encode(description)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Numeric Protocols
|
||||
|
||||
extension BigInt: ExpressibleByIntegerLiteral {
|
||||
|
||||
public init(integerLiteral value: Int) {
|
||||
if value >= 0, value < BigInt._digits.count {
|
||||
self = BigInt._digits[value]
|
||||
} else {
|
||||
words = [UInt(bitPattern: value)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: AdditiveArithmetic {
|
||||
|
||||
@inlinable
|
||||
public static func + (lhs: BigInt, rhs: BigInt) -> BigInt {
|
||||
var result = lhs
|
||||
result += rhs
|
||||
return result
|
||||
}
|
||||
|
||||
public static func += (lhs: inout BigInt, rhs: BigInt) {
|
||||
if lhs.words.count == 1, rhs.words.count == 1 {
|
||||
let lhsWord = lhs.words[0]
|
||||
let rhsWord = rhs.words[0]
|
||||
|
||||
let (result, isOverflow) = lhsWord.addingReportingOverflow(rhsWord)
|
||||
|
||||
if !isOverflow && result < Int.max {
|
||||
lhs.words[0] = result
|
||||
return
|
||||
}
|
||||
let knownNegativeResult = lhsWord > Int.max && rhsWord > Int.max
|
||||
|
||||
if lhsWord > Int.max || rhsWord > Int.max, !knownNegativeResult {
|
||||
// positive + negative is always smaller, so overflow is a red herring
|
||||
lhs.words[0] = result
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var isOverflow = false
|
||||
|
||||
var rhsWords = rhs.words
|
||||
|
||||
lhs.words.append(lhs._isNegative ? UInt.max : 0)
|
||||
rhsWords.append(rhs._isNegative ? UInt.max : 0)
|
||||
|
||||
BigInt._signExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
var temp: UInt = 0
|
||||
for index in 0 ..< lhs.words.count {
|
||||
var carryOverflow = false
|
||||
|
||||
if isOverflow {
|
||||
(temp, carryOverflow) = rhsWords[index].addingReportingOverflow(1)
|
||||
} else {
|
||||
temp = rhsWords[index]
|
||||
}
|
||||
|
||||
(lhs.words[index], isOverflow) = lhs.words[index].addingReportingOverflow(temp)
|
||||
|
||||
isOverflow = carryOverflow || isOverflow
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func - (lhs: BigInt, rhs: BigInt) -> BigInt {
|
||||
var result = lhs
|
||||
result -= rhs
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func -= (lhs: inout BigInt, rhs: BigInt) {
|
||||
lhs += -rhs
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: Numeric {
|
||||
|
||||
public init?<T>(exactly source: T) where T: BinaryInteger {
|
||||
self.init(source)
|
||||
}
|
||||
|
||||
public var magnitude: BigInt { _isNegative ? -self : self }
|
||||
|
||||
public static func * (lhs: BigInt, rhs: BigInt) -> BigInt {
|
||||
let lhsIsNeg = lhs.words[lhs.words.endIndex - 1] > Int.max
|
||||
let rhsIsNeg = rhs.words[rhs.words.endIndex - 1] > Int.max
|
||||
|
||||
let lhsWords = lhsIsNeg ? (-lhs).words : lhs.words
|
||||
let rhsWords = rhsIsNeg ? (-rhs).words : rhs.words
|
||||
|
||||
let count = lhsWords.count + rhsWords.count + 1
|
||||
var newWords = Words(repeating: 0, count: count)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
var carry: UInt = 0
|
||||
var digit: UInt = 0
|
||||
|
||||
var lastJ: Int = 0
|
||||
for j in i ..< (lhsWords.count + i) {
|
||||
var (high, low) = rhsWords[i].multipliedFullWidth(by: lhsWords[j - i])
|
||||
var isOverflow: Bool
|
||||
(digit, isOverflow) = low.addingReportingOverflow(newWords[j])
|
||||
if isOverflow {
|
||||
high += 1
|
||||
}
|
||||
|
||||
(digit, isOverflow) = digit.addingReportingOverflow(carry)
|
||||
if isOverflow {
|
||||
high += 1
|
||||
}
|
||||
|
||||
carry = high
|
||||
newWords[j] = digit
|
||||
lastJ = j
|
||||
}
|
||||
|
||||
if carry != 0 {
|
||||
let isOverflow: Bool
|
||||
(digit, isOverflow) = newWords[lastJ + 1].addingReportingOverflow(carry)
|
||||
if isOverflow {
|
||||
carry = 1
|
||||
}
|
||||
newWords[lastJ + 1] = digit
|
||||
}
|
||||
}
|
||||
|
||||
for i in stride(from: count - 1, through: 1, by: -1) {
|
||||
if newWords[i] == 0, newWords[i - 1] <= Int.max {
|
||||
newWords.removeLast()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if lhsIsNeg || rhsIsNeg, !(lhsIsNeg && rhsIsNeg) {
|
||||
return -BigInt(_uncheckedWords: newWords)
|
||||
}
|
||||
|
||||
return BigInt(_uncheckedWords: newWords)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func *= (lhs: inout BigInt, rhs: BigInt) {
|
||||
lhs = lhs * rhs
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: SignedNumeric {
|
||||
|
||||
public mutating func negate() {
|
||||
var isOverflow = true
|
||||
for i in 0 ..< words.count {
|
||||
if isOverflow {
|
||||
(words[i], isOverflow) = (~words[i]).addingReportingOverflow(1)
|
||||
} else {
|
||||
words[i] = ~words[i]
|
||||
}
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &words)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static prefix func - (x: BigInt) -> BigInt {
|
||||
var result = x
|
||||
result.negate()
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: BinaryInteger {
|
||||
|
||||
public init?<T>(exactly source: T) where T: BinaryFloatingPoint {
|
||||
guard source.isFinite, source == source.rounded(.towardZero) else {
|
||||
return nil
|
||||
}
|
||||
self.init(source)
|
||||
}
|
||||
|
||||
public init<T>(_ source: T) where T: BinaryFloatingPoint {
|
||||
precondition(
|
||||
source.isFinite,
|
||||
"""
|
||||
\(type(of: source)) value cannot be converted to BigInt because it is \
|
||||
either infinite or NaN
|
||||
""")
|
||||
|
||||
let isNegative = source < 0.0
|
||||
var float = isNegative ? -source : source
|
||||
|
||||
if let _ = UInt(exactly: T.greatestFiniteMagnitude) {
|
||||
words = [UInt(float)]
|
||||
} else {
|
||||
var words = Words()
|
||||
let radix = T(sign: .plus, exponent: T.Exponent(UInt.bitWidth), significand: 1)
|
||||
repeat {
|
||||
let digit = UInt(float.truncatingRemainder(dividingBy: radix))
|
||||
words.append(digit)
|
||||
float = (float / radix).rounded(.towardZero)
|
||||
} while float != 0
|
||||
|
||||
if let last = words.last, last >= Int.max {
|
||||
words.append(0)
|
||||
}
|
||||
self.words = words
|
||||
}
|
||||
|
||||
if isNegative {
|
||||
self.negate()
|
||||
}
|
||||
}
|
||||
|
||||
public init<T>(_ source: T) where T: BinaryInteger {
|
||||
if source >= 0, source < BigInt._digits.count {
|
||||
self = BigInt._digits[Int(source)]
|
||||
} else {
|
||||
words = Words(source.words)
|
||||
if source > 0 && source.words[source.words.endIndex - 1] > Int.max {
|
||||
words.append(0)
|
||||
}
|
||||
// needed to handle sign-extended multi-word numbers that
|
||||
// actually fit in a single word
|
||||
BigInt._dropExcessWords(words: &words)
|
||||
}
|
||||
}
|
||||
|
||||
public init<T>(clamping source: T) where T: BinaryInteger {
|
||||
self.init(source)
|
||||
}
|
||||
|
||||
public init<T>(truncatingIfNeeded source: T) where T: BinaryInteger {
|
||||
words = Words(source.words)
|
||||
}
|
||||
|
||||
public var bitWidth: Int { words.count * UInt.bitWidth }
|
||||
|
||||
public var trailingZeroBitCount: Int {
|
||||
var totalZeros = 0
|
||||
for word in words {
|
||||
if word == 0 {
|
||||
totalZeros += UInt.bitWidth
|
||||
} else {
|
||||
totalZeros += word.trailingZeroBitCount
|
||||
break
|
||||
}
|
||||
}
|
||||
return totalZeros
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func / (lhs: BigInt, rhs: BigInt) -> BigInt {
|
||||
let (result, _) = _div(lhs: lhs, rhs: rhs)
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func /= (lhs: inout BigInt, rhs: BigInt) {
|
||||
lhs = lhs / rhs
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func % (lhs: BigInt, rhs: BigInt) -> BigInt {
|
||||
let (_, result) = _div(lhs: lhs, rhs: rhs)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func %= (lhs: inout BigInt, rhs: BigInt) {
|
||||
lhs = lhs % rhs
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static prefix func ~ (x: BigInt) -> BigInt {
|
||||
let newWords = x.words.map { ~$0 }
|
||||
return BigInt(_uncheckedWords: Words(newWords))
|
||||
}
|
||||
|
||||
public static func &= (lhs: inout BigInt, rhs: BigInt) {
|
||||
var rhsWords = rhs.words
|
||||
BigInt._signExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
lhs.words[i] &= rhsWords[i]
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func |= (lhs: inout BigInt, rhs: BigInt) {
|
||||
var rhsWords = rhs.words
|
||||
BigInt._signExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
lhs.words[i] |= rhsWords[i]
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func ^= (lhs: inout BigInt, rhs: BigInt) {
|
||||
var rhsWords = rhs.words
|
||||
BigInt._signExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
lhs.words[i] &= rhsWords[i]
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func <<= <RHS>(lhs: inout BigInt, rhs: RHS) where RHS: BinaryInteger {
|
||||
if rhs.signum() < 0 {
|
||||
lhs >>= rhs.magnitude
|
||||
return
|
||||
}
|
||||
|
||||
let wordLength = UInt.bitWidth
|
||||
let isNegative = lhs._isNegative
|
||||
|
||||
let (fullWords, remainder) = rhs.quotientAndRemainder(dividingBy: RHS(wordLength))
|
||||
lhs.words = Words(repeating: 0, count: Int(fullWords)) + lhs.words + [isNegative ? UInt.max : 0]
|
||||
|
||||
if remainder > 0 {
|
||||
var value: UInt = 0
|
||||
for i in 0 ..< lhs.words.count {
|
||||
let temp = lhs.words[i] >> (wordLength - Int(remainder))
|
||||
lhs.words[i] <<= Int(remainder)
|
||||
if i > 0 {
|
||||
lhs.words[i] &= UInt.max << Int(remainder)
|
||||
lhs.words[i] |= value
|
||||
}
|
||||
|
||||
value = temp
|
||||
}
|
||||
|
||||
if isNegative {
|
||||
lhs.words[lhs.words.count - 1] |= (UInt.max << Int(remainder))
|
||||
}
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func >>= <RHS>(lhs: inout BigInt, rhs: RHS) where RHS: BinaryInteger {
|
||||
if rhs.signum() < 0 {
|
||||
lhs <<= rhs.magnitude
|
||||
return
|
||||
}
|
||||
|
||||
let wordLength = UInt.bitWidth
|
||||
let isNegative = lhs._isNegative
|
||||
|
||||
let (fullWords, remainder) = rhs.quotientAndRemainder(dividingBy: RHS(wordLength))
|
||||
if fullWords < lhs.words.count {
|
||||
lhs.words.removeFirst(Int(fullWords))
|
||||
} else {
|
||||
lhs = isNegative ? -1 : 0
|
||||
return
|
||||
}
|
||||
|
||||
if remainder > 0 {
|
||||
let mask = ~(UInt.max << remainder)
|
||||
var value: UInt = 0
|
||||
for i in stride(from: lhs.words.count - 1, through: 0, by: -1) {
|
||||
let temp = lhs.words[i] & mask
|
||||
lhs.words[i] >>= remainder
|
||||
lhs.words[i] |= (value << (UInt.bitWidth - Int(remainder)))
|
||||
value = temp
|
||||
}
|
||||
}
|
||||
|
||||
if isNegative {
|
||||
lhs.words[lhs.words.count - 1] |= (UInt.max << (UInt.bitWidth - Int(remainder)))
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func quotientAndRemainder(dividingBy rhs: BigInt) -> (quotient: BigInt, remainder: BigInt) {
|
||||
return BigInt._div(lhs: self, rhs: rhs)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func signum() -> BigInt { _isNegative ? -1 : (self == 0) ? 0 : 1 }
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension BigInt {
|
||||
|
||||
/// See _The Art of Computer Programming_ volume 2 by Donald Knuth, Section 4.3.1: The Classical Algorithms
|
||||
private static func _findQhat(
|
||||
high: UInt,
|
||||
low: UInt.Magnitude,
|
||||
divisor: UInt,
|
||||
nextVdigit: UInt,
|
||||
nextUdigit: UInt
|
||||
) -> UInt {
|
||||
var qhat: Array<UInt>
|
||||
var rhat: Array<UInt>
|
||||
if high >= divisor {
|
||||
let v = divisor
|
||||
let u = [low, high]
|
||||
var r: UInt = 0
|
||||
qhat = Words(repeating: 0, count: 2)
|
||||
for j in (0...1).reversed() {
|
||||
let uj = u[j]
|
||||
(qhat[j], r) = v.dividingFullWidth((r, uj))
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &qhat)
|
||||
rhat = [r]
|
||||
} else {
|
||||
let (qhatWord, rhatWord) = divisor.dividingFullWidth((high, low))
|
||||
qhat = [qhatWord]
|
||||
rhat = [rhatWord]
|
||||
}
|
||||
|
||||
repeat {
|
||||
var qhatTooLarge = false
|
||||
|
||||
if qhat.count > 1 {
|
||||
qhatTooLarge = true
|
||||
} else {
|
||||
// All of the following is computing and checking qhat*v_n-2 > rhat*b + u_j+n-2
|
||||
// from TAoCP Volume 2 Section 4.3.1, Algorithm D, step D3
|
||||
let (comp_lhs_hi, comp_lhs_lo) = qhat[0].multipliedFullWidth(by: nextVdigit)
|
||||
|
||||
if comp_lhs_hi > rhat[0] {
|
||||
qhatTooLarge = true
|
||||
} else if comp_lhs_hi == rhat[0] && comp_lhs_lo > nextUdigit {
|
||||
qhatTooLarge = true
|
||||
}
|
||||
}
|
||||
|
||||
// high >= divisor is standing in for the test qhat >= b from Algorithm D step D3
|
||||
if qhatTooLarge {
|
||||
// begin qhat -= 1
|
||||
if qhat.count == 1 {
|
||||
qhat[0] -= 1
|
||||
} else {
|
||||
let (qlow, underflow) = qhat[0].subtractingReportingOverflow(1)
|
||||
qhat[0] = qlow
|
||||
if qhat[1] > 0 && underflow {
|
||||
qhat[1] -= 1
|
||||
if qhat[1] == 0 {
|
||||
qhat.remove(at: 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
// end qhat -= 1
|
||||
|
||||
// begin rhat += divisor
|
||||
let (rhatResult, overflow) : (UInt, Bool)
|
||||
if rhat.count == 1 || rhat[1] == 0 {
|
||||
(rhatResult, overflow) = rhat[0].addingReportingOverflow(divisor)
|
||||
rhat[0] = rhatResult
|
||||
if overflow {
|
||||
rhat.append(1)
|
||||
}
|
||||
} // we don't need an else because rhat is already larger than BigInt._digitRadix
|
||||
// end rhat += divisor
|
||||
} else {
|
||||
break
|
||||
}
|
||||
} while rhat.count == 1 // equivalent to rhat < b
|
||||
|
||||
return qhat[0]
|
||||
}
|
||||
|
||||
/// See _The Art of Computer Programming_ volume 2 by Donald Knuth, Section 4.3.1: The Classical Algorithms
|
||||
@usableFromInline
|
||||
internal static func _div(lhs: BigInt, rhs: BigInt) -> (quotient: BigInt, remainder: BigInt) {
|
||||
precondition(rhs != _digits[0], "Division by zero error!")
|
||||
|
||||
if lhs.words.count == 1, rhs.words.count == 1 {
|
||||
let (quot, rem) = Int(bitPattern: lhs.words[0]).quotientAndRemainder(dividingBy: Int(bitPattern: rhs.words[0]))
|
||||
return (BigInt(_uncheckedWords: [UInt(bitPattern: quot)]), BigInt(_uncheckedWords: [UInt(bitPattern: rem)]))
|
||||
}
|
||||
|
||||
let lhsIsNeg = lhs._isNegative
|
||||
let rhsIsNeg = rhs._isNegative
|
||||
|
||||
var lhsWords = lhsIsNeg ? (-lhs).words : lhs.words
|
||||
var rhsWords = rhsIsNeg ? (-rhs).words : rhs.words
|
||||
|
||||
// See the answer to exercise 16 in Section 4.3.1 of TAOCP
|
||||
if rhsWords.count == 1 || (rhsWords.count == 2 && rhsWords[1] == 0) {
|
||||
let v = rhsWords[0]
|
||||
let u = lhsWords
|
||||
var r: UInt = 0
|
||||
var quot = Words(repeating: 0, count: u.count)
|
||||
for j in (0...(u.count - 1)).reversed() {
|
||||
let uj = u[j]
|
||||
(quot[j], r) = v.dividingFullWidth((r, uj))
|
||||
}
|
||||
|
||||
if quot[u.count - 1] > UInt(Int.max) {
|
||||
quot.append(0)
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: ")
|
||||
return (quotient: BigInt(_uncheckedWords: quot), remainder: BigInt(r))
|
||||
}
|
||||
|
||||
while rhsWords[rhsWords.endIndex - 1] == 0 {
|
||||
rhsWords.removeLast()
|
||||
}
|
||||
|
||||
if rhsWords.count > lhsWords.count { return (0, lhs) }
|
||||
|
||||
if lhsWords.count <= rhsWords.count {
|
||||
for _ in 0 ... (rhsWords.count - lhsWords.count) {
|
||||
lhsWords.append(0)
|
||||
}
|
||||
}
|
||||
|
||||
let m = lhsWords.count - rhsWords.count
|
||||
let n = rhsWords.count
|
||||
|
||||
let bitWidth = UInt(UInt.bitWidth)
|
||||
|
||||
let s = UInt(rhsWords[n - 1].leadingZeroBitCount)
|
||||
let rn = UnsafeMutablePointer<UInt>.allocate(capacity: n)
|
||||
rn.initialize(repeating: 0, count: n)
|
||||
defer { rn.deallocate() }
|
||||
for i in (1 ... (n - 1)).reversed() {
|
||||
rn[i] = (rhsWords[i] << s) | (rhsWords[i - 1] >> (bitWidth - s))
|
||||
}
|
||||
rn[0] = rhsWords[0] << s
|
||||
|
||||
let ln = UnsafeMutablePointer<UInt>.allocate(capacity: m + n + 1)
|
||||
ln.initialize(repeating: 0, count: m + n + 1)
|
||||
defer { ln.deallocate() }
|
||||
ln[m + n] = lhsWords[m + n - 1] >> (bitWidth - s)
|
||||
for i in (1 ... (m + n - 1)).reversed() {
|
||||
ln[i] = (lhsWords[i] << s) | (lhsWords[i - 1] >> (bitWidth - s))
|
||||
}
|
||||
ln[0] = lhsWords[0] << s
|
||||
|
||||
let resultSize = m + 1
|
||||
var quot = Words(repeating: 0, count: resultSize)
|
||||
|
||||
for j in (0 ... m).reversed() {
|
||||
let qhat = _findQhat(
|
||||
high: ln[j + n],
|
||||
low: UInt.Magnitude(ln[j + n - 1]),
|
||||
divisor: rn[n - 1],
|
||||
nextVdigit: rn[n - 2],
|
||||
nextUdigit: ln[j + n - 2])
|
||||
|
||||
var carry: UInt = 0
|
||||
var isOverflow = false
|
||||
var borrow: UInt = 0
|
||||
var underflow = false
|
||||
for i in 0 ..< n {
|
||||
if borrow > 0 {
|
||||
(ln[i + j], underflow) = ln[i + j].subtractingReportingOverflow(borrow)
|
||||
borrow = underflow ? 1 : 0
|
||||
}
|
||||
|
||||
var (pHigh, pLow) = qhat.multipliedFullWidth(by: rn[i])
|
||||
(pLow, isOverflow) = pLow.addingReportingOverflow(carry)
|
||||
if isOverflow {
|
||||
pHigh += 1
|
||||
}
|
||||
|
||||
(ln[i + j], underflow) = ln[i + j].subtractingReportingOverflow(pLow)
|
||||
if underflow {
|
||||
borrow += 1
|
||||
}
|
||||
|
||||
carry = pHigh
|
||||
}
|
||||
|
||||
(ln[j + n], underflow) = ln[j + n].subtractingReportingOverflow(carry + borrow)
|
||||
|
||||
if underflow {
|
||||
let newQhat = qhat - 1
|
||||
|
||||
carry = 0
|
||||
var total: UInt = 0
|
||||
for i in 0 ..< n {
|
||||
(total, isOverflow) = ln[i + j].addingReportingOverflow(carry)
|
||||
carry = isOverflow ? 1 : 0
|
||||
(ln[i + j], isOverflow) = total.addingReportingOverflow(rn[i])
|
||||
if carry == 0 { carry = isOverflow ? 1 : 0 }
|
||||
}
|
||||
(ln[j + n], _) = ln[j + n].addingReportingOverflow(carry)
|
||||
|
||||
quot[j] = newQhat
|
||||
} else {
|
||||
quot[j] = qhat
|
||||
}
|
||||
}
|
||||
|
||||
var rem = Words(repeating: 0, count: n)
|
||||
|
||||
for i in 0 ..< (n - 1) {
|
||||
rem[i] = (ln[i] >> s) | ln[i + 1] << (bitWidth - s)
|
||||
}
|
||||
rem[n - 1] = ln[n - 1] >> s
|
||||
|
||||
if rem[n - 1] > UInt(Int.max) {
|
||||
rem.append(0)
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: ")
|
||||
BigInt._dropExcessWords(words: &rem)
|
||||
|
||||
return (BigInt(_uncheckedWords: quot), BigInt(_uncheckedWords: rem))
|
||||
}
|
||||
|
||||
private static func _signExtend(lhsWords: inout Words, rhsWords: inout Words) {
|
||||
let lhsIsNeg = (lhsWords.last ?? 0) >> (UInt.bitWidth - Int(1)) == 1
|
||||
let rhsIsNeg = (rhsWords.last ?? 0) >> (UInt.bitWidth - Int(1)) == 1
|
||||
|
||||
if lhsWords.count > rhsWords.count {
|
||||
for _ in 0 ..< (lhsWords.count - rhsWords.count) {
|
||||
rhsIsNeg ? rhsWords.append(UInt.max) : rhsWords.append(0)
|
||||
}
|
||||
} else if rhsWords.count > lhsWords.count {
|
||||
for _ in 0 ..< (rhsWords.count - lhsWords.count) {
|
||||
lhsIsNeg ? lhsWords.append(UInt.max) : lhsWords.append(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _dropExcessWords(words: inout Words) {
|
||||
while words.count > 1, words[words.endIndex - 1] == 0 {
|
||||
if words[words.endIndex - 2] <= Int.max {
|
||||
words.removeLast()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
while words.count > 1, words[words.endIndex - 1] == UInt.max {
|
||||
if words[words.endIndex - 2] > Int.max {
|
||||
words.removeLast()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,751 @@
|
||||
//===--- BigUInt.swift ----------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
public struct BigUInt: UnsignedInteger {
|
||||
|
||||
public typealias Words = [UInt]
|
||||
|
||||
public private(set) var words: Words
|
||||
|
||||
@usableFromInline
|
||||
internal init(_uncheckedWords: Words) {
|
||||
self.words = _uncheckedWords
|
||||
}
|
||||
|
||||
public init<T>(bitPattern source: T) where T: BinaryInteger {
|
||||
words = Words(source.words)
|
||||
BigUInt._dropExcessWords(words: &words)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal var _isNegative: Bool {
|
||||
words[words.endIndex - 1] > Int.max
|
||||
}
|
||||
|
||||
private static let _digits: [BigUInt] = (0 ... 36).map {
|
||||
BigUInt(_uncheckedWords: [UInt(bitPattern: $0)])
|
||||
}
|
||||
|
||||
private static let _digitRadix = BigInt(_uncheckedWords: [0, 1])
|
||||
}
|
||||
|
||||
// MARK: - Basic Behaviors
|
||||
|
||||
extension BigUInt: Equatable {
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: BigUInt, rhs: BigUInt) -> Bool {
|
||||
lhs.words == rhs.words
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func != (lhs: BigUInt, rhs: BigUInt) -> Bool {
|
||||
!(lhs == rhs)
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: Hashable {
|
||||
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(words)
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: Comparable {
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: BigUInt, rhs: BigUInt) -> Bool {
|
||||
let lhsNegative = lhs._isNegative
|
||||
let rhsNegative = rhs._isNegative
|
||||
|
||||
if lhsNegative && !rhsNegative { return true }
|
||||
if rhsNegative && !lhsNegative { return false }
|
||||
|
||||
if (lhsNegative && rhsNegative) || (!lhsNegative && !rhsNegative) {
|
||||
if lhs.words.count > rhs.words.count {
|
||||
return lhsNegative ? true : false
|
||||
}
|
||||
if lhs.words.count < rhs.words.count {
|
||||
return lhsNegative ? false : true
|
||||
}
|
||||
|
||||
for i in stride(from: lhs.words.count - 1, through: 0, by: -1) {
|
||||
if lhs.words[i] > rhs.words[i] {
|
||||
return false
|
||||
} else if lhs.words[i] < rhs.words[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: LosslessStringConvertible {
|
||||
|
||||
public init?(_ description: String) {
|
||||
self.init(description, radix: 10)
|
||||
}
|
||||
|
||||
public init?<T>(_ description: T, radix: Int = 10) where T: StringProtocol {
|
||||
precondition(2 ... 36 ~= radix, "Radix not in range 2 ... 36")
|
||||
|
||||
self = 0
|
||||
|
||||
let hasPrefix = description.hasPrefix("+")
|
||||
let utf8 = description.utf8.dropFirst(hasPrefix ? 1 : 0)
|
||||
guard !utf8.isEmpty else { return nil }
|
||||
|
||||
for var byte in utf8 {
|
||||
switch byte {
|
||||
case UInt8(ascii: "0") ... UInt8(ascii: "9"):
|
||||
byte -= UInt8(ascii: "0")
|
||||
case UInt8(ascii: "A") ... UInt8(ascii: "Z"):
|
||||
byte -= UInt8(ascii: "A")
|
||||
byte += 10
|
||||
case UInt8(ascii: "a") ... UInt8(ascii: "z"):
|
||||
byte -= UInt8(ascii: "a")
|
||||
byte += 10
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
guard byte < radix else { return nil }
|
||||
self *= BigUInt._digits[radix]
|
||||
self += BigUInt._digits[Int(byte)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: Decodable {
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let singleValueContainer = try decoder.singleValueContainer()
|
||||
let description = try singleValueContainer.decode(String.self)
|
||||
guard let result = BigUInt(description) else {
|
||||
throw DecodingError.dataCorruptedError(
|
||||
in: singleValueContainer,
|
||||
debugDescription: "BigUInt(\(description.debugDescription)) failed")
|
||||
}
|
||||
self = result
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: Encodable {
|
||||
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var singleValueContainer = encoder.singleValueContainer()
|
||||
try singleValueContainer.encode(description)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Numeric Protocols
|
||||
|
||||
extension BigUInt: ExpressibleByIntegerLiteral {
|
||||
|
||||
public init(integerLiteral value: Int) {
|
||||
if value < BigUInt._digits.count {
|
||||
self = BigUInt._digits[value]
|
||||
} else {
|
||||
words = [UInt(bitPattern: value)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: AdditiveArithmetic {
|
||||
|
||||
@inlinable
|
||||
public static func + (lhs: BigUInt, rhs: BigUInt) -> BigUInt {
|
||||
var result = lhs
|
||||
result += rhs
|
||||
return result
|
||||
}
|
||||
|
||||
public static func += (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
if lhs.words.count == 1, rhs.words.count == 1 {
|
||||
let lhsWord = lhs.words[0]
|
||||
let rhsWord = rhs.words[0]
|
||||
|
||||
let (result, isOverflow) = lhsWord.addingReportingOverflow(rhsWord)
|
||||
|
||||
if !isOverflow && result < Int.max {
|
||||
lhs.words[0] = result
|
||||
return
|
||||
}
|
||||
let knownNegativeResult = lhsWord > Int.max && rhsWord > Int.max
|
||||
|
||||
if lhsWord > Int.max || rhsWord > Int.max, !knownNegativeResult {
|
||||
// positive + negative is always smaller, so overflow is a red herring
|
||||
lhs.words[0] = result
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var isOverflow = false
|
||||
|
||||
var rhsWords = rhs.words
|
||||
|
||||
lhs.words.append(0)
|
||||
rhsWords.append(0)
|
||||
BigUInt._zeroExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
|
||||
var temp: UInt = 0
|
||||
for index in 0 ..< lhs.words.count {
|
||||
var carryOverflow = false
|
||||
|
||||
if isOverflow {
|
||||
(temp, carryOverflow) = rhsWords[index].addingReportingOverflow(1)
|
||||
} else {
|
||||
temp = rhsWords[index]
|
||||
}
|
||||
|
||||
(lhs.words[index], isOverflow) = lhs.words[index].addingReportingOverflow(temp)
|
||||
|
||||
isOverflow = carryOverflow || isOverflow
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func - (lhs: BigUInt, rhs: BigUInt) -> BigUInt {
|
||||
var result = lhs
|
||||
result -= rhs
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func -= (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
lhs = .init(_uncheckedWords: (BigInt(_uncheckedWords: lhs.words) + -BigInt(_uncheckedWords: rhs.words)).words)
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: Numeric {
|
||||
|
||||
public init?<T>(exactly source: T) where T: BinaryInteger {
|
||||
self.init(source)
|
||||
}
|
||||
|
||||
public var magnitude: BigUInt { self }
|
||||
|
||||
public static func * (lhs: BigUInt, rhs: BigUInt) -> BigUInt {
|
||||
let lhsWords = lhs.words
|
||||
let rhsWords = rhs.words
|
||||
|
||||
let count = lhsWords.count + rhsWords.count + 1
|
||||
var newWords = Words(repeating: 0, count: count)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
var carry: UInt = 0
|
||||
var digit: UInt = 0
|
||||
|
||||
var lastJ: Int = 0
|
||||
for j in i ..< (lhsWords.count + i) {
|
||||
var (high, low) = rhsWords[i].multipliedFullWidth(by: lhsWords[j - i])
|
||||
var isOverflow: Bool
|
||||
(digit, isOverflow) = low.addingReportingOverflow(newWords[j])
|
||||
if isOverflow {
|
||||
high += 1
|
||||
}
|
||||
|
||||
(digit, isOverflow) = digit.addingReportingOverflow(carry)
|
||||
if isOverflow {
|
||||
high += 1
|
||||
}
|
||||
|
||||
carry = high
|
||||
newWords[j] = digit
|
||||
lastJ = j
|
||||
}
|
||||
|
||||
if carry != 0 {
|
||||
let isOverflow: Bool
|
||||
(digit, isOverflow) = newWords[lastJ + 1].addingReportingOverflow(carry)
|
||||
if isOverflow {
|
||||
carry = 1
|
||||
}
|
||||
newWords[lastJ + 1] = digit
|
||||
}
|
||||
}
|
||||
|
||||
for i in stride(from: count - 1, through: 1, by: -1) {
|
||||
if newWords[i] == 0, newWords[i - 1] <= Int.max {
|
||||
newWords.removeLast()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return BigUInt(_uncheckedWords: newWords)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func *= (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
lhs = lhs * rhs
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: BinaryInteger {
|
||||
|
||||
public init?<T>(exactly source: T) where T: BinaryFloatingPoint {
|
||||
guard source.isFinite, source == source.rounded(.towardZero) else {
|
||||
return nil
|
||||
}
|
||||
self.init(source)
|
||||
}
|
||||
|
||||
public init<T>(_ source: T) where T: BinaryFloatingPoint {
|
||||
precondition(
|
||||
source.isFinite && source >= 0.0,
|
||||
"""
|
||||
\(type(of: source)) value cannot be converted to BigUInt because it is \
|
||||
either infinite, NaN, or negative
|
||||
""")
|
||||
|
||||
var float = source
|
||||
|
||||
if let _ = UInt(exactly: T.greatestFiniteMagnitude) {
|
||||
words = [UInt(float)]
|
||||
} else {
|
||||
var words = Words()
|
||||
let radix = T(sign: .plus, exponent: T.Exponent(UInt.bitWidth), significand: 1)
|
||||
repeat {
|
||||
let digit = UInt(float.truncatingRemainder(dividingBy: radix))
|
||||
words.append(digit)
|
||||
float = (float / radix).rounded(.towardZero)
|
||||
} while float != 0
|
||||
|
||||
if let last = words.last, last >= Int.max {
|
||||
words.append(0)
|
||||
}
|
||||
self.words = words
|
||||
}
|
||||
}
|
||||
|
||||
public init<T>(_ source: T) where T: BinaryInteger {
|
||||
if source >= 0, source < BigUInt._digits.count {
|
||||
self = BigUInt._digits[Int(source)]
|
||||
} else {
|
||||
words = Words(source.words)
|
||||
if source > 0 && source.words[source.words.endIndex - 1] > Int.max {
|
||||
words.append(0)
|
||||
}
|
||||
// needed to handle sign-extended multi-word numbers that
|
||||
// actually fit in a single word
|
||||
BigUInt._dropExcessWords(words: &words)
|
||||
}
|
||||
}
|
||||
|
||||
public init<T>(clamping source: T) where T: BinaryInteger {
|
||||
self.init(source)
|
||||
}
|
||||
|
||||
public init<T>(truncatingIfNeeded source: T) where T: BinaryInteger {
|
||||
words = Words(source.words)
|
||||
}
|
||||
|
||||
public var bitWidth: Int { words.count * UInt.bitWidth }
|
||||
|
||||
public var trailingZeroBitCount: Int {
|
||||
var totalZeros = 0
|
||||
for word in words {
|
||||
if word == 0 {
|
||||
totalZeros += UInt.bitWidth
|
||||
} else {
|
||||
totalZeros += word.trailingZeroBitCount
|
||||
break
|
||||
}
|
||||
}
|
||||
return totalZeros
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func / (lhs: BigUInt, rhs: BigUInt) -> BigUInt {
|
||||
let (result, _) = _div(lhs: lhs, rhs: rhs)
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func /= (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
lhs = lhs / rhs
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func % (lhs: BigUInt, rhs: BigUInt) -> BigUInt {
|
||||
let (_, result) = _div(lhs: lhs, rhs: rhs)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func %= (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
lhs = lhs % rhs
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static prefix func ~ (x: BigUInt) -> BigUInt {
|
||||
let newWords = x.words.map { ~$0 }
|
||||
return BigUInt(_uncheckedWords: Words(newWords))
|
||||
}
|
||||
|
||||
public static func &= (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
var rhsWords = rhs.words
|
||||
BigUInt._zeroExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
lhs.words[i] &= rhsWords[i]
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func |= (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
var rhsWords = rhs.words
|
||||
BigUInt._zeroExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
lhs.words[i] |= rhsWords[i]
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func ^= (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
var rhsWords = rhs.words
|
||||
BigUInt._zeroExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
lhs.words[i] &= rhsWords[i]
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func <<= <RHS>(lhs: inout BigUInt, rhs: RHS) where RHS: BinaryInteger {
|
||||
if rhs.signum() < 0 {
|
||||
lhs >>= rhs.magnitude
|
||||
return
|
||||
}
|
||||
|
||||
let wordLength = UInt.bitWidth
|
||||
|
||||
let (fullWords, remainder) = rhs.quotientAndRemainder(dividingBy: RHS(wordLength))
|
||||
lhs.words = Words(repeating: 0, count: Int(fullWords)) + lhs.words + [0]
|
||||
|
||||
if remainder > 0 {
|
||||
var value: UInt = 0
|
||||
for i in 0 ..< lhs.words.count {
|
||||
let temp = lhs.words[i] >> (wordLength - Int(remainder))
|
||||
lhs.words[i] <<= Int(remainder)
|
||||
if i > 0 {
|
||||
lhs.words[i] &= UInt.max << Int(remainder)
|
||||
lhs.words[i] |= value
|
||||
}
|
||||
|
||||
value = temp
|
||||
}
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func >>= <RHS>(lhs: inout BigUInt, rhs: RHS) where RHS: BinaryInteger {
|
||||
if rhs.signum() < 0 {
|
||||
lhs <<= rhs.magnitude
|
||||
return
|
||||
}
|
||||
|
||||
let wordLength = UInt.bitWidth
|
||||
|
||||
let (fullWords, remainder) = rhs.quotientAndRemainder(dividingBy: RHS(wordLength))
|
||||
if fullWords < lhs.words.count {
|
||||
lhs.words.removeFirst(Int(fullWords))
|
||||
} else {
|
||||
lhs = 0
|
||||
return
|
||||
}
|
||||
|
||||
if remainder > 0 {
|
||||
let mask = ~(UInt.max << remainder)
|
||||
var value: UInt = 0
|
||||
for i in stride(from: lhs.words.count - 1, through: 0, by: -1) {
|
||||
let temp = lhs.words[i] & mask
|
||||
lhs.words[i] >>= remainder
|
||||
lhs.words[i] |= (value << (UInt.bitWidth - Int(remainder)))
|
||||
value = temp
|
||||
}
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func quotientAndRemainder(dividingBy rhs: BigUInt) -> (quotient: BigUInt, remainder: BigUInt) {
|
||||
return BigUInt._div(lhs: self, rhs: rhs)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension BigUInt {
|
||||
|
||||
/// See _The Art of Computer Programming_ volume 2 by Donald Knuth, Section 4.3.1: The Classical Algorithms
|
||||
private static func _findQhat(
|
||||
high: UInt,
|
||||
low: UInt.Magnitude,
|
||||
divisor: UInt,
|
||||
nextVdigit: UInt,
|
||||
nextUdigit: UInt
|
||||
) -> UInt {
|
||||
var qhat: Array<UInt>
|
||||
var rhat: Array<UInt>
|
||||
if high >= divisor {
|
||||
let v = divisor
|
||||
let u = [low, high]
|
||||
var r: UInt = 0
|
||||
qhat = Words(repeating: 0, count: 2)
|
||||
for j in (0...1).reversed() {
|
||||
let uj = u[j]
|
||||
(qhat[j], r) = v.dividingFullWidth((r, uj))
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: &qhat)
|
||||
rhat = [r]
|
||||
} else {
|
||||
let (qhatWord, rhatWord) = divisor.dividingFullWidth((high, low))
|
||||
qhat = [qhatWord]
|
||||
rhat = [rhatWord]
|
||||
}
|
||||
|
||||
repeat {
|
||||
var qhatTooLarge = false
|
||||
|
||||
if qhat.count > 1 {
|
||||
qhatTooLarge = true
|
||||
} else {
|
||||
// All of the following is computing and checking qhat*v_n-2 > rhat*b + u_j+n-2
|
||||
// from TAoCP Volume 2 Section 4.3.1, Algorithm D, step D3
|
||||
let (comp_lhs_hi, comp_lhs_lo) = qhat[0].multipliedFullWidth(by: nextVdigit)
|
||||
|
||||
if comp_lhs_hi > rhat[0] {
|
||||
qhatTooLarge = true
|
||||
} else if comp_lhs_hi == rhat[0] && comp_lhs_lo > nextUdigit {
|
||||
qhatTooLarge = true
|
||||
}
|
||||
}
|
||||
|
||||
// high >= divisor is standing in for the test qhat >= b from Algorithm D step D3
|
||||
if qhatTooLarge {
|
||||
// begin qhat -= 1
|
||||
if qhat.count == 1 {
|
||||
qhat[0] -= 1
|
||||
} else {
|
||||
let (qlow, underflow) = qhat[0].subtractingReportingOverflow(1)
|
||||
qhat[0] = qlow
|
||||
if qhat[1] > 0 && underflow {
|
||||
qhat[1] -= 1
|
||||
if qhat[1] == 0 {
|
||||
qhat.remove(at: 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
// end qhat -= 1
|
||||
|
||||
// begin rhat += divisor
|
||||
let (rhatResult, overflow) : (UInt, Bool)
|
||||
if rhat.count == 1 || rhat[1] == 0 {
|
||||
(rhatResult, overflow) = rhat[0].addingReportingOverflow(divisor)
|
||||
rhat[0] = rhatResult
|
||||
if overflow {
|
||||
rhat.append(1)
|
||||
}
|
||||
} // we don't need an else because rhat is already larger than BigInt._digitRadix
|
||||
// end rhat += divisor
|
||||
} else {
|
||||
break
|
||||
}
|
||||
} while rhat.count == 1 // equivalent to rhat < b
|
||||
|
||||
return qhat[0]
|
||||
}
|
||||
|
||||
/// See _The Art of Computer Programming_ volume 2 by Donald Knuth, Section 4.3.1: The Classical Algorithms
|
||||
@usableFromInline
|
||||
internal static func _div(lhs: BigUInt, rhs: BigUInt) -> (quotient: BigUInt, remainder: BigUInt) {
|
||||
precondition(rhs != _digits[0], "Division by zero error!")
|
||||
|
||||
if lhs.words.count == 1, rhs.words.count == 1 {
|
||||
let (quot, rem) = Int(bitPattern: lhs.words[0]).quotientAndRemainder(dividingBy: Int(bitPattern: rhs.words[0]))
|
||||
return (BigUInt(_uncheckedWords: [UInt(bitPattern: quot)]), BigUInt(_uncheckedWords: [UInt(bitPattern: rem)]))
|
||||
}
|
||||
|
||||
var lhsWords = lhs.words
|
||||
var rhsWords = rhs.words
|
||||
|
||||
// See the answer to exercise 16 in Section 4.3.1 of TAOCP
|
||||
if rhsWords.count == 1 || (rhsWords.count == 2 && rhsWords[1] == 0) {
|
||||
let v = rhsWords[0]
|
||||
let u = lhsWords
|
||||
var r: UInt = 0
|
||||
var quot = Words(repeating: 0, count: u.count)
|
||||
for j in (0...(u.count - 1)).reversed() {
|
||||
let uj = u[j]
|
||||
(quot[j], r) = v.dividingFullWidth((r, uj))
|
||||
}
|
||||
|
||||
if quot[u.count - 1] > UInt(Int.max) {
|
||||
quot.append(0)
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: ")
|
||||
return (quotient: BigUInt(_uncheckedWords: quot), remainder: BigUInt(r))
|
||||
}
|
||||
|
||||
while rhsWords[rhsWords.endIndex - 1] == 0 {
|
||||
rhsWords.removeLast()
|
||||
}
|
||||
|
||||
if rhsWords.count > lhsWords.count { return (0, lhs) }
|
||||
|
||||
if lhsWords.count <= rhsWords.count {
|
||||
for _ in 0 ... (rhsWords.count - lhsWords.count) {
|
||||
lhsWords.append(0)
|
||||
}
|
||||
}
|
||||
|
||||
let m = lhsWords.count - rhsWords.count
|
||||
let n = rhsWords.count
|
||||
|
||||
let bitWidth = UInt(UInt.bitWidth)
|
||||
|
||||
let s = UInt(rhsWords[n - 1].leadingZeroBitCount)
|
||||
let rn = UnsafeMutablePointer<UInt>.allocate(capacity: n)
|
||||
rn.initialize(repeating: 0, count: n)
|
||||
defer { rn.deallocate() }
|
||||
for i in (1 ... (n - 1)).reversed() {
|
||||
rn[i] = (rhsWords[i] << s) | (rhsWords[i - 1] >> (bitWidth - s))
|
||||
}
|
||||
rn[0] = rhsWords[0] << s
|
||||
|
||||
let ln = UnsafeMutablePointer<UInt>.allocate(capacity: m + n + 1)
|
||||
ln.initialize(repeating: 0, count: m + n + 1)
|
||||
defer { ln.deallocate() }
|
||||
ln[m + n] = lhsWords[m + n - 1] >> (bitWidth - s)
|
||||
for i in (1 ... (m + n - 1)).reversed() {
|
||||
ln[i] = (lhsWords[i] << s) | (lhsWords[i - 1] >> (bitWidth - s))
|
||||
}
|
||||
ln[0] = lhsWords[0] << s
|
||||
|
||||
let resultSize = m + 1
|
||||
var quot = Words(repeating: 0, count: resultSize)
|
||||
|
||||
for j in (0 ... m).reversed() {
|
||||
let qhat = _findQhat(
|
||||
high: ln[j + n],
|
||||
low: UInt.Magnitude(ln[j + n - 1]),
|
||||
divisor: rn[n - 1],
|
||||
nextVdigit: rn[n - 2],
|
||||
nextUdigit: ln[j + n - 2])
|
||||
|
||||
var carry: UInt = 0
|
||||
var isOverflow = false
|
||||
var borrow: UInt = 0
|
||||
var underflow = false
|
||||
for i in 0 ..< n {
|
||||
if borrow > 0 {
|
||||
(ln[i + j], underflow) = ln[i + j].subtractingReportingOverflow(borrow)
|
||||
borrow = underflow ? 1 : 0
|
||||
}
|
||||
|
||||
var (pHigh, pLow) = qhat.multipliedFullWidth(by: rn[i])
|
||||
(pLow, isOverflow) = pLow.addingReportingOverflow(carry)
|
||||
if isOverflow {
|
||||
pHigh += 1
|
||||
}
|
||||
|
||||
(ln[i + j], underflow) = ln[i + j].subtractingReportingOverflow(pLow)
|
||||
if underflow {
|
||||
borrow += 1
|
||||
}
|
||||
|
||||
carry = pHigh
|
||||
}
|
||||
|
||||
(ln[j + n], underflow) = ln[j + n].subtractingReportingOverflow(carry + borrow)
|
||||
|
||||
if underflow {
|
||||
let newQhat = qhat - 1
|
||||
|
||||
carry = 0
|
||||
var total: UInt = 0
|
||||
for i in 0 ..< n {
|
||||
(total, isOverflow) = ln[i + j].addingReportingOverflow(carry)
|
||||
carry = isOverflow ? 1 : 0
|
||||
(ln[i + j], isOverflow) = total.addingReportingOverflow(rn[i])
|
||||
if carry == 0 { carry = isOverflow ? 1 : 0 }
|
||||
}
|
||||
(ln[j + n], _) = ln[j + n].addingReportingOverflow(carry)
|
||||
|
||||
quot[j] = newQhat
|
||||
} else {
|
||||
quot[j] = qhat
|
||||
}
|
||||
}
|
||||
|
||||
var rem = Words(repeating: 0, count: n)
|
||||
|
||||
for i in 0 ..< (n - 1) {
|
||||
rem[i] = (ln[i] >> s) | ln[i + 1] << (bitWidth - s)
|
||||
}
|
||||
rem[n - 1] = ln[n - 1] >> s
|
||||
|
||||
if rem[n - 1] > UInt(Int.max) {
|
||||
rem.append(0)
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: ")
|
||||
BigUInt._dropExcessWords(words: &rem)
|
||||
|
||||
return (BigUInt(_uncheckedWords: quot), BigUInt(_uncheckedWords: rem))
|
||||
}
|
||||
|
||||
private static func _zeroExtend(lhsWords: inout Words, rhsWords: inout Words) {
|
||||
if lhsWords.count > rhsWords.count {
|
||||
for _ in 0 ..< (lhsWords.count - rhsWords.count) {
|
||||
rhsWords.append(0)
|
||||
}
|
||||
} else if rhsWords.count > lhsWords.count {
|
||||
for _ in 0 ..< (rhsWords.count - lhsWords.count) {
|
||||
lhsWords.append(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _dropExcessWords(words: inout Words) {
|
||||
while words.count > 1, words[words.endIndex - 1] == 0 {
|
||||
if words[words.endIndex - 2] <= Int.max {
|
||||
words.removeLast()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
while words.count > 1, words[words.endIndex - 1] == UInt.max {
|
||||
if words[words.endIndex - 2] > Int.max {
|
||||
words.removeLast()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#[[
|
||||
This source file is part of the Swift Numerics open source project
|
||||
|
||||
Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
add_library(BigIntModule
|
||||
BigInt.swift)
|
||||
set_target_properties(BigIntModule PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
|
||||
_install_target(BigIntModule)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_NUMERICS_EXPORTS BigIntModule)
|
||||
@@ -0,0 +1,3 @@
|
||||
# Arbitrary-precision integers
|
||||
|
||||
This module provides a `BigInt` type.
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019-2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -14,7 +14,7 @@ import RealModule
|
||||
extension Complex: AdditiveArithmetic {
|
||||
/// The additive identity, with real and imaginary parts both zero.
|
||||
///
|
||||
/// See also: ``one``, ``i``, ``infinity``
|
||||
/// See also: `one`, `i`, `infinity`
|
||||
@_transparent
|
||||
public static var zero: Complex {
|
||||
Complex(0, 0)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019-2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -13,8 +13,6 @@ import RealModule
|
||||
|
||||
extension Complex: AlgebraicField {
|
||||
/// The multiplicative identity `1 + 0i`.
|
||||
///
|
||||
/// See also: ``zero``, ``i``, ``infinity``
|
||||
@_transparent
|
||||
public static var one: Complex {
|
||||
Complex(1, 0)
|
||||
@@ -29,93 +27,52 @@ extension Complex: AlgebraicField {
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func /=(z: inout Complex, w: Complex) {
|
||||
z = z / w
|
||||
public static func /(z: Complex, w: Complex) -> Complex {
|
||||
// Try the naive expression z/w = z*conj(w) / |w|^2; if we can compute
|
||||
// this without over/underflow, everything is fine and the result is
|
||||
// correct. If not, we have to rescale and do the computation carefully.
|
||||
let lenSq = w.lengthSquared
|
||||
guard lenSq.isNormal else { return rescaledDivide(z, w) }
|
||||
return z * (w.conjugate.divided(by: lenSq))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func /(z: Complex, w: Complex) -> Complex {
|
||||
// Try the naive expression z/w = z * (conj(w) / |w|^2); if we can
|
||||
// compute this without over/underflow, everything is fine and the
|
||||
// result is correct. If not, we have to rescale and do the
|
||||
// computation carefully (see below).
|
||||
let lenSq = w.lengthSquared
|
||||
guard lenSq.isNormal else { return rescaledDivide(z, w) }
|
||||
return z * w.conjugate.divided(by: lenSq)
|
||||
public static func /=(z: inout Complex, w: Complex) {
|
||||
z = z / w
|
||||
}
|
||||
|
||||
@usableFromInline @_alwaysEmitIntoClient @inline(never)
|
||||
internal static func rescaledDivide(_ z: Complex, _ w: Complex) -> Complex {
|
||||
if w.isZero { return .infinity }
|
||||
if !w.isFinite { return .zero }
|
||||
// Scaling algorithm adapted from Doug Priest's "Efficient Scaling for
|
||||
// Complex Division":
|
||||
if w.magnitude < .leastNormalMagnitude {
|
||||
// A difference from Priest's algorithm is that he didn't have to worry
|
||||
// about types like Float16, where the significand width is comparable
|
||||
// to the exponent range, such that |leastNormalMagnitude|^(-¾) isn't
|
||||
// representable (e.g. for Float16 it would want to be 2¹⁸, but the
|
||||
// largest allowed exponent is 15). Note that it's critical to use zʹ/wʹ
|
||||
// after rescaling to avoid this, rather than falling through into the
|
||||
// normal rescaling, because otherwise we might end up back in the
|
||||
// situation where |w| ~ 1.
|
||||
let s = 1/(RealType(RealType.radix) * .leastNormalMagnitude)
|
||||
let wʹ = w.multiplied(by: s)
|
||||
let zʹ = z.multiplied(by: s)
|
||||
return zʹ / wʹ
|
||||
if z.isZero || !w.isFinite { return .zero }
|
||||
// TODO: detect when RealType is Float and just promote to Double, then
|
||||
// use the naive algorithm.
|
||||
let zScale = z.magnitude
|
||||
let wScale = w.magnitude
|
||||
let zNorm = z.divided(by: zScale)
|
||||
let wNorm = w.divided(by: wScale)
|
||||
let r = (zNorm * wNorm.conjugate).divided(by: wNorm.lengthSquared)
|
||||
// At this point, the result is (r * zScale)/wScale computed without
|
||||
// undue overflow or underflow. We know that r is close to unity, so
|
||||
// the question is simply what order in which to do this computation
|
||||
// to avoid spurious overflow or underflow. There are three options
|
||||
// to choose from:
|
||||
//
|
||||
// - r * (zScale / wScale)
|
||||
// - (r * zScale) / wScale
|
||||
// - (r / wScale) * zScale
|
||||
//
|
||||
// The simplest case is when zScale / wScale is normal:
|
||||
if (zScale / wScale).isNormal {
|
||||
return r.multiplied(by: zScale / wScale)
|
||||
}
|
||||
// Having handled that case, we proceed pretty similarly to Priest:
|
||||
//
|
||||
// 1. Choose real scale s ~ |w|^(-¾), an exact power of the radix.
|
||||
// 2. wʹ ← sw
|
||||
// 3. zʹ ← sz
|
||||
// 4. return zʹ * (wʹ.conjugate / wʹ.lengthSquared) (i.e. zʹ/wʹ).
|
||||
//
|
||||
// Why is this safe and accurate? First, observe that wʹ and zʹ are both
|
||||
// computed exactly because:
|
||||
//
|
||||
// - s is an exact power of radix.
|
||||
// - wʹ ~ |w|^(¼), and hence cannot overflow or underflow.
|
||||
// - zʹ might overflow or underflow, but only if the final result also
|
||||
// overflows or underflows. (This is more subtle than I make it
|
||||
// sound. In particular, most of the fast ways one might try to
|
||||
// compute s give rise to a situation where when |w| is close to
|
||||
// one, multiplication by s is a dilation even though the actual
|
||||
// division is a contraction or vice-versa, and thus intermediate
|
||||
// computations might incorrectly overflow or underflow. Priest
|
||||
// had to take some care to avoid this situation, but we do not,
|
||||
// because we have already ruled out |w| ~ 1 before we call this
|
||||
// function.)
|
||||
//
|
||||
// Next observe that |wʹ.lengthSquared| ~ |w|^(½), so again this cannot
|
||||
// overflow or underflow, and neither can (wʹ.conjugate/wʹ.lengthSquared),
|
||||
// which has magnitude like |w|^(-¼).
|
||||
//
|
||||
// Note that because the scale factor is always a power of the radix,
|
||||
// the rescaling does not affect rounding, and so this algorithm is scale-
|
||||
// invariant compared to the mainline `/` implementation, up to the
|
||||
// underflow boundary.
|
||||
//
|
||||
// Note that our final assembly of the result is different from Priest;
|
||||
// he applies s to w twice, instead of once to w and once to z, and
|
||||
// does the product as (zw̅ʺ)*(1/|wʹ|²), while we do zʹ(w̅ʹ/|wʹ|²). We
|
||||
// prefer our version for three reasons:
|
||||
//
|
||||
// 1. it extracts a little more ILP
|
||||
// 2. it makes it so that we get exactly the same roundings on the
|
||||
// rescaled divide path as on the fast path, so that z/w = tz/tw
|
||||
// when tz and tw are computed exactly.
|
||||
// 3. it unlocks a future optimization where we hoist s and
|
||||
// (w̅ʹ/|wʹ|²) and make divisions all fast-path without perturbing
|
||||
// rounding.
|
||||
let s = RealType(
|
||||
sign: .plus,
|
||||
exponent: -3*w.magnitude.exponent/4,
|
||||
significand: 1
|
||||
)
|
||||
let wʹ = w.multiplied(by: s)
|
||||
let zʹ = z.multiplied(by: s)
|
||||
return zʹ * wʹ.conjugate.divided(by: wʹ.lengthSquared)
|
||||
// Otherwise, we need to compute either rNorm * zScale or rNorm / wScale
|
||||
// first. Choose the first if the first scaling behaves well, otherwise
|
||||
// choose the other one.
|
||||
if (r.magnitude * zScale).isNormal {
|
||||
return r.multiplied(by: zScale).divided(by: wScale)
|
||||
}
|
||||
return r.divided(by: wScale).multiplied(by: zScale)
|
||||
}
|
||||
|
||||
/// A normalized complex number with the same phase as this value.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//===--- Complex+ElementaryFunctions.swift --------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -32,12 +32,6 @@
|
||||
// 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
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -37,20 +37,17 @@ extension Complex: Numeric {
|
||||
self.init(real, 0)
|
||||
}
|
||||
|
||||
/// The infinity-norm of the value (a.k.a. "maximum norm" or "Чебышёв
|
||||
/// [Chebyshev] norm").
|
||||
/// The ∞-norm of the value (`max(abs(real), abs(imaginary))`).
|
||||
///
|
||||
/// Equal to `max(abs(real), abs(imaginary))`.
|
||||
/// If you need the Euclidean norm (a.k.a. 2-norm) use the `length` or
|
||||
/// `lengthSquared` properties instead.
|
||||
///
|
||||
/// If you need to work with the Euclidean norm (a.k.a. 2-norm) instead,
|
||||
/// use the ``length`` or ``lengthSquared`` properties. If you just need
|
||||
/// to know "how big" a number is, use this property.
|
||||
///
|
||||
/// **Edge cases:**
|
||||
///
|
||||
/// - If `z` is not finite, `z.magnitude` is infinity.
|
||||
/// - If `z` is zero, `z.magnitude` is zero.
|
||||
/// Edge cases:
|
||||
/// - If `z` is not finite, `z.magnitude` is `.infinity`.
|
||||
/// - If `z` is zero, `z.magnitude` is `0`.
|
||||
/// - Otherwise, `z.magnitude` is finite and non-zero.
|
||||
///
|
||||
/// See also `.length` and `.lengthSquared`.
|
||||
@_transparent
|
||||
public var magnitude: RealType {
|
||||
guard isFinite else { return .infinity }
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -11,8 +11,39 @@
|
||||
|
||||
import RealModule
|
||||
|
||||
// A [complex number](https://en.wikipedia.org/wiki/Complex_number).
|
||||
// See Documentation.docc/Complex.md for more details.
|
||||
/// A complex number represented by real and imaginary parts.
|
||||
///
|
||||
/// TODO: introductory text on complex numbers
|
||||
///
|
||||
/// Implementation notes:
|
||||
///
|
||||
/// This type does not provide heterogeneous real/complex arithmetic,
|
||||
/// not even the natural vector-space operations like real * complex.
|
||||
/// There are two reasons for this choice: first, Swift broadly avoids
|
||||
/// mixed-type arithmetic when the operation can be adequately expressed
|
||||
/// by a conversion and homogeneous arithmetic. Second, with the current
|
||||
/// typechecker rules, it would lead to undesirable ambiguity in common
|
||||
/// expressions (see README.md for more details).
|
||||
///
|
||||
/// Unlike C's `_Complex` and C++'s `std::complex<>` types, we do not
|
||||
/// attempt to make meaningful semantic distinctions between different
|
||||
/// representations of infinity or NaN. Any Complex value with at least
|
||||
/// one non-finite component is simply "non-finite". In as much as
|
||||
/// possible, we use the semantics of the point at infinity on the
|
||||
/// Riemann sphere for such values. This approach simplifies the number of
|
||||
/// edge cases that need to be considered for multiplication, division, and
|
||||
/// the elementary functions considerably.
|
||||
///
|
||||
/// `.magnitude` does not return the Euclidean norm; it uses the "infinity
|
||||
/// norm" (`max(|real|,|imaginary|)`) instead. There are two reasons for this
|
||||
/// choice: first, it's simply faster to compute on most hardware. Second,
|
||||
/// there exist values for which the Euclidean norm cannot be represented
|
||||
/// (consider a number with `.real` and `.imaginary` both equal to
|
||||
/// `RealType.greatestFiniteMagnitude`; the Euclidean norm would be
|
||||
/// `.sqrt(2) * .greatestFiniteMagnitude`, which overflows). Using
|
||||
/// the infinity norm avoids this problem entirely without significant
|
||||
/// downsides. You can access the Euclidean norm using the `length`
|
||||
/// property.
|
||||
@frozen
|
||||
public struct Complex<RealType> where RealType: Real {
|
||||
// A note on the `x` and `y` properties
|
||||
@@ -22,11 +53,11 @@ public struct Complex<RealType> where RealType: Real {
|
||||
// `.real` and `.imaginary` properties, which wrap this storage and
|
||||
// fixup the semantics for non-finite values.
|
||||
|
||||
/// The storage for the real component of the value.
|
||||
/// The real component of the value.
|
||||
@usableFromInline @inline(__always)
|
||||
internal var x: RealType
|
||||
|
||||
/// The storage for the imaginary part of the value.
|
||||
/// The imaginary part of the value.
|
||||
@usableFromInline @inline(__always)
|
||||
internal var y: RealType
|
||||
|
||||
@@ -64,24 +95,11 @@ extension Complex {
|
||||
set { y = newValue }
|
||||
}
|
||||
|
||||
/// The raw representation of the value.
|
||||
///
|
||||
/// Use this when you need the underlying RealType values,
|
||||
/// without fixup for NaN or infinity.
|
||||
public var rawStorage: (x: RealType, y: RealType) {
|
||||
@_transparent
|
||||
get { (x, y) }
|
||||
@_transparent
|
||||
set { (x, y) = newValue }
|
||||
}
|
||||
|
||||
/// The raw representation of the real part of this value.
|
||||
@available(*, deprecated, message: "Use rawStorage")
|
||||
@_transparent
|
||||
public var _rawX: RealType { x }
|
||||
|
||||
/// The raw representation of the imaginary part of this value.
|
||||
@available(*, deprecated, message: "Use rawStorage")
|
||||
@_transparent
|
||||
public var _rawY: RealType { y }
|
||||
}
|
||||
@@ -89,7 +107,7 @@ extension Complex {
|
||||
extension Complex {
|
||||
/// The imaginary unit.
|
||||
///
|
||||
/// See also ``zero``, ``one`` and ``infinity``.
|
||||
/// See also `.zero`, `.one` and `.infinity`.
|
||||
@_transparent
|
||||
public static var i: Complex {
|
||||
Complex(0, 1)
|
||||
@@ -97,7 +115,7 @@ extension Complex {
|
||||
|
||||
/// The point at infinity.
|
||||
///
|
||||
/// See also ``zero``, ``one`` and ``i``.
|
||||
/// See also `.zero`, `.one` and `.i`.
|
||||
@_transparent
|
||||
public static var infinity: Complex {
|
||||
Complex(.infinity, 0)
|
||||
@@ -107,7 +125,7 @@ extension Complex {
|
||||
///
|
||||
/// A complex value is finite if neither component is an infinity or nan.
|
||||
///
|
||||
/// See also ``isNormal``, ``isSubnormal`` and ``isZero``.
|
||||
/// See also `.isNormal`, `.isSubnormal` and `.isZero`.
|
||||
@_transparent
|
||||
public var isFinite: Bool {
|
||||
x.isFinite && y.isFinite
|
||||
@@ -120,7 +138,7 @@ extension Complex {
|
||||
/// one of the components is normal if its exponent allows a full-precision
|
||||
/// representation.
|
||||
///
|
||||
/// See also ``isFinite``, ``isSubnormal`` and ``isZero``.
|
||||
/// See also `.isFinite`, `.isSubnormal` and `.isZero`.
|
||||
@_transparent
|
||||
public var isNormal: Bool {
|
||||
isFinite && (x.isNormal || y.isNormal)
|
||||
@@ -132,7 +150,7 @@ extension Complex {
|
||||
/// When the result of a computation is subnormal, underflow has occurred and
|
||||
/// the result generally does not have full precision.
|
||||
///
|
||||
/// See also ``isFinite``, ``isNormal`` and ``isZero``.
|
||||
/// See also `.isFinite`, `.isNormal` and `.isZero`.
|
||||
@_transparent
|
||||
public var isSubnormal: Bool {
|
||||
isFinite && !isNormal && !isZero
|
||||
@@ -143,7 +161,7 @@ extension Complex {
|
||||
/// A complex number is zero if *both* the real and imaginary components
|
||||
/// are zero.
|
||||
///
|
||||
/// See also ``isFinite``, ``isNormal`` and ``isSubnormal``.
|
||||
/// See also `.isFinite`, `.isNormal` and `isSubnormal`.
|
||||
@_transparent
|
||||
public var isZero: Bool {
|
||||
x == 0 && y == 0
|
||||
@@ -182,7 +200,7 @@ extension Complex {
|
||||
self.init(real, 0)
|
||||
}
|
||||
|
||||
/// The complex number with zero real part and specified imaginary part.
|
||||
/// The complex number with specified imaginary part and zero real part.
|
||||
///
|
||||
/// Equivalent to `Complex(0, imaginary)`.
|
||||
@inlinable
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
# ``Complex``
|
||||
|
||||
A complex number type represented by its real and imaginary parts, and equipped
|
||||
with the usual arithmetic operators and math functions.
|
||||
|
||||
## Overview
|
||||
|
||||
You can access these Cartesian components using the real and imaginary
|
||||
properties.
|
||||
|
||||
```swift
|
||||
let z = Complex(1,-1) // 1 - i
|
||||
let re = z.real // 1
|
||||
let im = z.imaginary // -1
|
||||
```
|
||||
|
||||
All `Complex` numbers with a non-finite component are treated as a single
|
||||
"point at infinity," with infinite magnitude and indeterminant phase. Thus,
|
||||
the real and imaginary parts of an infinity are nan.
|
||||
|
||||
```swift
|
||||
let w = Complex<Double>.infinity
|
||||
w == -w // true
|
||||
let re = w.real // .nan
|
||||
let im = w.imag // .nan
|
||||
```
|
||||
|
||||
See <doc:Infinity> for more details.
|
||||
|
||||
The ``magnitude`` property of a complex number is the infinity norm of the
|
||||
value (a.k.a. “maximum norm” or “Чебышёв [Chebyshev] norm”). To get the two
|
||||
norm (a.k.a. "Euclidean norm"), use the ``length`` property. See
|
||||
<doc:Magnitude> for more details.
|
||||
|
||||
## Topics
|
||||
|
||||
### Real and imaginary parts
|
||||
|
||||
- ``real``
|
||||
- ``imaginary``
|
||||
- ``rawStorage``
|
||||
- ``init(_:_:)``
|
||||
- ``init(_:)-5aesj``
|
||||
- ``init(imaginary:)``
|
||||
|
||||
### Phase, length and magnitude
|
||||
|
||||
- ``magnitude``
|
||||
- ``length``
|
||||
- ``lengthSquared``
|
||||
- ``normalized``
|
||||
- ``phase``
|
||||
- ``polar``
|
||||
- ``init(length:phase:)``
|
||||
|
||||
### Scaling by real numbers
|
||||
- ``multiplied(by:)``
|
||||
- ``divided(by:)``
|
||||
|
||||
### Complex-specific operations
|
||||
- ``conjugate``
|
||||
|
||||
### Classification
|
||||
- ``isZero``
|
||||
- ``isSubnormal``
|
||||
- ``isNormal``
|
||||
- ``isFinite``
|
||||
@@ -1,88 +0,0 @@
|
||||
# ``ComplexModule``
|
||||
|
||||
Types and operations for working with complex numbers.
|
||||
|
||||
## Overview
|
||||
|
||||
### Representation
|
||||
|
||||
The `Complex` type is generic over an associated `RealType`; complex numbers
|
||||
are represented as two `RealType` values, the real and imaginary parts of the
|
||||
number.
|
||||
|
||||
```
|
||||
let z = Complex<Double>(1, 2)
|
||||
let re = z.real
|
||||
let im = z.imaginary
|
||||
```
|
||||
|
||||
### Memory layout
|
||||
|
||||
A `Complex` value is stored as two `RealType` values arranged consecutively
|
||||
in memory. Thus it has the same memory layout as:
|
||||
- A Fortran complex value built on the corresponding real type (as used
|
||||
by BLAS and LAPACK).
|
||||
- A C struct with real and imaginary parts and nothing else (as used by
|
||||
computational libraries predating C99).
|
||||
- A C99 `_Complex` value built on the corresponding real type.
|
||||
- A C++ `std::complex` value built on the corresponding real type.
|
||||
Functions taking complex arguments in these other languages are not
|
||||
automatically converted on import, but you can safely write shims that
|
||||
map them into Swift types by converting pointers.
|
||||
|
||||
### Real-Complex arithmetic
|
||||
|
||||
Because the real numbers are a subset of the complex numbers, many
|
||||
languages support arithmetic with mixed real and complex operands.
|
||||
For example, C allows the following:
|
||||
|
||||
```c
|
||||
#include <complex.h>
|
||||
double r = 1;
|
||||
double complex z = CMPLX(0, 2); // 2i
|
||||
double complex w = r + z; // 1 + 2i
|
||||
```
|
||||
|
||||
The `Complex` type does not provide such mixed operators:
|
||||
|
||||
```swift
|
||||
let r = 1.0
|
||||
let z = Complex(imaginary: 2.0)
|
||||
let w = r + z // error: binary operator '+' cannot be applied to operands of type 'Double' and 'Complex<Double>'
|
||||
```
|
||||
|
||||
In order to write the example from C above in Swift, you have to perform an
|
||||
explicit conversion:
|
||||
|
||||
```swift
|
||||
let r = 1.0
|
||||
let z = Complex(imaginary: 2.0)
|
||||
let w = Complex(r) + z // OK
|
||||
```
|
||||
|
||||
There are two reasons for this choice. Most importantly, Swift generally avoids
|
||||
mixed-type arithmetic. Second, if we _did_ provide such heterogeneous operators,
|
||||
it would lead to undesirable behavior in common expressions when combined with
|
||||
literal type inference. Consider the following example:
|
||||
|
||||
```swift
|
||||
let a: Double = 1
|
||||
let b = 2*a
|
||||
```
|
||||
|
||||
`b` ought to have type `Double`, but if we did have a Complex-by-Real `*`
|
||||
operation, `2*a` would either be ambiguous (if there were no type context),
|
||||
or be inferred to have type `Complex<Double>` (if the expression appeared
|
||||
in the context of an extension defined on `Complex`).
|
||||
|
||||
Note that we _do_ provide heterogeneous multiplication and division by a real
|
||||
value, spelled as ``Complex/divided(by:)`` and ``Complex/multiplied(by:)``
|
||||
to avoid ambiguity.
|
||||
|
||||
```swift
|
||||
let z = Complex<Double>(1,3)
|
||||
let w = z.multiplied(by: 2)
|
||||
```
|
||||
|
||||
These operations are generally more efficient than converting the scale to
|
||||
a complex number and then using `*` or `/`.
|
||||
@@ -1,55 +0,0 @@
|
||||
# Zero and infinity
|
||||
|
||||
Semantics of `Complex` zero and infinity values, and important considerations
|
||||
when porting code from other languages.
|
||||
|
||||
## Overview
|
||||
|
||||
Unlike C and C++'s complex types, `Complex` does not attempt to make a
|
||||
semantic distinction between different infinity and NaN values. Any `Complex`
|
||||
datum with a non-finite component is treated as the "point at infinity" on
|
||||
the Riemann sphere--a value with infinite magnitude and unspecified phase.
|
||||
|
||||
As a consequence, all values with either component infinite or NaN compare
|
||||
equal, and hash the same. Similarly, all zero values compare equal and hash
|
||||
the same.
|
||||
|
||||
### Rationale
|
||||
|
||||
This choice has some drawbacks,¹ but also some significant advantages.
|
||||
In particular, complex multiplication is the most common operation performed
|
||||
with a complex type, and one would like to be able to use the usual naive
|
||||
arithmetic implementation, consisting of four real multiplications and two
|
||||
real additions:
|
||||
|
||||
```
|
||||
(a + bi) * (c + di) = (ac - bd) + (ad + bc)i
|
||||
```
|
||||
|
||||
`Complex` can use this implementation, because we do not differentiate between
|
||||
infinities and NaN values. C and C++, by contrast, cannot use this
|
||||
implementation by default, because, for example:
|
||||
|
||||
```
|
||||
(1 + ∞i) * (0 - 2i) = (1*0 - ∞*(-2)) + (1*(-2) + ∞*0)i
|
||||
= (0 - ∞) + (-2 + nan)i
|
||||
= -∞ + nan i
|
||||
```
|
||||
|
||||
`Complex` treats this as "infinity", which is the correct result. C and C++
|
||||
treat it as a nan value, however, which is incorrect; infinity multiplied
|
||||
by a non-zero number should be infinity. Thus, C and C++ (by default) must
|
||||
detect these special cases and fix them up, which makes multiplication a
|
||||
more computationally expensive operation.²
|
||||
|
||||
### Footnotes:
|
||||
¹ W. Kahan, Branch Cuts for Complex Elementary Functions, or Much Ado
|
||||
About Nothing's Sign Bit. In A. Iserles and M.J.D. Powell, editors,
|
||||
_Proceedings The State of Art in Numerical Analysis_, pages 165–211, 1987.
|
||||
|
||||
² This can be addressed in C programs by use of the `STDC CX_LIMITED_RANGE`
|
||||
pragma, which instructs the compiler to simply not care about these cases.
|
||||
Unfortunately, this pragma is not often used in real C or C++ programs
|
||||
(though it does see some use in _libraries_). Programmers tend to specify
|
||||
`-ffast-math` or maybe `-ffinite-math-only` instead, which has other
|
||||
undesirable consequences.
|
||||
@@ -1,144 +0,0 @@
|
||||
# Magnitude and norms
|
||||
|
||||
Introduction to the concept of norm and discussion of the `Complex` type's
|
||||
`.magnitude` property.
|
||||
|
||||
## Overview
|
||||
|
||||
In mathematics, a *norm* is a function that gives each element of a vector
|
||||
space a non-negative length.¹
|
||||
|
||||
Many different norms can be defined on the complex numbers, viewed as a
|
||||
vector space over the reals. All of these norms have some basic
|
||||
properties. If we use *‖z‖* to represent any norm of *z*, it must:
|
||||
- be *subadditive* (a.k.a. satisfy the triangle inequalty):
|
||||
‖z + w‖ ≤ ‖z‖ + ‖w‖ for any two complex numbers z and w.
|
||||
- be *homogeneous*
|
||||
‖az‖ = |a|‖z‖ for any real number a and complex number z.
|
||||
- and be *positive definite*
|
||||
‖z‖ is zero if and only if z is zero.
|
||||
|
||||
The three most commonly-used norms are:
|
||||
- 1-norm ("taxicab norm"):
|
||||
‖x + iy‖₁ = |x| + |y|
|
||||
- 2-norm ("Euclidean norm"):
|
||||
‖x + iy‖₂ = √(x² + y²)
|
||||
- ∞-norm ("maximum norm" or "Чебышёв [Chebyshev] norm")²:
|
||||
‖x + iy‖ = max(|x|,|y|)
|
||||
|
||||
> Exercise:
|
||||
> 1. Check that these properties hold for one of the three norms
|
||||
that we just defined. (Hint: write z = a+bi and w = c+di,
|
||||
and use the fact that the absolute value is a norm on the
|
||||
real numbers, and therefore has the same property).
|
||||
|
||||
The `Complex` type gives special names to two of these norms; `length`
|
||||
for the 2-norm, and `magnitude` for the ∞-norm.
|
||||
|
||||
### Magnitude:
|
||||
|
||||
The `Numeric` protocol requires us to choose a norm to call `magnitude`,
|
||||
but does not give guidance as to which one we should pick. The easiest choice
|
||||
might have been the Euclidean norm; it's the one with which people are most
|
||||
likely to be familiar.
|
||||
|
||||
However, there are good reasons to make a different choice:
|
||||
- Computing the Euclidean norm requires special care to avoid spurious
|
||||
overflow/underflow (see implementation notes for `length` below). The
|
||||
naive expressions for the taxicab and maximum norm always give the best
|
||||
answer possible.
|
||||
- Even when special care is used, the Euclidean and taxicab norms are
|
||||
not necessarily representable. Both can be infinite even for finite
|
||||
numbers.
|
||||
|
||||
```swift
|
||||
let big = Double.greatestFiniteMagnitude
|
||||
let z = Complex(big, big)
|
||||
```
|
||||
|
||||
The taxicab norm of `z` would be `big + big`, which overflows; the
|
||||
Euclidean norm would be `sqrt(2) * big`, which also overflows.
|
||||
But the maximum norm is always equal to the magnitude of either `real`
|
||||
or `imaginary`, so it is necessarily representable.
|
||||
- The ∞-norm is the choice of established computational libraries, like
|
||||
BLAS and LAPACK.
|
||||
|
||||
For these reasons, the `magnitude` property of `Complex` binds the
|
||||
maximum norm:
|
||||
|
||||
```swift
|
||||
Complex(2, 3).magnitude // 3
|
||||
Complex(-1, 0.5).magnitude // 1
|
||||
```
|
||||
|
||||
### Length:
|
||||
|
||||
The `length` property of a `Complex` value is its Euclidean norm.
|
||||
|
||||
```swift
|
||||
Complex(2, 3).length // 3.605551275463989
|
||||
Complex(-1, 0.5).length // 1.118033988749895
|
||||
```
|
||||
|
||||
Aside from familiarity, the Euclidean norm has one important property
|
||||
that the maximum norm lacks:
|
||||
- it is *multiplicative*:
|
||||
‖zw‖₂ = ‖z‖₂‖w‖₂ for any two complex numbers z and w.
|
||||
|
||||
> Exercises:
|
||||
> 1. Find z and w that show that the maximum norm is not multiplicative.
|
||||
(i.e. exhibit z and w such that ‖zw‖ ≠ ‖z‖‖w‖.)
|
||||
> 2. Is the 1-norm multiplicative?
|
||||
|
||||
### Implementation notes:
|
||||
|
||||
The `length` property takes special care to produce an accurate answer,
|
||||
even when the value is poorly-scaled. The naive expression for `length`
|
||||
would be `sqrt(x*x + y*y)`, but this can overflow or underflow even when
|
||||
the final result should be a finite number.
|
||||
|
||||
```swift
|
||||
// Suppose that length were implemented like this:
|
||||
extension Complex {
|
||||
var naiveLength: RealType {
|
||||
.sqrt(real*real + imaginary*imaginary)
|
||||
}
|
||||
}
|
||||
|
||||
// Then taking the length of even a modestly large number:
|
||||
let z = Complex<Float>(1e20, 1e20)
|
||||
// or small number:
|
||||
let w = Complex<Float>(1e-24, 1e-24)
|
||||
// would overflow:
|
||||
z.naiveLength // Inf
|
||||
// or underflow:
|
||||
w.naiveLength // 0
|
||||
```
|
||||
|
||||
Instead, `length` is implemented using a two-step algorithm. First we
|
||||
compute `lengthSquared`, which is `x*x + y*y`. If this is a normal
|
||||
number (meaning that no overflow or underflow has occured), we can safely
|
||||
return its square root. Otherwise, we redo the computation with a more
|
||||
careful computation, which avoids spurious under- or overflow:
|
||||
|
||||
```swift
|
||||
let z = Complex<Float>(1e20, 1e20)
|
||||
let w = Complex<Float>(1e-24, 1e-24)
|
||||
z.length // 1.41421358E+20
|
||||
w.length // 1.41421362E-24
|
||||
```
|
||||
|
||||
### Footnotes:
|
||||
|
||||
¹ Throughout this documentation, "norm" refers to a
|
||||
[vector norm](https://en.wikipedia.org/wiki/Norm_(mathematics)).
|
||||
To confuse the matter, there are several similar things also called
|
||||
"norm" in mathematics. The other one you are most likely to run into
|
||||
is the [field norm](https://en.wikipedia.org/wiki/Field_norm).
|
||||
|
||||
Field norms are much less common than vector norms, but the C++
|
||||
`std::norm` operation implements a field norm. To get the (Euclidean)
|
||||
vector norm in C++, use `std::abs`.
|
||||
|
||||
² There's no subscript-∞ in unicode, so I write the infinity norm
|
||||
without the usual subscript.
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -12,7 +12,7 @@
|
||||
import RealModule
|
||||
|
||||
extension Complex {
|
||||
/// The Euclidean norm (a.k.a. 2-norm).
|
||||
/// The Euclidean norm (a.k.a. 2-norm, `sqrt(real*real + imaginary*imaginary)`).
|
||||
///
|
||||
/// This property takes care to avoid spurious over- or underflow in
|
||||
/// this computation. For example:
|
||||
@@ -26,15 +26,15 @@ extension Complex {
|
||||
/// because the length can be as much as sqrt(2) times larger than
|
||||
/// either component, and thus may not be representable in the real type.
|
||||
///
|
||||
/// For most use cases, you can use the cheaper ``magnitude``
|
||||
/// For most use cases, you can use the cheaper `.magnitude`
|
||||
/// property (which computes the ∞-norm) instead, which always produces
|
||||
/// a representable result. See <doc:Magnitude> for more details.
|
||||
/// a representable result.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// - If a complex value is not finite, its `length` is `infinity`.
|
||||
/// - If a complex value is not finite, its `.length` is `infinity`.
|
||||
///
|
||||
/// See also ``lengthSquared``, ``phase``, ``polar``
|
||||
/// and ``init(length:phase:)``.
|
||||
/// See also `.magnitude`, `.lengthSquared`, `.phase`, `.polar`
|
||||
/// and `init(r:θ:)`.
|
||||
@_transparent
|
||||
public var length: RealType {
|
||||
let naive = lengthSquared
|
||||
@@ -42,7 +42,7 @@ extension Complex {
|
||||
return .sqrt(naive)
|
||||
}
|
||||
|
||||
// Internal implementation detail of ``length``, moving slow path off
|
||||
// Internal implementation detail of `length`, moving slow path off
|
||||
// of the inline function. Note that even `carefulLength` can overflow
|
||||
// for finite inputs, but only when the result is outside the range
|
||||
// of representable values.
|
||||
@@ -54,31 +54,34 @@ extension Complex {
|
||||
|
||||
/// The squared length `(real*real + imaginary*imaginary)`.
|
||||
///
|
||||
/// This property is more efficient to compute than ``length``, but is
|
||||
/// This property is more efficient to compute than `length`, but is
|
||||
/// highly prone to overflow or underflow; for finite values that are
|
||||
/// not well-scaled, `lengthSquared` is often either zero or
|
||||
/// infinity, even when `length` is a finite number. Use this property
|
||||
/// only when you are certain that this value is well-scaled.
|
||||
///
|
||||
/// For many cases, ``magnitude`` can be used instead, which is similarly
|
||||
/// For many cases, `.magnitude` can be used instead, which is similarly
|
||||
/// cheap to compute and always returns a representable value.
|
||||
///
|
||||
/// Note that because of how `lengthSquared` is used, it is a primary
|
||||
/// design goal that it be as fast as possible. Therefore, it does not
|
||||
/// normalize infinities, and may return either `.infinity` or `.nan`
|
||||
/// for non-finite values.
|
||||
/// See also `.length` and `.magnitude`.
|
||||
@_transparent
|
||||
public var lengthSquared: RealType {
|
||||
x*x + y*y
|
||||
}
|
||||
|
||||
@available(*, unavailable, renamed: "lengthSquared")
|
||||
public var unsafeLengthSquared: RealType { lengthSquared }
|
||||
|
||||
/// The phase (angle, or "argument").
|
||||
///
|
||||
/// - Returns: The angle (measured above the real axis) in radians. If
|
||||
/// Returns the angle (measured above the real axis) in radians. If
|
||||
/// the complex value is zero or infinity, the phase is not defined,
|
||||
/// and `nan` is returned.
|
||||
///
|
||||
/// See also ``length``, ``polar`` and ``init(length:phase:)``.
|
||||
/// Edge cases:
|
||||
/// - If the complex value is zero or non-finite, phase is `nan`.
|
||||
///
|
||||
/// See also `.length`, `.polar` and `init(r:θ:)`.
|
||||
@inlinable
|
||||
public var phase: RealType {
|
||||
guard isFinite && !isZero else { return .nan }
|
||||
@@ -91,7 +94,7 @@ extension Complex {
|
||||
/// - If the complex value is zero or non-finite, phase is `.nan`.
|
||||
/// - If the complex value is non-finite, length is `.infinity`.
|
||||
///
|
||||
/// See also: ``length``, ``phase`` and ``init(length:phase:)``.
|
||||
/// See also: `.length`, `.phase` and `init(r:θ:)`.
|
||||
public var polar: (length: RealType, phase: RealType) {
|
||||
(length, phase)
|
||||
}
|
||||
@@ -114,7 +117,7 @@ extension Complex {
|
||||
/// ```
|
||||
/// - Otherwise, `θ` must be finite, or a precondition failure occurs.
|
||||
///
|
||||
/// See also ``length``, ``phase`` and ``polar``.
|
||||
/// See also `.length`, `.phase` and `.polar`.
|
||||
@inlinable
|
||||
public init(length: RealType, phase: RealType) {
|
||||
if phase.isFinite {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019-2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -20,22 +20,36 @@
|
||||
// what is the type of b? If we don't have a type context, it's ambiguous.
|
||||
// If we have a Complex type context, then b will be inferred to have type
|
||||
// Complex! Obviously, that doesn't help anyone.
|
||||
|
||||
//
|
||||
// TODO: figure out if there's some way to avoid these surprising results
|
||||
// and turn these into operators if/when we have it.
|
||||
// (https://github.com/apple/swift-numerics/issues/12)
|
||||
extension Complex {
|
||||
/// The result of multiplying this value by the real number `a`.
|
||||
///
|
||||
/// Equivalent to `self * Complex(a)`, but may be computed more efficiently.
|
||||
@inlinable @inline(__always)
|
||||
public func multiplied(by a: RealType) -> Complex {
|
||||
/// `self` scaled by `a`.
|
||||
@usableFromInline @_transparent
|
||||
internal func multiplied(by a: RealType) -> Complex {
|
||||
// This can be viewed in two different ways, which are mathematically
|
||||
// equivalent: either we are computing `self * Complex(a)` (i.e.
|
||||
// converting `a` to be a complex value, and then using the complex
|
||||
// multiplication) or we are using the scalar product of the vector
|
||||
// space structure: `Complex(a*real, a*imaginary)`.
|
||||
//
|
||||
// Although these two interpretations are _mathematically_ equivalent,
|
||||
// they will generate different representations of the point at
|
||||
// infinity in general. For example, suppose `self` is represented by
|
||||
// `(infinity, 0)`. Then `self * Complex(1)` would evaluate as
|
||||
// `(1*infinity - 0*0, 0*infinity + 1*0) = (infinity, nan)`, but
|
||||
// the vector space interpretation produces `(infinity, 0)`. This does
|
||||
// not matter much, because these are two representations of the same
|
||||
// semantic value, but note that one requires four multiplies and two
|
||||
// additions, while the one we use requires only two real multiplications.
|
||||
Complex(x*a, y*a)
|
||||
}
|
||||
|
||||
/// The result of dividing this value by the real number `a`.
|
||||
///
|
||||
/// More efficient than `self / Complex(a)`. May not produce exactly the
|
||||
/// same result, but will always be more accurate if they differ.
|
||||
@inlinable @inline(__always)
|
||||
public func divided(by a: RealType) -> Complex {
|
||||
/// `self` unscaled by `a`.
|
||||
@usableFromInline @_transparent
|
||||
internal func divided(by a: RealType) -> Complex {
|
||||
// See implementation notes for `multiplied` above.
|
||||
Complex(x/a, y/a)
|
||||
}
|
||||
}
|
||||
@@ -12,29 +12,26 @@
|
||||
extension BinaryInteger {
|
||||
/// `self` divided by `other`, rounding the result according to `rule`.
|
||||
///
|
||||
/// By default, this function uses ``RoundingRule/down``, which **is not
|
||||
/// the same** as the rounding of the `/` operator from the Swift standard
|
||||
/// library. They agree when the signs of the arguments match, but produce
|
||||
/// different results when the quotient is negative. This behavior is
|
||||
/// chosen because it generally produces a more useful remainder; in
|
||||
/// particular, when the divisor is positive, the remainder is always
|
||||
/// positive. To match the behavior of `/`, use ``RoundingRule/towardZero``.
|
||||
/// The default rounding rule is `.down`, which _is not the same_ as the
|
||||
/// behavior of the `/` operator from the Swift standard library, but is
|
||||
/// chosen because it generally produces a more useful remainder. In
|
||||
/// particular, when `b` is positive, the remainder is always positive.
|
||||
/// To match the behavior of `/`, use the `.towardZero` rounding mode.
|
||||
///
|
||||
/// Note that the remainder of division is not always representable in an
|
||||
/// unsigned type if a rounding rule other than ``RoundingRule/down``,
|
||||
/// ``RoundingRule/towardZero``, or ``RoundingRule/requireExact`` is
|
||||
/// used. For example:
|
||||
/// ```swift
|
||||
/// let a: UInt = 5
|
||||
/// let b: UInt = 3
|
||||
/// let q = a.divided(by: b, rounding: .up) // 2
|
||||
/// let r = a - b*q // 5 - 3*2 overflows UInt.
|
||||
/// ```
|
||||
/// unsigned type if a rounding rule other than `.down`, `.towardZero`, or
|
||||
/// `.requireExact` is used. For example:
|
||||
///
|
||||
/// let a: UInt = 5
|
||||
/// let b: UInt = 3
|
||||
/// let q = a.divided(by: b, rounding: .up) // 2
|
||||
/// let r = a - b*q // 5 - 3*2 overflows UInt.
|
||||
///
|
||||
/// For this reason, there is no `remainder(dividingBy:rounding:)`
|
||||
/// operation defined on `BinaryInteger`. Signed integers do not have
|
||||
/// this problem, so the `SignedInteger` protocol is extended with
|
||||
/// ``SignedInteger/divided(by:rounding:)`` returning both quotient
|
||||
/// and remainder.
|
||||
/// this problem, so it is defined on the `SignedInteger` protocol
|
||||
/// instead, as is an overload of `divided(by:rounding:)` that returns
|
||||
/// both quotient and remainder.
|
||||
@inlinable
|
||||
public func divided(
|
||||
by other: Self,
|
||||
@@ -55,7 +52,7 @@ extension BinaryInteger {
|
||||
// rounded toward zero.
|
||||
//
|
||||
// If we subtract 1 from q, we add other to r to compensate, because:
|
||||
//
|
||||
//
|
||||
// self = q*other + r
|
||||
// = (q-1)*other + (r+other)
|
||||
//
|
||||
@@ -67,64 +64,66 @@ extension BinaryInteger {
|
||||
// disagree, we have to adjust q downward and r to match.
|
||||
if other.signum() != r.signum() { return q-1 }
|
||||
return q
|
||||
|
||||
case .up:
|
||||
// For rounding up, we want to have r have the opposite sign of
|
||||
// other; if not, we adjust q upward and r to match.
|
||||
if other.signum() == r.signum() { return q+1 }
|
||||
return q
|
||||
|
||||
case .towardZero:
|
||||
// This is exactly what the `/` operator did for us.
|
||||
return q
|
||||
|
||||
case .toOdd:
|
||||
// If q is already odd, we're done.
|
||||
if q._lowWord & 1 == 1 { return q }
|
||||
// Otherwise, q is even but inexact; it was originally rounded toward
|
||||
// zero, so rounding away from zero instead will make it odd.
|
||||
fallthrough
|
||||
case .awayFromZero:
|
||||
break
|
||||
|
||||
case .toNearestOrDown:
|
||||
if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||
|
||||
2*r.magnitude == other.magnitude && other.signum() != r.signum() {
|
||||
break
|
||||
}
|
||||
return q
|
||||
|
||||
case .toNearestOrUp:
|
||||
if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||
|
||||
2*r.magnitude == other.magnitude && other.signum() == r.signum() {
|
||||
break
|
||||
}
|
||||
return q
|
||||
|
||||
case .toNearestOrZero:
|
||||
if r.magnitude <= other.magnitude.shifted(rightBy: 1, rounding: .down) {
|
||||
return q
|
||||
}
|
||||
// Otherwise, round q away from zero.
|
||||
|
||||
case .toNearestOrAway:
|
||||
// To round away from zero, we apply the adjustments for both down
|
||||
// and up.
|
||||
if other.signum() != r.signum() { return q-1 }
|
||||
return q+1
|
||||
case .toNearestOrAwayFromZero:
|
||||
// For round to nearest or away, the condition we want to satisfy is
|
||||
// |r| <= |other/2|, with sign(q) != sign(r) when equality holds.
|
||||
if r.magnitude < other.magnitude.shifted(rightBy: 1, rounding: .up) {
|
||||
return q
|
||||
}
|
||||
|
||||
// The (q,r) we have does not satisfy the to nearest or away condition;
|
||||
// round away from zero to choose the other representative of (q, r).
|
||||
if other.signum() != r.signum() { return q-1 }
|
||||
return q+1
|
||||
case .toNearestOrEven:
|
||||
// First guarantee that |r| <= |other/2|; if not we have to round away
|
||||
// instead, so break to do that.
|
||||
if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||
|
||||
2*r.magnitude == other.magnitude && !q.isMultiple(of: 2) {
|
||||
break
|
||||
// For round to nearest or away, the condition we want to satisfy is
|
||||
// |r| <= |other/2|, with q even when equality holds.
|
||||
if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||
|
||||
2*r.magnitude == other.magnitude && q._lowWord & 1 == 1 {
|
||||
if (other > 0) != (r > 0) { return q-1 }
|
||||
return q+1
|
||||
}
|
||||
return q
|
||||
case .stochastically:
|
||||
var qhi: UInt64
|
||||
var rhi: UInt64
|
||||
if other.magnitude <= UInt64.max {
|
||||
qhi = UInt64(other.magnitude)
|
||||
rhi = UInt64(r.magnitude)
|
||||
} else {
|
||||
// TODO: this is untested currently.
|
||||
let qmag = other.magnitude
|
||||
let shift = qmag._msb - 1
|
||||
qhi = UInt64(truncatingIfNeeded: qmag >> shift)
|
||||
rhi = UInt64(truncatingIfNeeded: r.magnitude >> shift)
|
||||
}
|
||||
let (sum, car) = rhi.addingReportingOverflow(.random(in: 0 ..< qhi))
|
||||
if car || sum >= qhi {
|
||||
if (other > 0) != (r > 0) { return q-1 }
|
||||
return q+1
|
||||
}
|
||||
return q
|
||||
|
||||
case .toOdd:
|
||||
// If q is already odd, we have the correct result.
|
||||
if q._lowWord & 1 == 1 { return q }
|
||||
|
||||
case .requireExact:
|
||||
preconditionFailure("Division was not exact.")
|
||||
}
|
||||
|
||||
// We didn't have the right result, so round q away from zero.
|
||||
return other.signum() == r.signum() ? q+1 : q-1
|
||||
}
|
||||
|
||||
// TODO: make this API and make it possible to implement more efficiently.
|
||||
@@ -154,10 +153,10 @@ extension SignedInteger {
|
||||
/// Divides `self` by `other`, rounding the quotient according to `rule`,
|
||||
/// and returns the remainder.
|
||||
///
|
||||
/// The default rounding rule is ``RoundingRule/down``, which _is not the
|
||||
/// same_ as the behavior of the `%` operator from the Swift standard
|
||||
/// library, but is chosen because it generally produces a more useful
|
||||
/// remainder. To match the behavior of `%`, use ``RoundingRule/towardZero``.
|
||||
/// The default rounding rule is `.down`, which _is not the same_ as the
|
||||
/// behavior of the `%` operator from the Swift standard library, but is
|
||||
/// chosen because it generally produces a more useful remainder. To
|
||||
/// match the behavior of `%`, use the `.towardZero` rounding mode.
|
||||
///
|
||||
/// - Precondition: `other` cannot be zero.
|
||||
@inlinable
|
||||
@@ -173,10 +172,10 @@ extension SignedInteger {
|
||||
/// Divides `self` by `other`, rounding the quotient according to `rule`,
|
||||
/// and returns both the quotient and remainder.
|
||||
///
|
||||
/// The default rounding rule is ``RoundingRule/down``, which _is not the
|
||||
/// same_ as the behavior of the `%` operator from the Swift standard
|
||||
/// library, but is chosen because it generally produces a more useful
|
||||
/// remainder. To match the behavior of `/`, use ``RoundingRule/towardZero``.
|
||||
/// The default rounding rule is `.down`, which _is not the same_ as the
|
||||
/// behavior of the `/` operator from the Swift standard library, but is
|
||||
/// chosen because it generally produces a more useful remainder. To
|
||||
/// match the behavior of `/`, use the `.towardZero` rounding mode.
|
||||
///
|
||||
/// Because the default rounding mode does not match Swift's standard
|
||||
/// library, this function is a disfavored overload of `divided(by:)`
|
||||
@@ -222,77 +221,68 @@ extension SignedInteger {
|
||||
// For rounding down, we want to have r match the sign of other
|
||||
// rather than self; this means that if the signs of r and other
|
||||
// disagree, we have to adjust q downward and r to match.
|
||||
return other.signum() == r.signum() ? (q, r) : (q-1, r+other)
|
||||
|
||||
if other.signum() != r.signum() { return (q-1, r+other) }
|
||||
return (q, r)
|
||||
case .up:
|
||||
// For rounding up, we want to have r have the opposite sign of
|
||||
// other; if not, we adjust q upward and r to match.
|
||||
return other.signum() == r.signum() ? (q+1, r-other) : (q, r)
|
||||
|
||||
if other.signum() == r.signum() { return (q+1, r-other) }
|
||||
return (q, r)
|
||||
case .towardZero:
|
||||
// This is exactly what the `/` operator did for us.
|
||||
return (q, r)
|
||||
|
||||
case .awayFromZero:
|
||||
break
|
||||
|
||||
case .toNearestOrDown:
|
||||
// If |r| < |other/2|, we already rounded q to nearest. If the are
|
||||
// equal and q is negative, then we already broke the tie in the right
|
||||
// direction. However, we don't have access to the before-rounding q,
|
||||
// which may have rounded up to zero, losing the sign information, so
|
||||
// we have to look at other and r instead.
|
||||
if 2*r.magnitude < other.magnitude ||
|
||||
2*r.magnitude == other.magnitude && other.signum() == r.signum() {
|
||||
return (q, r)
|
||||
}
|
||||
|
||||
case .toNearestOrUp:
|
||||
// If |r| < |other/2|, we already rounded q to nearest. If the are
|
||||
// equal and q is non-negative, then we already broke the tie in the
|
||||
// right direction.
|
||||
if 2*r.magnitude < other.magnitude ||
|
||||
2*r.magnitude == other.magnitude && other.signum() != r.signum() {
|
||||
return (q, r)
|
||||
}
|
||||
|
||||
case .toNearestOrZero:
|
||||
// Check first if |r| <= |other/2|. If this holds, we have already
|
||||
// rounded q correctly. Because we're working with magnitudes, we can
|
||||
// safely compute 2r without worrying about overflow, even for fixed-
|
||||
// width types, because r cannot be .min (because |r| < |other| by
|
||||
// construction).
|
||||
if 2*r.magnitude <= other.magnitude {
|
||||
return (q, r)
|
||||
}
|
||||
|
||||
case .toNearestOrAway:
|
||||
// Check first if |r| < |other/2|. If this holds, we already rounded
|
||||
// q to nearest.
|
||||
if 2*r.magnitude < other.magnitude {
|
||||
return (q, r)
|
||||
}
|
||||
|
||||
case .toNearestOrEven:
|
||||
// If |r| < |other/2|, we already rounded q to nearest. If the are
|
||||
// equal and q is even, then we already broke the tie in the right
|
||||
// direction.
|
||||
if 2*r.magnitude < other.magnitude ||
|
||||
2*r.magnitude == other.magnitude && q.isMultiple(of: 2) {
|
||||
return (q, r)
|
||||
}
|
||||
|
||||
case .toOdd:
|
||||
// If q is already odd, we have the correct result.
|
||||
// If q is already odd, we're done.
|
||||
if q._lowWord & 1 == 1 { return (q, r) }
|
||||
|
||||
// Otherwise, q is even but inexact; it was originally rounded toward
|
||||
// zero, so rounding away from zero instead will make it odd.
|
||||
fallthrough
|
||||
case .awayFromZero:
|
||||
// To round away from zero, we apply the adjustments for both down
|
||||
// and up.
|
||||
if other.signum() != r.signum() { return (q-1, r+other) }
|
||||
return (q+1, r-other)
|
||||
case .toNearestOrAwayFromZero:
|
||||
// For round to nearest or away, the condition we want to satisfy is
|
||||
// |r| <= |other/2|, with sign(q) != sign(r) when equality holds.
|
||||
if r.magnitude < other.magnitude.shifted(rightBy: 1, rounding: .up) {
|
||||
return (q, r)
|
||||
}
|
||||
// The (q,r) we have does not satisfy the to nearest or away condition;
|
||||
// round away from zero to choose the other representative of (q, r).
|
||||
if other.signum() != r.signum() { return (q-1, r+other) }
|
||||
return (q+1, r-other)
|
||||
case .toNearestOrEven:
|
||||
// For round to nearest or away, the condition we want to satisfy is
|
||||
// |r| <= |other/2|, with q even when equality holds.
|
||||
if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||
|
||||
2*r.magnitude == other.magnitude && q._lowWord & 1 == 1 {
|
||||
if (other > 0) != (r > 0) { return (q-1, r+other) }
|
||||
return (q+1, r-other)
|
||||
}
|
||||
return (q, r)
|
||||
case .stochastically:
|
||||
var qhi: UInt64
|
||||
var rhi: UInt64
|
||||
if other.magnitude <= UInt64.max {
|
||||
qhi = UInt64(other.magnitude)
|
||||
rhi = UInt64(r.magnitude)
|
||||
} else {
|
||||
// TODO: this is untested currently.
|
||||
let qmag = other.magnitude
|
||||
let shift = qmag._msb - 1
|
||||
qhi = UInt64(truncatingIfNeeded: qmag >> shift)
|
||||
rhi = UInt64(truncatingIfNeeded: r.magnitude >> shift)
|
||||
}
|
||||
let (sum, car) = rhi.addingReportingOverflow(.random(in: 0 ..< qhi))
|
||||
if car || sum >= qhi {
|
||||
if (other > 0) != (r > 0) { return (q-1, r+other) }
|
||||
return (q+1, r-other)
|
||||
}
|
||||
return (q, r)
|
||||
case .requireExact:
|
||||
preconditionFailure("Division was not exact.")
|
||||
}
|
||||
|
||||
// Fallthrough behavior is to round q away from zero and adjust r to
|
||||
// match.
|
||||
return other.signum() == r.signum() ? (q+1, r-other) : (q-1, r+other)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -318,7 +308,7 @@ extension SignedInteger {
|
||||
/// is not representable.
|
||||
///
|
||||
/// - Returns: `(quotient, remainder)`, with `0 <= remainder < b.magnitude`.
|
||||
public func euclideanDivision<T>(_ a: T, _ b: T) -> (quotient: T, remainder: T)
|
||||
func euclideanDivision<T>(_ a: T, _ b: T) -> (quotient: T, remainder: T)
|
||||
where T: SignedInteger
|
||||
{
|
||||
a.divided(by: b, rounding: a >= 0 ? .towardZero : .awayFromZero)
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2021-2024 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// The [greatest common divisor][gcd] of `a` and `b`.
|
||||
/// The greatest common divisor of `a` and `b`.
|
||||
///
|
||||
/// If both inputs are zero, the result is zero. If one input is zero, the
|
||||
/// result is the absolute value of the other input.
|
||||
@@ -21,20 +21,33 @@
|
||||
/// gcd(Int.min, Int.min) // Overflow error
|
||||
/// gcd(Int.min, 0) // Overflow error
|
||||
///
|
||||
/// [gcd]: https://en.wikipedia.org/wiki/Greatest_common_divisor
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Greatest_common_divisor
|
||||
@inlinable
|
||||
public func gcd<T: BinaryInteger>(_ a: T, _ b: T) -> T {
|
||||
var x = a
|
||||
var y = b
|
||||
if x.magnitude < y.magnitude { swap(&x, &y) }
|
||||
// Avoid overflow when x = signed min, y = -1.
|
||||
if y.magnitude == 1 { return 1 }
|
||||
// Euclidean algorithm for GCD. It's worth using Lehmer instead for larger
|
||||
// integer types, but for now this is good and dead-simple and faster than
|
||||
// the other obvious choice, the binary algorithm.
|
||||
while y != 0 { (x, y) = (y, x%y) }
|
||||
// Try to convert result to T.
|
||||
if let result = T(exactly: x.magnitude) { return result }
|
||||
// If that fails, produce a diagnostic.
|
||||
fatalError("GCD (\(x)) is not representable as \(T.self).")
|
||||
var x = a.magnitude
|
||||
var y = b.magnitude
|
||||
|
||||
if x == 0 { return T(y) }
|
||||
if y == 0 { return T(x) }
|
||||
|
||||
let xtz = x.trailingZeroBitCount
|
||||
let ytz = y.trailingZeroBitCount
|
||||
|
||||
y >>= ytz
|
||||
|
||||
// The binary GCD algorithm
|
||||
//
|
||||
// After the right-shift in the loop, both x and y are odd. Each pass removes
|
||||
// at least one low-order bit from the larger of the two, so the number of
|
||||
// iterations is bounded by the sum of the bit-widths of the inputs.
|
||||
//
|
||||
// A tighter bound is the maximum bit-width of the inputs, which is achieved
|
||||
// by odd numbers that sum to a power of 2, though the proof is more involved.
|
||||
repeat {
|
||||
x >>= x.trailingZeroBitCount
|
||||
if x < y { swap(&x, &y) }
|
||||
x -= y
|
||||
} while x != 0
|
||||
|
||||
return T(y << min(xtz, ytz))
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2021-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -17,56 +17,38 @@
|
||||
///
|
||||
/// Examples using rounding to integer to illustrate the various options:
|
||||
/// ```
|
||||
/// Directed rounding rules
|
||||
///
|
||||
/// value | down | up | towardZero | awayFromZero |
|
||||
/// =======+==============+==============+==============+==============+
|
||||
/// -1.5 | -2 | -1 | -1 | -2 |
|
||||
/// 1.5 | 1 | 2 | 1 | 2 |
|
||||
/// -------+--------------+--------------+--------------+--------------+
|
||||
/// -0.5 | -1 | 0 | 0 | -1 |
|
||||
/// -------+--------------+--------------+--------------+--------------+
|
||||
/// 0.5 | 0 | 1 | 0 | 1 |
|
||||
/// 0.3 | 0 | 1 | 0 | 1 |
|
||||
/// -------+--------------+--------------+--------------+--------------+
|
||||
/// 0.7 | 0 | 1 | 0 | 1 |
|
||||
/// -------+--------------+--------------+--------------+--------------+
|
||||
/// 1.2 | 1 | 2 | 1 | 2 |
|
||||
/// -------+--------------+--------------+--------------+--------------+
|
||||
/// 2.0 | 2 | 2 | 2 | 2 |
|
||||
/// 2 | 2 | 2 | 2 | 2 |
|
||||
/// -------+--------------+--------------+--------------+--------------+
|
||||
///
|
||||
/// toNearestOr... rounding rules
|
||||
/// value | toOdd | toNearestOrAwayFromZero | toNearestOrEven |
|
||||
/// =======+==============+=========================+==================+
|
||||
/// 1.5 | 1 | 2 | 2 |
|
||||
/// -------+--------------+-------------------------+------------------+
|
||||
/// -0.5 | -1 | -1 | 0 |
|
||||
/// -------+--------------+-------------------------+------------------+
|
||||
/// 0.3 | 1 | 0 | 0 |
|
||||
/// -------+--------------+-------------------------+------------------+
|
||||
/// 2 | 2 | 2 | 2 |
|
||||
/// -------+--------------+-------------------------+------------------+
|
||||
///
|
||||
/// value | orDown | orUp | orZero | orAway | orEven |
|
||||
/// =======+==========+==========+==========+==========+==========+
|
||||
/// -1.5 | -2 | -1 | -1 | -2 | -2 |
|
||||
/// -------+----------+----------+----------+----------+----------+
|
||||
/// -0.5 | -1 | 0 | 0 | -1 | 0 |
|
||||
/// -------+----------+----------+----------+----------+----------+
|
||||
/// 0.5 | 0 | 1 | 0 | 1 | 0 |
|
||||
/// -------+----------+----------+----------+----------+----------+
|
||||
/// 0.7 | 1 | 1 | 1 | 1 | 1 |
|
||||
/// -------+----------+----------+----------+----------+----------+
|
||||
/// 1.2 | 1 | 1 | 1 | 1 | 1 |
|
||||
/// -------+----------+----------+----------+----------+----------+
|
||||
/// 2.0 | 2 | 2 | 2 | 2 | 2 |
|
||||
/// -------+----------+----------+----------+----------+----------+
|
||||
///
|
||||
/// Specialized rounding rules
|
||||
///
|
||||
/// value | toOdd | requireExact |
|
||||
/// =======+==============+================+
|
||||
/// -1.5 | -1 | trap |
|
||||
/// -------+--------------+----------------+
|
||||
/// -0.5 | -1 | trap |
|
||||
/// -------+--------------+----------------+
|
||||
/// 0.5 | 1 | trap |
|
||||
/// -------+--------------+----------------+
|
||||
/// 0.7 | 1 | trap |
|
||||
/// -------+--------------+----------------+
|
||||
/// 1.2 | 1 | trap |
|
||||
/// -------+--------------+----------------+
|
||||
/// 2.0 | 2 | 2 |
|
||||
/// -------+--------------+----------------+
|
||||
/// value | stochastically | requireExact |
|
||||
/// =======+=======================+================+
|
||||
/// 1.5 | 50% 1, 50% 2 | trap |
|
||||
/// -------+-----------------------+----------------+
|
||||
/// -0.5 | 50% -1, 50% 0 | trap |
|
||||
/// -------+-----------------------+----------------+
|
||||
/// 0.3 | 70% 0, 30% 1 | trap |
|
||||
/// -------+-----------------------+----------------+
|
||||
/// 2 | 2 | 2 |
|
||||
/// -------+-----------------------+----------------+
|
||||
/// ```
|
||||
public enum RoundingRule {
|
||||
/// Produces the closest representable value that is less than or equal
|
||||
@@ -131,54 +113,18 @@ public enum RoundingRule {
|
||||
/// even though 2 is even, because 4/2 is exactly 2 and no rounding occurs.
|
||||
case toOdd
|
||||
|
||||
/// Produces the representable value that is closest to the value being
|
||||
/// rounded. If two values are equally close, the one that is less than
|
||||
/// the value being rounded is chosen.
|
||||
///
|
||||
/// Examples:
|
||||
/// - `(-4).divided(by: 3, rounding: .toNearestOrDown)`
|
||||
/// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2.
|
||||
///
|
||||
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrDown)` is `2`,
|
||||
/// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is less.
|
||||
case toNearestOrDown
|
||||
|
||||
/// Produces the representable value that is closest to the value being
|
||||
/// rounded. If two values are equally close, the one that is greater than
|
||||
/// the value being rounded is chosen.
|
||||
///
|
||||
/// Examples:
|
||||
/// - `(-4).divided(by: 3, rounding: .toNearestOrUp)`
|
||||
/// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2.
|
||||
///
|
||||
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrUp)` is `3`,
|
||||
/// because 5/2 = 2.5 is equally close to 2 and 3, and 3 is greater.
|
||||
case toNearestOrUp
|
||||
|
||||
/// Produces the representable value that is closest to the value being
|
||||
/// rounded. If two values are equally close, the one that has smaller
|
||||
/// magnitude is returned.
|
||||
///
|
||||
/// Examples:
|
||||
/// - `(-4).divided(by: 3, rounding: .toNearestOrZero)`
|
||||
/// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2.
|
||||
///
|
||||
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrZero)` is `3`,
|
||||
/// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is closer to zero.
|
||||
case toNearestOrZero
|
||||
|
||||
/// Produces the representable value that is closest to the value being
|
||||
/// rounded. If two values are equally close, the one that has greater
|
||||
/// magnitude is returned.
|
||||
///
|
||||
/// Examples:
|
||||
/// - `(-4).divided(by: 3, rounding: .toNearestOrAway)`
|
||||
/// - `(-4).divided(by: 3, rounding: .toNearestOrAwayFromZero)`
|
||||
/// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2.
|
||||
///
|
||||
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrAway)` is `3`,
|
||||
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrAwayFromZero)` is `3`,
|
||||
/// because 5/2 = 2.5 is equally close to 2 and 3, and 3 is further away
|
||||
/// from zero.
|
||||
case toNearestOrAway
|
||||
case toNearestOrAwayFromZero
|
||||
|
||||
/// Produces the representable value that is closest to the value being
|
||||
/// rounded. If two values are equally close, the one whose least
|
||||
@@ -192,6 +138,45 @@ public enum RoundingRule {
|
||||
/// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is even.
|
||||
case toNearestOrEven
|
||||
|
||||
/// Adds a uniform random value from [0, d) to the value being rounded,
|
||||
/// where d is the distance between the two closest representable values,
|
||||
/// then rounds the sum downwards.
|
||||
///
|
||||
/// Unlike all the other rounding modes, this mode is _not deterministic_;
|
||||
/// repeated calls to rounding operations with this mode will generally
|
||||
/// produce different results. There is a tradeoff implicit in using this
|
||||
/// mode: you can sacrifice _reproducible_ results to get _more accurate_
|
||||
/// results in aggregate. For a contrived but illustrative example, consider
|
||||
/// the following:
|
||||
/// ```
|
||||
/// let data = Array(repeating: 1, count: 100)
|
||||
/// let result = data.reduce(0) {
|
||||
/// $0 + $1.divided(by: 3, rounding: rule)
|
||||
/// }
|
||||
/// ```
|
||||
/// because 1/3 is always the same value between 0 and 1, any
|
||||
/// deterministic rounding rule must produce either 0 or 100 for
|
||||
/// this computation. But rounding `stochastically` will
|
||||
/// produce a value close to 33. The _error_ of the computation
|
||||
/// is smaller, but the result will now change between runs of the
|
||||
/// program.
|
||||
///
|
||||
/// For this simple case a better solution would be to add the
|
||||
/// values first, and then divide. This gives a result that is both
|
||||
/// reproducible _and_ accurate:
|
||||
/// ```
|
||||
/// let result = data.reduce(0, +)/3
|
||||
/// ```
|
||||
/// but this isn't always possible in more sophisticated scenarios,
|
||||
/// and in those cases this rounding rule may be useful.
|
||||
///
|
||||
/// Examples:
|
||||
/// - `(-4).divided(by: 3, rounding: .stochastically)`
|
||||
/// will be –1 with probability 2/3 and –2 with probability 1/3.
|
||||
/// - `5.shifted(rightBy: 1, rounding: .stochastically)`
|
||||
/// will be 2 with probability 1/2 and 3 with probability 1/2.
|
||||
case stochastically
|
||||
|
||||
/// If the value being rounded is representable, that value is returned.
|
||||
/// Otherwise, a precondition failure occurs.
|
||||
///
|
||||
@@ -200,67 +185,3 @@ public enum RoundingRule {
|
||||
/// because –4/3 = –1.3̅ is not an integer.
|
||||
case requireExact
|
||||
}
|
||||
|
||||
extension RoundingRule {
|
||||
/// Produces the representable value that is closest to the value being
|
||||
/// rounded. If two values are equally close, the one that has greater
|
||||
/// magnitude is returned.
|
||||
///
|
||||
/// > Deprecated: Use `.toNearestOrAway` instead.
|
||||
@inlinable
|
||||
@available(*, deprecated, renamed: "toNearestOrAway")
|
||||
public static var toNearestOrAwayFromZero: Self { .toNearestOrAway }
|
||||
}
|
||||
|
||||
extension FloatingPoint {
|
||||
/// `self` rounded to integer according to `rule`.
|
||||
///
|
||||
/// This mirrors the standard library `rounded` API, providing access to
|
||||
/// the expanded set of rounding rules defined in IntegerUtilities. It is
|
||||
/// not just a shadow because that would lead to ambiguity errors in
|
||||
/// existing code that uses the shortened `rounded(.down)` form.
|
||||
@inlinable @inline(__always)
|
||||
public func rounding(_ rule: RoundingRule) -> Self {
|
||||
switch rule {
|
||||
case .down:
|
||||
return rounded(.down)
|
||||
case .up:
|
||||
return rounded(.up)
|
||||
case .towardZero:
|
||||
return rounded(.towardZero)
|
||||
case .awayFromZero:
|
||||
return rounded(.awayFromZero)
|
||||
case .toNearestOrDown:
|
||||
// FP doesn't have toNearestOrDown, so round toNearestOrEven and fixup
|
||||
// any exact-halfway cases.
|
||||
let nearest = rounded(.toNearestOrEven)
|
||||
return nearest - self == 1/2 ? rounded(.down) : nearest
|
||||
case .toNearestOrUp:
|
||||
// FP doesn't have toNearestOrUp, so round toNearestOrEven and fixup
|
||||
// any exact-halfway cases.
|
||||
let nearest = rounded(.toNearestOrEven)
|
||||
return self - nearest == 1/2 ? rounded(.up) : nearest
|
||||
case .toNearestOrZero:
|
||||
// FP doesn't have toNearestOrZero, so round toNearestOrEven and fixup
|
||||
// any exact-halfway cases.
|
||||
let nearest = rounded(.toNearestOrEven)
|
||||
return (self - nearest).magnitude == 1/2 ? rounded(.towardZero) : nearest
|
||||
case .toNearestOrAway:
|
||||
return self.rounded(.toNearestOrAwayFromZero)
|
||||
case .toNearestOrEven:
|
||||
return self.rounded(.toNearestOrEven)
|
||||
case .toOdd:
|
||||
let trunc = rounded(.towardZero)
|
||||
if trunc == self { return trunc }
|
||||
let one = Self(signOf: self, magnitudeOf: 1)
|
||||
// We have eliminated all large values at this point; add ±0.5, and see
|
||||
// which way that rounds, then select the other value.
|
||||
let even = (trunc + one/2).rounded(.toNearestOrEven)
|
||||
return trunc == even ? trunc + one : trunc
|
||||
case .requireExact:
|
||||
let trunc = rounded(.towardZero)
|
||||
precondition(isInfinite || trunc == self, "\(self) is not an exact integer.")
|
||||
return self
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,8 +31,8 @@ extension FixedWidthInteger {
|
||||
/// let c = a.addingWithSaturation(b)
|
||||
/// ```
|
||||
///
|
||||
/// If the "normal addition" `self + other` does not trap,
|
||||
/// this method produces the same result.
|
||||
/// Anytime the "normal addition" `self + other` does not trap,
|
||||
/// `addingWithSaturation` produces the same result.
|
||||
@inlinable
|
||||
public func addingWithSaturation(_ other: Self) -> Self {
|
||||
let (wrapped, overflow) = addingReportingOverflow(other)
|
||||
@@ -54,8 +54,8 @@ extension FixedWidthInteger {
|
||||
/// `a.subtractingWithSaturation(b)`, because `-b` is not representable
|
||||
/// if `b` is the minimum value of a signed type.
|
||||
///
|
||||
/// If the "normal subtraction" `self - other` does not trap,
|
||||
/// this method produces the same result.
|
||||
/// Anytime the "normal subtraction" `self - other` does not trap,
|
||||
/// `subtractingWithSaturation` produces the same result.
|
||||
@inlinable
|
||||
public func subtractingWithSaturation(_ other: Self) -> Self {
|
||||
let (wrapped, overflow) = subtractingReportingOverflow(other)
|
||||
@@ -85,8 +85,8 @@ extension FixedWidthInteger {
|
||||
/// let c = a.multipliedWithSaturation(by: b)
|
||||
/// ```
|
||||
///
|
||||
/// If the "normal multiplication" `self * other` does not trap,
|
||||
/// this method produces the same result.
|
||||
/// Anytime the "normal multiplication" `self * other` does not trap,
|
||||
/// `multipliedWithSaturation` produces the same result.
|
||||
@inlinable
|
||||
public func multipliedWithSaturation(by other: Self) -> Self {
|
||||
let (high, low) = multipliedFullWidth(by: other)
|
||||
@@ -95,17 +95,17 @@ extension FixedWidthInteger {
|
||||
return Self.max &- high.signbit
|
||||
}
|
||||
|
||||
/// Bitwise left shift with rounding and saturation.
|
||||
/// Bitwise left with rounding and saturation.
|
||||
///
|
||||
/// `self` multiplied by the rational number 2^(`count`), saturated to the
|
||||
/// range `Self.min ... Self.max`, and rounded according to `rule`.
|
||||
///
|
||||
/// See `shifted(rightBy:rounding:)`, defined on `BinaryInteger`, for more
|
||||
/// discussion of rounding shifts with examples.
|
||||
/// See `shifted(rightBy:rounding:)` for more discussion of rounding
|
||||
/// shifts with examples.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - leftBy count: the number of bits to shift by. If positive, this is
|
||||
/// a left-shift, and if negative a right shift.
|
||||
/// - leftBy count: the number of bits to shift by. If positive, this is a left-shift,
|
||||
/// and if negative a right shift.
|
||||
/// - rounding rule: the direction in which to round if `count` is negative.
|
||||
@inlinable
|
||||
public func shiftedWithSaturation(
|
||||
@@ -154,8 +154,8 @@ extension FixedWidthInteger {
|
||||
/// shifts with examples.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - leftBy count: the number of bits to shift by. If positive, this is a
|
||||
/// left-shift, and if negative a right shift.
|
||||
/// - leftBy count: the number of bits to shift by. If positive, this is a left-shift,
|
||||
/// and if negative a right shift.
|
||||
/// - rounding rule: the direction in which to round if `count` is negative.
|
||||
@_transparent
|
||||
public func shiftedWithSaturation<Count: BinaryInteger>(
|
||||
|
||||
@@ -12,8 +12,8 @@
|
||||
extension BinaryInteger {
|
||||
/// `self` divided by 2^(`count`), rounding the result according to `rule`.
|
||||
///
|
||||
/// The default rounding rule is ``RoundingRule/down``, which matches the
|
||||
/// behavior of the `>>` operator from the standard library.
|
||||
/// The default rounding rule is `.down`, which matches the behavior of
|
||||
/// the `>>` operator from the standard library.
|
||||
///
|
||||
/// Some examples of different rounding rules:
|
||||
///
|
||||
@@ -105,7 +105,6 @@ extension BinaryInteger {
|
||||
let lost = Magnitude(truncatingIfNeeded: self) & mask
|
||||
let floor = self >> count
|
||||
let ceiling = floor + (lost == 0 ? 0 : 1)
|
||||
let half: Magnitude = (1 as Magnitude) << (count &- 1)
|
||||
switch rule {
|
||||
case .down:
|
||||
return floor
|
||||
@@ -115,21 +114,42 @@ extension BinaryInteger {
|
||||
return self > 0 ? floor : ceiling
|
||||
case .awayFromZero:
|
||||
return self < 0 ? floor : ceiling
|
||||
case .toNearestOrDown:
|
||||
return floor + Self((lost + (half - 1)) >> count)
|
||||
case .toNearestOrUp:
|
||||
return floor + Self((lost + half) >> count)
|
||||
case .toNearestOrZero:
|
||||
let round = half - (self < 0 ? 0 : 1)
|
||||
return floor + Self((round + lost) >> count)
|
||||
case .toNearestOrAway:
|
||||
let round = half - (self > 0 ? 0 : 1)
|
||||
case .toOdd:
|
||||
return floor | (lost == 0 ? 0 : 1)
|
||||
case .toNearestOrAwayFromZero:
|
||||
let round = mask >> 1 + (self > 0 ? 1 : 0)
|
||||
return floor + Self((round + lost) >> count)
|
||||
case .toNearestOrEven:
|
||||
let round = mask >> 1 + Magnitude(floor & 1)
|
||||
return floor + Self((round + lost) >> count)
|
||||
case .toOdd:
|
||||
return floor | (lost == 0 ? 0 : 1)
|
||||
case .stochastically:
|
||||
// TODO: it's unfortunate that we can't specify a custom random source
|
||||
// for the stochastically rounding rule, but I don't see a nice way to
|
||||
// have that share the API with the other rounding rules, because we'd
|
||||
// then have to take the RNG in-out. The same problem applies to
|
||||
// rounding with dithering. We should consider adding a stateful
|
||||
// rounding API down the road to support those use cases.
|
||||
//
|
||||
// In theory, u01 should be Self.random(in: 0 ..< onesBit), but the
|
||||
// random(in:) method does not exist on BinaryInteger. This is
|
||||
// (arguably) good, though, because there's actually no reason to
|
||||
// generate large amounts of randomness just to implement stochastic
|
||||
// rounding; 32b suffices for almost all purposes, and 64b is more
|
||||
// than enough.
|
||||
var g = SystemRandomNumberGenerator()
|
||||
let u01 = g.next()
|
||||
if count < 64 {
|
||||
// count is small, so mask and lost are representable as both
|
||||
// UInt64 and Self, regardless of what type Self actually is.
|
||||
return floor + Self(((u01 & UInt64(mask)) + UInt64(lost)) >> count)
|
||||
} else {
|
||||
// count is large, so lost may not be representable as UInt64; pre-
|
||||
// shift by count-64 to isolate the high 64b of the fraction, then
|
||||
// add u01 and carry-out to round.
|
||||
let highWord = UInt64(truncatingIfNeeded: lost >> (Int(count) - 64))
|
||||
let (_, carry) = highWord.addingReportingOverflow(u01)
|
||||
return floor + (carry ? 1 : 0)
|
||||
}
|
||||
case .requireExact:
|
||||
precondition(lost == 0, "shift was not exact.")
|
||||
return floor
|
||||
@@ -138,8 +158,8 @@ extension BinaryInteger {
|
||||
|
||||
/// `self` divided by 2^(`count`), rounding the result according to `rule`.
|
||||
///
|
||||
/// The default rounding rule is ``RoundingRule/down``, which matches the
|
||||
/// behavior of the `>>` operator from the standard library.
|
||||
/// The default rounding rule is `.down`, which matches the behavior of
|
||||
/// the `>>` operator from the standard library.
|
||||
///
|
||||
/// Some examples of different rounding rules:
|
||||
///
|
||||
|
||||
@@ -19,6 +19,7 @@ target_compile_options(Numerics PUBLIC
|
||||
# load symbol when validating the TBD
|
||||
-Xfrontend -validate-tbd-against-ir=none)
|
||||
target_link_libraries(Numerics PUBLIC
|
||||
BigIntModule
|
||||
ComplexModule
|
||||
IntegerUtilities
|
||||
RealModule)
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// A module that re-exports the complete Swift Numerics public API.
|
||||
@_exported import BigIntModule
|
||||
@_exported import ComplexModule
|
||||
@_exported import IntegerUtilities
|
||||
@_exported import RealModule
|
||||
@_exported import QuaternionModule
|
||||
@@ -1,83 +0,0 @@
|
||||
//===--- 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])
|
||||
}
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
//===--- 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)
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
//===--- 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
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
//===--- 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)
|
||||
}
|
||||
}
|
||||
@@ -1,221 +0,0 @@
|
||||
//===--- 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)
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
//===--- 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
//===--- 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))
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
//===--- 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()))
|
||||
}
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
//===--- 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
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
//===--- 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))"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,302 +0,0 @@
|
||||
//===--- 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))
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,39 +0,0 @@
|
||||
//===--- 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)
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
# Transformation
|
||||
|
||||
In computer science, quaternions are frequently used to represent three-dimensional rotations; as quaternions have some [advantages over other representations][advantages].
|
||||
|
||||
`Transformation.swift` encapsulates an API to interact with the three-dimensional transformation properties of quaternions. It provides conversions to and from other rotation representations, namely [*Angle-Axis*][angle_axis_wiki], [*Rotation Vector*][rotation_vector_wiki] and [*Polar decomposition*][polar_wiki], as well as it provides methods to directly transform arbitrary vectors by quaternions.
|
||||
|
||||
## Policies
|
||||
|
||||
- zero and non-finite quaternions have indeterminate transformation properties and can not be converted to other representations. Thus,
|
||||
|
||||
- The `angle` of `.zero` or `.infinity` is `RealType.nan`.
|
||||
- The `axis` of `.zero` or `.infinity` is `RealType.nan` in all lanes.
|
||||
- The `rotationVector` of `.zero` or `.infinity` is `RealType.nan` in all lanes.
|
||||
- The polar `phase` of `.zero` or `.infinity` is `RealType.nan`
|
||||
|
||||
- Quaternions with an `angle` of `.zero` have an indeterminate rotation axis. Thus,
|
||||
|
||||
- the `axis` of `angle == .zero` is `RealType.nan` in all lanes.
|
||||
- the `rotationVector` of `angle == .zero` is `RealType.nan` in all lanes.
|
||||
|
||||
|
||||
[advantages]: https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Advantages_of_quaternions
|
||||
[angle_axis_wiki]: https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Recovering_the_axis-angle_representation
|
||||
[polar_wiki]: https://en.wikipedia.org/wiki/Polar_decomposition#Quaternion_polar_decomposition
|
||||
[rotation_vector_wiki]: https://en.wikipedia.org/wiki/Axis–angle_representation#Rotation_vector
|
||||
@@ -1,271 +0,0 @@
|
||||
//===--- 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
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// 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
|
||||
@@ -32,16 +32,15 @@
|
||||
/// Because integer multiplication does not form a group; it's commutative and
|
||||
/// associative, but integers do not have multiplicative inverses.
|
||||
/// I.e. if a is any integer other than 1 or -1, there is no integer b such
|
||||
/// that `a*b = 1`. The existence of inverses is requried to form a field.
|
||||
/// that a*b = 1. The existence of inverses is requried to form a field.
|
||||
///
|
||||
/// If a type `T` conforms to the ``Real`` protocol, then `T` and `Complex<T>`
|
||||
/// If a type `T` conforms to the `Real` protocol, then `T` and `Complex<T>`
|
||||
/// both conform to `AlgebraicField`.
|
||||
///
|
||||
/// See also Swift's `SignedNumeric`, `Numeric` and `AdditiveArithmetic`
|
||||
/// protocols.
|
||||
/// See also `Real`, `SignedNumeric`, `Numeric` and `AdditiveArithmetic`.
|
||||
///
|
||||
/// [field]: https://en.wikipedia.org/wiki/Field_(mathematics)
|
||||
public protocol AlgebraicField: SignedNumeric where Magnitude: AlgebraicField {
|
||||
public protocol AlgebraicField: SignedNumeric {
|
||||
|
||||
/// Replaces a with the (approximate) quotient `a/b`.
|
||||
static func /=(a: inout Self, b: Self)
|
||||
@@ -91,10 +90,10 @@ public protocol AlgebraicField: SignedNumeric where Magnitude: AlgebraicField {
|
||||
/// ```
|
||||
var reciprocal: Self? { get }
|
||||
|
||||
/// `a + b`, with the optimizer licensed to reassociate and form FMAs.
|
||||
/// a + b, with the optimizer licensed to reassociate and form FMAs.
|
||||
static func _relaxedAdd(_ a: Self, _ b: Self) -> Self
|
||||
|
||||
/// `a * b`, with the optimizer licensed to reassociate and form FMAs.
|
||||
/// a * b, with the optimizer licensed to reassociate and form FMAs.
|
||||
static func _relaxedMul(_ a: Self, _ b: Self) -> Self
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2020-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// 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
|
||||
@@ -47,7 +47,7 @@ extension Numeric where Magnitude: FloatingPoint {
|
||||
/// property implements a valid norm.)
|
||||
///
|
||||
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _scale invariant_,
|
||||
/// so long as no underflow or overflow has occurred, and no exceptional
|
||||
/// so long as no underflow or overflow has occured, and no exceptional
|
||||
/// value is produced by the scaling.
|
||||
///
|
||||
/// See also `isApproximatelyEqual(to:absoluteTolerance:[relativeTolerance:norm:])`.
|
||||
@@ -218,7 +218,7 @@ extension AdditiveArithmetic {
|
||||
/// norm: \.length
|
||||
/// )
|
||||
/// ```
|
||||
/// (if we used the default norm, `\.magnitude`, we would be testing if
|
||||
/// (if we used the default norm, `.magnitude`, we would be testing if
|
||||
/// `z` were inside a square region instead.)
|
||||
@inlinable
|
||||
public func isApproximatelyEqual<Magnitude>(
|
||||
@@ -227,6 +227,12 @@ extension AdditiveArithmetic {
|
||||
relativeTolerance: Magnitude = 0,
|
||||
norm: (Self) -> Magnitude
|
||||
) -> Bool
|
||||
// TODO: constraint should really be weaker than FloatingPoint,
|
||||
// but we need to have `isFinite` for it to work correctly with
|
||||
// floating-point magnitudes in generic contexts, which is the
|
||||
// most common case. The fix for this is to lift the isFinite
|
||||
// requirement to Numeric in the standard library, but that's
|
||||
// source-breaking, so requires an ABI rumspringa.
|
||||
where Magnitude: FloatingPoint {
|
||||
assert(
|
||||
absoluteTolerance >= 0 && absoluteTolerance.isFinite,
|
||||
|
||||
@@ -2,13 +2,19 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2020-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2020-2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A namespace for "augmented arithmetic" operations for types conforming to
|
||||
/// `Real`.
|
||||
///
|
||||
/// Augmented arithmetic refers to a family of algorithms that represent
|
||||
/// the results of floating-point computations using multiple values such that
|
||||
/// either the error is minimized or the result is exact.
|
||||
public enum Augmented { }
|
||||
|
||||
extension Augmented {
|
||||
@@ -39,9 +45,7 @@ extension Augmented {
|
||||
/// - If both `head` and `tail` are normal, then `a * b` is exactly
|
||||
/// equal to `head + tail` when computed as real numbers.
|
||||
@_transparent
|
||||
public static func product<T:FloatingPoint>(
|
||||
_ a: T, _ b: T
|
||||
) -> (head: T, tail: T) {
|
||||
public static func product<T:Real>(_ a: T, _ b: T) -> (head: T, tail: T) {
|
||||
let head = a*b
|
||||
// TODO: consider providing an FMA-less implementation for use when
|
||||
// targeting platforms without hardware FMA support. This works everywhere,
|
||||
@@ -52,30 +56,24 @@ extension Augmented {
|
||||
|
||||
/// The sum `a + b` represented as an implicit sum `head + tail`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - a: The summand with larger magnitude.
|
||||
/// - b: The summand with smaller magnitude.
|
||||
///
|
||||
/// `head` is the correctly rounded value of `a + b`. `tail` is the
|
||||
/// error from that computation rounded to the closest representable
|
||||
/// value.
|
||||
///
|
||||
/// > Note:
|
||||
/// > `tail` is guaranteed to be the best approximation to the error of
|
||||
/// the sum only if `large.magnitude` >= `small.magnitude`. If this is
|
||||
/// not the case, then `head` is the correctly rounded sum, but `tail`
|
||||
/// is not guaranteed to be the exact error. If you do not know a priori
|
||||
/// how the magnitudes of `a` and `b` compare, you likely want to use
|
||||
/// ``sum(_:_:)`` instead.
|
||||
///
|
||||
/// Unlike ``product(_:_:)``, the rounding error of `sum` never underflows.
|
||||
/// Unlike `Augmented.product(a, b)`, the rounding error of a sum can
|
||||
/// never underflow.
|
||||
///
|
||||
/// This operation is sometimes called ["fastTwoSum"].
|
||||
///
|
||||
/// > Note:
|
||||
/// > Classical fastTwoSum does not work when `radix` is 10. This function
|
||||
/// will fall back on another algorithm for decimal floating-point types
|
||||
/// to ensure correct results.
|
||||
/// - Parameters:
|
||||
/// - a: The summand with larger magnitude.
|
||||
/// - b: The summand with smaller magnitude.
|
||||
///
|
||||
/// Preconditions:
|
||||
///
|
||||
/// - `large.magnitude` must not be smaller than `small.magnitude`.
|
||||
/// They may be equal, or one or both may be `NaN`.
|
||||
/// This precondition is only enforced in debug builds.
|
||||
///
|
||||
/// Edge Cases:
|
||||
///
|
||||
@@ -90,37 +88,35 @@ extension Augmented {
|
||||
///
|
||||
/// ["fastTwoSum"]: https://en.wikipedia.org/wiki/2Sum
|
||||
@_transparent
|
||||
public static func sum<T: FloatingPoint>(
|
||||
large a: T, small b: T
|
||||
) -> (head: T, tail: T) {
|
||||
// Fall back on 2Sum if radix != 2. Future implementations might use an
|
||||
// cheaper algorithm specialized for decimal FP, but must deliver a
|
||||
// correct result if the preconditions are satisfied.
|
||||
guard T.radix == 2 else { return sum(a, b) }
|
||||
// Fast2Sum:
|
||||
public static func sum<T:Real>(large a: T, small b: T) -> (head: T, tail: T) {
|
||||
assert(!(b.magnitude > a.magnitude))
|
||||
let head = a + b
|
||||
let tail = a - head + b
|
||||
return (head, tail)
|
||||
}
|
||||
|
||||
|
||||
/// The sum `a + b` represented as an implicit sum `head + tail`.
|
||||
///
|
||||
/// `head` is the correctly rounded value of `a + b`. `tail` is the
|
||||
/// error from that computation rounded to the closest representable
|
||||
/// value.
|
||||
///
|
||||
/// The magnitude of the summands does not change the result of this
|
||||
/// operation. If you know statically that `a.magnitude >= b.magnitude`,
|
||||
/// you may want to consider using ``sum(large:small:)`` to get the same
|
||||
/// result somewhat more efficiently. If you do not have such a static
|
||||
/// bound, you usually want to use this function instead.
|
||||
/// Unlike `Augmented.sum(large: a, small: b)`, the magnitude of the summands
|
||||
/// does not matter and `a.magnitude` might as well be strictly less than
|
||||
/// `b.magnitude`. However, it is recommended to only use this function over
|
||||
/// `Augmented.sum(large: a, small: b)` in cases where the ordering of the
|
||||
/// summands magnitude is unknown at compile time. In cases where either of
|
||||
/// the summands magnitude is guaranteed to be greater than or equal the
|
||||
/// magnitude of the other summand, use `Augmented.sum(large: a, small: b)`
|
||||
/// over this function; as it faster to calculate.
|
||||
///
|
||||
/// Unlike ``product(_:_:)``, the rounding error of `sum` never underflows.
|
||||
/// Unlike `Augmented.product(a, b)`, the rounding error of a sum can
|
||||
/// never underflow.
|
||||
///
|
||||
/// This operation is sometimes called ["twoSum"].
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - a: One of the summands
|
||||
/// - a: One of the summand
|
||||
/// - b: The other summand
|
||||
///
|
||||
/// Edge Cases:
|
||||
@@ -130,15 +126,13 @@ extension Augmented {
|
||||
/// interpreted as having any meaning (it may be `NaN` or `infinity`).
|
||||
///
|
||||
/// Postconditions:
|
||||
///
|
||||
///
|
||||
/// - If `head` is normal, then `abs(tail) < head.ulp`.
|
||||
/// Assuming IEEE 754 default rounding, `abs(tail) <= head.ulp/2`.
|
||||
///
|
||||
/// ["twoSum"]: https://en.wikipedia.org/wiki/2Sum
|
||||
@_transparent
|
||||
public static func sum<T: FloatingPoint>(
|
||||
_ a: T, _ b: T
|
||||
) -> (head: T, tail: T) {
|
||||
public static func sum<T: Real>(_ a: T, _ b: T) -> (head: T, tail: T) {
|
||||
let head = a + b
|
||||
let x = head - b
|
||||
let y = head - x
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
# ``Augmented``
|
||||
|
||||
A namespace for a family of algorithms that compute the results of floating-
|
||||
point arithmetic using multiple values such that either the error is minimized
|
||||
or the result is exact.
|
||||
|
||||
## Overview
|
||||
|
||||
Consider multiplying two Doubles. A Double has 53 significand bits, so their
|
||||
product could be up to 106 bits wide before it is rounded to a Double result.
|
||||
So up to 53 of those 106 bits will be "lost" in that process:
|
||||
|
||||
```swift
|
||||
let a = 1.0 + .ulpOfOne // 1 + 2⁻⁵²
|
||||
let b = 1.0 - .ulpOfOne // 1 - 2⁻⁵²
|
||||
let c = a * b // 1 - 2⁻¹⁰⁴ before rounding, rounds to 1.0
|
||||
```
|
||||
|
||||
Sometimes it is necessary to preserve some or all of those low-order bits;
|
||||
maybe a subsequent subtraction cancels most of the high-order bits, and so
|
||||
the low-order part of the product suddenly becomes significant:
|
||||
|
||||
```swift
|
||||
let result = 1 - c // exactly zero, but "should be" 2⁻¹⁰⁴
|
||||
```
|
||||
|
||||
Augmented arithmetic is a building-block that library writers can use to
|
||||
handle cases like this more carefully. For the example above, one might
|
||||
compute:
|
||||
|
||||
```swift
|
||||
let (head, tail) = Augmented.product(a,b)
|
||||
```
|
||||
|
||||
`head` is then 1.0 and `tail` is -2⁻¹⁰⁴, so no information has been lost.
|
||||
Of course, the result is now split across two Doubles instead of one, but the
|
||||
information in `tail` can be carried forward into future computations.
|
||||
@@ -1,68 +0,0 @@
|
||||
# ``ElementaryFunctions``
|
||||
|
||||
A type that has elementary functions (`sin`, `cos`, etc.) available.
|
||||
|
||||
## Overview
|
||||
|
||||
An ["elementary function"][elfn] is a function built up from powers, roots,
|
||||
exponentials, logarithms, trigonometric functions (sin, cos, tan) and
|
||||
their inverses, and the hyperbolic functions (sinh, cosh, tanh) and their
|
||||
inverses.
|
||||
|
||||
Conformance to this protocol means that all of these building blocks are
|
||||
available as static functions on the type.
|
||||
|
||||
```swift
|
||||
let x: Float = 1
|
||||
let y = Float.sin(x) // 0.84147096
|
||||
```
|
||||
|
||||
`ElementaryFunctions` conformance implies `AdditiveArithmetic`, so addition
|
||||
and subtraction and the `zero` property are also available.
|
||||
|
||||
``RealFunctions`` refines this protocol and adds additional functions that
|
||||
are primarily used with real numbers, such as ``RealFunctions/atan2(y:x:)``
|
||||
and ``RealFunctions/exp10(_:)``.
|
||||
|
||||
``Real`` conforms to `RealFunctions` and `FloatingPoint`, and is the
|
||||
protocol that you will use most often for generic code.
|
||||
|
||||
## Topics
|
||||
|
||||
There are a few families of functions defined by `ElementaryFunctions`:
|
||||
|
||||
### Exponential functions
|
||||
- ``exp(_:)``
|
||||
- ``expMinusOne(_:)``
|
||||
|
||||
### Logarithmetic functions
|
||||
- ``log(_:)``
|
||||
- ``log(onePlus:)``
|
||||
|
||||
### Power and root functions:
|
||||
- ``pow(_:_:)-9imp6``
|
||||
- ``pow(_:_:)-2qmul``
|
||||
- ``sqrt(_:)``
|
||||
- ``root(_:_:)``
|
||||
|
||||
### Trigonometric functions
|
||||
- ``cos(_:)``
|
||||
- ``sin(_:)``
|
||||
- ``tan(_:)``
|
||||
|
||||
### Inverse trigonometric functions
|
||||
- ``acos(_:)``
|
||||
- ``asin(_:)``
|
||||
- ``atan(_:)``
|
||||
|
||||
### Hyperbolic functions
|
||||
- ``cosh(_:)``
|
||||
- ``sinh(_:)``
|
||||
- ``tanh(_:)``
|
||||
|
||||
### Inverse hyperbolic functions
|
||||
- ``acosh(_:)``
|
||||
- ``asinh(_:)``
|
||||
- ``atanh(_:)``
|
||||
|
||||
[elfn]: http://en.wikipedia.org/wiki/Elementary_function
|
||||
@@ -1,27 +0,0 @@
|
||||
# ``RealFunctions``
|
||||
|
||||
A type that extends ``ElementaryFunctions`` with additional operations that
|
||||
are primarily used with real numbers.
|
||||
|
||||
## Topics
|
||||
|
||||
### Exponential functions
|
||||
- ``exp2(_:)``
|
||||
- ``exp10(_:)``
|
||||
|
||||
### Logarithmetic functions
|
||||
- ``log2(_:)``
|
||||
- ``log10(_:)``
|
||||
|
||||
### Plane geometry
|
||||
- ``atan2(y:x:)``
|
||||
- ``hypot(_:_:)``
|
||||
|
||||
### Gamma function
|
||||
- ``gamma(_:)``
|
||||
- ``logGamma(_:)``
|
||||
- ``signGamma(_:)``
|
||||
|
||||
### Error function
|
||||
- ``erf(_:)``
|
||||
- ``erfc(_:)``
|
||||
@@ -1,28 +0,0 @@
|
||||
# ``RealModule``
|
||||
|
||||
Extensions on the Swift standard library that provide functionality for
|
||||
floating-point types.
|
||||
|
||||
## Overview
|
||||
|
||||
``RealModule`` provides four protocols that extend the standard library's
|
||||
numeric protocol hierarchy: AlgebraicField, ElementaryFunctions,
|
||||
RealFunctions, and Real.
|
||||
|
||||
Types conforming to AlgebraicField represent
|
||||
[fields](https://en.wikipedia.org/wiki/Field_(mathematics)). These are the
|
||||
mathematical structures that typically form the elements of vectors and
|
||||
matrices, so this protocol is appropriate for writing generic code to do
|
||||
linear-algebra-type operations.
|
||||
|
||||
ElementaryFunctions provides bindings for the "math functions": the logarithm
|
||||
and exponential functions, sine, cosine and tangent as well as their inverses,
|
||||
and other functions that you may be familiar with from trigonometry and
|
||||
calculus. RealFunctions refines ElementaryFunctions and provides functions that
|
||||
are primarily used with the real numbers, such as atan2, erf and gamma, and
|
||||
the base-2 and -10 logarithm and exponential funtions.
|
||||
|
||||
The Real protocol is a convenient name for the intersection of `FloatingPoint`,
|
||||
`RealFunctions`, and `AlgebraicField`; this is the protocol that you are most
|
||||
likely to want to constrain to when writing generic "math" code that works
|
||||
with floating-point types.
|
||||
@@ -1,53 +0,0 @@
|
||||
# ``Relaxed``
|
||||
|
||||
A namespace for a family of operations that "relax" the usual rules for
|
||||
floating-point to allow reassociation of arithmetic and FMA formation.
|
||||
|
||||
## Overview
|
||||
|
||||
Because of rounding, and the arithmetic rules for infinity and NaN values,
|
||||
floating-point addition and multiplication are not associative:
|
||||
|
||||
```swift
|
||||
let ε = Double.leastNormalMagnitude
|
||||
let sumLeft = (-1 + 1) + ε // 0 + ε = ε
|
||||
let sumRight = -1 + (1 + ε) // -1 + 1 = 0
|
||||
|
||||
let ∞ = Double.infinity
|
||||
let productLeft = (ε * ε) * ∞ // 0 * ∞ = .nan
|
||||
let productRight = ε * (ε * ∞) // ε * ∞ = ∞
|
||||
```
|
||||
|
||||
For some algorithms, the distinction between these results is incidental; for
|
||||
some others it is critical to their correct function. Because of this,
|
||||
compilers cannot freely change the order of reductions, which prevents some
|
||||
important optimizations: extraction of instruction-level parallelism and
|
||||
vectorization.
|
||||
|
||||
If you know that you are in a case where the order of elements being summed
|
||||
or multiplied is incidental, the Relaxed operations give you a mechanism
|
||||
to communicate that to the compiler and unlock these optimizations. For
|
||||
example, consider the following two functions:
|
||||
|
||||
```swift
|
||||
func sum(array: [Float]) -> Float {
|
||||
array.reduce(0, +)
|
||||
}
|
||||
|
||||
func relaxedSum(array: [Float]) -> Float {
|
||||
array.reduce(0, Relaxed.sum)
|
||||
}
|
||||
```
|
||||
|
||||
when called on an array with 1000 elements in a Release build, `relaxedSum`
|
||||
is about 8x faster than `sum` on Apple M2, with a similar speedup on Intel
|
||||
processors, without the need for any unsafe code or flags.
|
||||
|
||||
### multiplyAdd
|
||||
|
||||
In addition to `sum` and `product`, `Relaxed` provides the
|
||||
``multiplyAdd(_:_:_:)`` operation, which communciates to the compiler that
|
||||
it is allowed to replace separate multiply and add operations with a single
|
||||
_fused multiply-add_ instruction if its cost model indicates that it would
|
||||
be advantageous to do so. When targeting processors that support this
|
||||
instruction, this may be a significant performance advantage.
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// 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
|
||||
|
||||
@@ -2,19 +2,62 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A type that has elementary functions available.
|
||||
///
|
||||
/// An ["elementary function"][elfn] is a function built up from powers, roots,
|
||||
/// exponentials, logarithms, trigonometric functions (sin, cos, tan) and
|
||||
/// their inverses, and the hyperbolic functions (sinh, cosh, tanh) and their
|
||||
/// inverses.
|
||||
///
|
||||
/// Conformance to this protocol means that all of these building blocks are
|
||||
/// available as static functions on the type.
|
||||
///
|
||||
/// ```swift
|
||||
/// let x: Float = 1
|
||||
/// let y = Float.sin(x) // 0.84147096
|
||||
/// ```
|
||||
///
|
||||
/// There are three broad families of functions defined by
|
||||
/// `ElementaryFunctions`:
|
||||
/// - Exponential, trigonometric, and hyperbolic functions:
|
||||
/// `exp`, `expMinusOne`, `cos`, `sin`, `tan`, `cosh`, `sinh`, and `tanh`.
|
||||
/// - Logarithmic, inverse trigonometric, and inverse hyperbolic functions:
|
||||
/// `log`, `log(onePlus:)`, `acos`, `asin`, `atan`, `acosh`, `asinh`, and
|
||||
/// `atanh`.
|
||||
/// - Power and root functions:
|
||||
/// `pow`, `sqrt`, and `root`.
|
||||
///
|
||||
/// `ElementaryFunctions` conformance implies `AdditiveArithmetic`, so addition
|
||||
/// and subtraction and the `.zero` property are also available.
|
||||
///
|
||||
/// There are two other protocols that you are more likely to want to use
|
||||
/// directly:
|
||||
///
|
||||
/// `RealFunctions` refines `ElementaryFunctions` and includes
|
||||
/// additional functions specific to real number types.
|
||||
///
|
||||
/// `Real` conforms to `RealFunctions` and `FloatingPoint`, and is the
|
||||
/// protocol that you will want to use most often for generic code.
|
||||
///
|
||||
/// See Also:
|
||||
///
|
||||
/// - `RealFunctions`
|
||||
/// - `Real`
|
||||
///
|
||||
/// [elfn]: http://en.wikipedia.org/wiki/Elementary_function
|
||||
public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
/// The [exponential function][wiki] e^x whose base `e` is the base of the
|
||||
/// natural logarithm.
|
||||
///
|
||||
/// For types that conform to ``RealFunctions`` see
|
||||
/// ``RealFunctions/exp2(_:)`` and ``RealFunctions/exp10(_:)``.
|
||||
/// See also `expMinusOne()`, as well as `exp2()` and `exp10()`
|
||||
/// defined for types conforming to `RealFunctions`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Exponential_function
|
||||
static func exp(_ x: Self) -> Self
|
||||
@@ -25,7 +68,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
/// catastrophic cancellation and the result will not have full accuracy.
|
||||
/// The `.expMinusOne(x)` function gives you a means to address this problem.
|
||||
///
|
||||
/// As an example, consider the expression `(x + 1) * .exp(x) - 1`. When `x`
|
||||
/// As an example, consider the expression `(x + 1)*exp(x) - 1`. When `x`
|
||||
/// is smaller than `.ulpOfOne`, this expression evaluates to `0.0`, when it
|
||||
/// should actually round to `2*x`. We can get a full-accuracy result by
|
||||
/// using the following instead:
|
||||
@@ -36,8 +79,8 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
/// This re-written expression delivers an accurate result for all values
|
||||
/// of `x`, not just for small values.
|
||||
///
|
||||
/// For types that conform to ``RealFunctions`` see
|
||||
/// ``RealFunctions/exp2(_:)`` and ``RealFunctions/exp10(_:)``.
|
||||
/// See also `exp()`, as well as `exp2()` and `exp10()` defined for types
|
||||
/// conforming to `RealFunctions`.
|
||||
static func expMinusOne(_ x: Self) -> Self
|
||||
|
||||
/// The [hyperbolic cosine][wiki] of `x`.
|
||||
@@ -47,7 +90,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
/// 2
|
||||
/// ```
|
||||
///
|
||||
/// See also ``acosh(_:)``.
|
||||
/// See also `sinh()`, `tanh()` and `acosh()`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
|
||||
static func cosh(_ x: Self) -> Self
|
||||
@@ -59,7 +102,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
/// 2
|
||||
/// ```
|
||||
///
|
||||
/// See also ``asinh(_:)``.
|
||||
/// See also `cosh()`, `tanh()` and `asinh()`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
|
||||
static func sinh(_ x: Self) -> Self
|
||||
@@ -71,7 +114,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
/// cosh(x)
|
||||
/// ```
|
||||
///
|
||||
/// See also ``atanh(_:)``.
|
||||
/// See also `cosh()`, `sinh()` and `atanh()`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
|
||||
static func tanh(_ x: Self) -> Self
|
||||
@@ -80,7 +123,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
///
|
||||
/// For real types, `x` may be interpreted as an angle measured in radians.
|
||||
///
|
||||
/// See also ``acos(_:)``.
|
||||
/// See also `sin()`, `tan()` and `acos()`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Cosine
|
||||
static func cos(_ x: Self) -> Self
|
||||
@@ -90,7 +133,7 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
///
|
||||
/// For real types, `x` may be interpreted as an angle measured in radians.
|
||||
///
|
||||
/// See also ``asin(_:)``.
|
||||
/// See also `cos()`, `tan()` and `asin()`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Sine
|
||||
static func sin(_ x: Self) -> Self
|
||||
@@ -99,54 +142,49 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
///
|
||||
/// For real types, `x` may be interpreted as an angle measured in radians.
|
||||
///
|
||||
/// See also ``atan(_:)``.
|
||||
/// See also `cos()`, `sin()` and `atan()`, as well as `atan2(y:x:)` for
|
||||
/// types that conform to `RealFunctions`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Tangent
|
||||
static func tan(_ x: Self) -> Self
|
||||
|
||||
/// The [natural logarithm][wiki] of `x`.
|
||||
///
|
||||
/// For types that conform to ``RealFunctions`` see also
|
||||
/// ``RealFunctions/log2(_:)`` and ``RealFunctions/log10(_:)``.
|
||||
/// See also `log(onePlus:)`, as well as `log2()` and `log10()` for types
|
||||
/// that conform to `RealFunctions`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Logarithm
|
||||
static func log(_ x: Self) -> Self
|
||||
|
||||
/// log(1 + x), computed in such a way as to maintain accuracy for small x.
|
||||
///
|
||||
/// For types that conform to ``RealFunctions`` see also
|
||||
/// ``RealFunctions/log2(_:)`` and ``RealFunctions/log10(_:)``.
|
||||
/// See also `log()`, as well as `log2()` and `log10()` for types
|
||||
/// that conform to `RealFunctions`.
|
||||
static func log(onePlus x: Self) -> Self
|
||||
|
||||
/// The [inverse hyperbolic cosine][wiki] of `x`.
|
||||
///
|
||||
/// ```
|
||||
/// cosh(acosh(x)) ≅ x
|
||||
/// ```
|
||||
///
|
||||
/// See also ``cosh(_:)``.
|
||||
/// See also `asinh()`, `atanh()` and `cosh()`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
|
||||
static func acosh(_ x: Self) -> Self
|
||||
|
||||
/// The [inverse hyperbolic sine][wiki] of `x`.
|
||||
///
|
||||
/// ```
|
||||
/// sinh(asinh(x)) ≅ x
|
||||
/// ```
|
||||
///
|
||||
/// See also ``sinh(_:)``.
|
||||
/// See also `acosh()`, `atanh()` and `sinh()`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
|
||||
static func asinh(_ x: Self) -> Self
|
||||
|
||||
/// The [inverse hyperbolic tangent][wiki] of `x`.
|
||||
///
|
||||
/// ```
|
||||
/// tanh(atanh(x)) ≅ x
|
||||
/// ```
|
||||
///
|
||||
/// See also ``tanh(_:)``.
|
||||
/// See also `acosh()`, `asinh()` and `tanh()`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
|
||||
static func atanh(_ x: Self) -> Self
|
||||
@@ -155,12 +193,10 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
///
|
||||
/// For real types, the result may be interpreted as an angle measured in
|
||||
/// radians.
|
||||
///
|
||||
/// ```
|
||||
/// cos(acos(x)) ≅ x
|
||||
/// ```
|
||||
///
|
||||
/// See also ``cos(_:)``.
|
||||
/// See also `asin()`, `atan()` and `cos()`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
|
||||
static func acos(_ x: Self) -> Self
|
||||
@@ -169,12 +205,10 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
///
|
||||
/// For real types, the result may be interpreted as an angle measured in
|
||||
/// radians.
|
||||
///
|
||||
/// ```
|
||||
/// sin(asin(x)) ≅ x
|
||||
/// ```
|
||||
///
|
||||
/// See also ``sin(_:)``.
|
||||
/// See also `acos()`, `atan()` and `sin()`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
|
||||
static func asin(_ x: Self) -> Self
|
||||
@@ -183,14 +217,11 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
///
|
||||
/// For real types, the result may be interpreted as an angle measured in
|
||||
/// radians.
|
||||
///
|
||||
/// ```
|
||||
/// tan(atan(x)) ≅ x
|
||||
/// ```
|
||||
///
|
||||
/// See also ``tan(_:)``.
|
||||
/// For types that conform to ``RealFunctions``, you will sometimes want
|
||||
/// to use ``RealFunctions/atan2(y:x:)`` instead.
|
||||
/// See also `acos()`, `asin()` and `tan()`, as well as `atan2(y:x:)` for
|
||||
/// types that conform to `RealArithmetic`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
|
||||
static func atan(_ x: Self) -> Self
|
||||
@@ -202,9 +233,10 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
/// In particular, this means that if `x` and `y` are both zero, `pow(x,y)`
|
||||
/// is `nan` for real types and `infinity` for complex types, rather than 1.
|
||||
///
|
||||
/// There is also
|
||||
/// <doc:/documentation/RealModule/ElementaryFunctions/pow(_:_:)-9imp6>,
|
||||
/// whose behavior is defined in terms of repeated multiplication.
|
||||
/// There is also a `pow(_:Self,_:Int)` overload, whose behavior is defined
|
||||
/// in terms of repeated multiplication, and hence returns 1 for this case.
|
||||
///
|
||||
/// See also `sqrt()` and `root()`.
|
||||
static func pow(_ x: Self, _ y: Self) -> Self
|
||||
|
||||
/// `x` raised to the nth power.
|
||||
@@ -212,13 +244,19 @@ public protocol ElementaryFunctions: AdditiveArithmetic {
|
||||
/// The edge-cases of this function are defined in terms of repeated
|
||||
/// multiplication or division, rather than exp(n log x). In particular,
|
||||
/// `Float.pow(0, 0)` is 1.
|
||||
///
|
||||
/// See also `sqrt()` and `root()`.
|
||||
static func pow(_ x: Self, _ n: Int) -> Self
|
||||
|
||||
/// The [square root][wiki] of `x`.
|
||||
///
|
||||
/// See also `pow()` and `root()`.
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Square_root
|
||||
static func sqrt(_ x: Self) -> Self
|
||||
|
||||
/// The nth root of `x`.
|
||||
///
|
||||
/// See also `pow()` and `sqrt()`.
|
||||
static func root(_ x: Self, _ n: Int) -> Self
|
||||
}
|
||||
@@ -173,10 +173,9 @@ extension Float16: Real {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !arch(wasm32)
|
||||
// WASM doesn't have _Float16 on the C side, so we can't define the C hooks
|
||||
// that these use. TODO: implement these as Swift builtins instead.
|
||||
|
||||
// TODO: once clang stabilizes the calling conventions for _Float16 on Intel,
|
||||
// we can re-enable these; presently the type is disabled on the target.
|
||||
#if !(arch(i386) || arch(x86_64))
|
||||
@_transparent
|
||||
public static func _relaxedAdd(_ a: Float16, _ b: Float16) -> Float16 {
|
||||
_numerics_relaxed_addf16(a, b)
|
||||
|
||||
@@ -73,5 +73,5 @@ Not having this protocol is a significant missing feature for numerical computin
|
||||
|
||||
[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
|
||||
[SE-0246]: https://github.com/apple/swift-evolution/blob/master/proposals/0246-mathable.md
|
||||
[Sigmoid]: https://en.wikipedia.org/wiki/Sigmoid_function
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// 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
|
||||
@@ -24,24 +24,23 @@
|
||||
/// }
|
||||
/// ```
|
||||
/// See also `ElementaryFunctions`, `RealFunctions` and `AlgebraicField`.
|
||||
public protocol Real: FloatingPoint, RealFunctions, AlgebraicField { }
|
||||
public protocol Real: FloatingPoint, RealFunctions, AlgebraicField {
|
||||
}
|
||||
|
||||
// While `Real` does not provide any additional customization points,
|
||||
// it does allow us to default the implementation of a few operations,
|
||||
// and also provides `signGamma`.
|
||||
extension Real {
|
||||
// Most math libraries do not provide exp10, so we need a default
|
||||
// implementation. This is not a great one (if the underlying math
|
||||
// library does not have a sub-ulp accurate pow, this will not get
|
||||
// exact powers of ten right), but suffices in the short term.
|
||||
// implementation.
|
||||
@_transparent
|
||||
public static func exp10(_ x: Self) -> Self {
|
||||
pow(10, x)
|
||||
return pow(10, x)
|
||||
}
|
||||
|
||||
/// cos(x) - 1, computed in such a way as to maintain accuracy for small x.
|
||||
///
|
||||
/// See also ``ElementaryFunctions/expMinusOne(_:)``.
|
||||
/// See also `ElementaryFunctions.expMinusOne()`.
|
||||
@_transparent
|
||||
public static func cosMinusOne(_ x: Self) -> Self {
|
||||
let sinxOver2 = sin(x/2)
|
||||
@@ -91,7 +90,7 @@ extension Real {
|
||||
|
||||
@_transparent
|
||||
public static func sqrt(_ x: Self) -> Self {
|
||||
x.squareRoot()
|
||||
return x.squareRoot()
|
||||
}
|
||||
|
||||
/// The (approximate) reciprocal (multiplicative inverse) of this number,
|
||||
@@ -129,13 +128,13 @@ extension Real {
|
||||
/// the real reciprocal (when it exists) as follows (I will use circle
|
||||
/// operators to denote real-number arithmetic, and normal operators
|
||||
/// for floating-point arithmetic):
|
||||
/// ```
|
||||
/// a * b.reciprocal! = a * (1/b)
|
||||
/// = a * (1 ⊘ b)(1 + δ₁)
|
||||
/// = (a ⊘ b)(1 + δ₁)(1 + δ₂)
|
||||
/// = (a ⊘ b)(1 + δ₁ + δ₂ + δ₁δ₂)
|
||||
/// ```
|
||||
/// where `0 < δᵢ <= ulpOfOne/2`. This gives a roughly 1-ulp error,
|
||||
///
|
||||
/// a * b.reciprocal! = a * (1/b)
|
||||
/// = a * (1 ⊘ b)(1 + δ₁)
|
||||
/// = (a ⊘ b)(1 + δ₁)(1 + δ₂)
|
||||
/// = (a ⊘ b)(1 + δ₁ + δ₂ + δ₁δ₂)
|
||||
///
|
||||
/// where 0 < δᵢ <= ulpOfOne/2. This gives a roughly 1-ulp error,
|
||||
/// about twice the error bound we get using division. For most
|
||||
/// purposes this is an acceptable error, but if you need to match
|
||||
/// results obtained using division, you should not use this.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// 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
|
||||
@@ -10,89 +10,70 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
public protocol RealFunctions: ElementaryFunctions {
|
||||
/// The signed angle formed in the plane between the vector `(x,y)` and the
|
||||
/// positive real axis, measured in radians.
|
||||
/// `atan(y/x)`, with sign selected according to the quadrant of `(x, y)`.
|
||||
///
|
||||
/// The result is in the interval `[-π, π]`.
|
||||
///
|
||||
/// The argument order to `atan2` may be surprising to new programmers.
|
||||
/// The convention of `y` being the first argument goes back at least to
|
||||
/// Fortran IV in 1961 and is generally followed in computing with a few
|
||||
/// notable exceptions (e.g. Mathematica and Excel). This convention was
|
||||
/// originally chosen because of the mathematical definition of the
|
||||
/// function:
|
||||
///
|
||||
/// ```
|
||||
/// atan2(y,x) = atan(y/x) if x > 0
|
||||
/// ```
|
||||
///
|
||||
/// See also ``ElementaryFunctions/atan(_:)``, as well as the `phase` and
|
||||
/// `polar` properties defined on the `Complex` type.
|
||||
/// See also `atan()`.
|
||||
static func atan2(y: Self, x: Self) -> Self
|
||||
|
||||
/// The [error function](https://en.wikipedia.org/wiki/Error_function)
|
||||
/// evaluated at `x`.
|
||||
/// The error function evaluated at `x`.
|
||||
///
|
||||
/// See also `erfc()`.
|
||||
static func erf(_ x: Self) -> Self
|
||||
|
||||
/// The complimentary [error function](https://en.wikipedia.org/wiki/Error_function)
|
||||
/// evaluated at `x`.
|
||||
/// The complimentary error function evaluated at `x`.
|
||||
///
|
||||
/// See also `erf()`.
|
||||
static func erfc(_ x: Self) -> Self
|
||||
|
||||
/// 2 raised to the power x.
|
||||
/// 2^x
|
||||
///
|
||||
/// See also ``log2(_:)``, ``ElementaryFunctions/exp(_:)``,
|
||||
/// ``ElementaryFunctions/expMinusOne(_:)``
|
||||
/// and ``ElementaryFunctions/pow(_:_:)-2qmul``.
|
||||
/// See also `exp()`, `expMinusOne()`, `exp10()`, `log2()` and `pow()`.
|
||||
static func exp2(_ x: Self) -> Self
|
||||
|
||||
/// 10 raised to the power x.
|
||||
/// 10^x
|
||||
///
|
||||
/// See also ``log10(_:)``, ``ElementaryFunctions/exp(_:)``,
|
||||
/// ``ElementaryFunctions/expMinusOne(_:)``
|
||||
/// and ``ElementaryFunctions/pow(_:_:)-2qmul``.
|
||||
/// See also `exp()`, `expMinusOne()`, `exp2()`, `log10()` and `pow()`.
|
||||
static func exp10(_ x: Self) -> Self
|
||||
|
||||
/// The length of the vector `(x,y)`, computed in a manner that avoids
|
||||
/// spurious overflow or underflow.
|
||||
///
|
||||
/// See also the `length` and `polar` properties defined on the `Complex`
|
||||
/// type.
|
||||
/// `sqrt(x*x + y*y)`, computed in a manner that avoids spurious overflow or
|
||||
/// underflow.
|
||||
static func hypot(_ x: Self, _ y: Self) -> Self
|
||||
|
||||
/// The [gamma function](https://en.wikipedia.org/wiki/Gamma_function) Γ(x).
|
||||
/// The gamma function Γ(x).
|
||||
///
|
||||
/// See also `logGamma()` and `signGamma()`.
|
||||
static func gamma(_ x: Self) -> Self
|
||||
|
||||
/// The base-2 logarithm of `x`.
|
||||
///
|
||||
/// See also ``exp2(_:)``, ``ElementaryFunctions/log(_:)``,
|
||||
/// and ``ElementaryFunctions/log(onePlus:)``.
|
||||
/// See also `exp2()`, `log()`, `log(onePlus:)` and `log10()`.
|
||||
static func log2(_ x: Self) -> Self
|
||||
|
||||
/// The base-10 logarithm of `x`.
|
||||
///
|
||||
/// See also ``exp10(_:)``, ``ElementaryFunctions/log(_:)``,
|
||||
/// and ``ElementaryFunctions/log(onePlus:)``.
|
||||
/// See also: `exp10()`, `log()`, `log(onePlus:)` and `log2()`.
|
||||
static func log10(_ x: Self) -> Self
|
||||
|
||||
#if !os(Windows)
|
||||
/// The logarithm of the absolute value of the
|
||||
/// [gamma function](https://en.wikipedia.org/wiki/Gamma_function),
|
||||
/// log(|Γ(x)|).
|
||||
/// The logarithm of the absolute value of the gamma function, log(|Γ(x)|).
|
||||
///
|
||||
/// Not available on Windows targets.
|
||||
///
|
||||
/// See also `gamma()` and `signGamma()`.
|
||||
static func logGamma(_ x: Self) -> Self
|
||||
|
||||
/// The sign of the
|
||||
/// [gamma function](https://en.wikipedia.org/wiki/Gamma_function), Γ(x).
|
||||
/// The sign of the gamma function, Γ(x).
|
||||
///
|
||||
/// For `x >= 0`, `signGamma(x)` is `.plus`. For negative `x`, `signGamma(x)`
|
||||
/// is `.plus` when `x` is an integer, and otherwise it is `.minus` whenever
|
||||
/// `trunc(x)` is even, and `.plus` when `trunc(x)` is odd.
|
||||
///
|
||||
/// This function is used together with ``logGamma(_:)``, which computes the
|
||||
/// This function is used together with `logGamma`, which computes the
|
||||
/// logarithm of the absolute value of Γ(x), to recover the sign information.
|
||||
///
|
||||
/// Not available on Windows targets.
|
||||
///
|
||||
/// See also `gamma()` and `logGamma()`.
|
||||
static func signGamma(_ x: Self) -> FloatingPointSign
|
||||
#endif
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2021-2025 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -11,11 +11,12 @@
|
||||
|
||||
import _NumericsShims
|
||||
|
||||
/// A namespace for "relaxed arithmetic" operations for types conforming to
|
||||
/// `AlgebraicField`.
|
||||
public enum Relaxed { }
|
||||
|
||||
extension Relaxed {
|
||||
/// a+b, but grants the optimizer permission to reassociate expressions
|
||||
/// and form FMAs.
|
||||
/// a+b with the optimizer licensed to reassociate expressions and form FMAs.
|
||||
///
|
||||
/// Floating-point addition is not an associative operation, so the Swift
|
||||
/// compiler does not have any flexibility in how it evaluates an expression
|
||||
@@ -44,8 +45,7 @@ extension Relaxed {
|
||||
T._relaxedAdd(a, b)
|
||||
}
|
||||
|
||||
/// a*b, but grants the optimizer permission to reassociate expressions
|
||||
/// and form FMAs.
|
||||
/// a*b with the optimizer licensed to reassociate expressions and form FMAs.
|
||||
///
|
||||
/// Floating-point addition and multiplication are not associative operations,
|
||||
/// so the Swift compiler does not have any flexibility in how it evaluates
|
||||
|
||||
@@ -9,10 +9,6 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define HEADER_SHIM static inline __attribute__((__always_inline__))
|
||||
|
||||
// This header uses most of the libm functions, but we don't want to end up
|
||||
@@ -389,7 +385,7 @@ HEADER_SHIM long double libm_lgammal(long double x, int *signp) {
|
||||
// MARK: - math inlines with relaxed semantics to support optimization.
|
||||
#define CLANG_RELAX_FP _Pragma("clang fp reassociate(on) contract(fast)")
|
||||
|
||||
#if !defined __wasm__ // No _Float16 on wasm
|
||||
#if !(__i386__ || __x86_64__)
|
||||
/// a + b with the "allow reassociation" and "allow FMA formation" flags
|
||||
/// set in the IR.
|
||||
HEADER_SHIM _Float16 _numerics_relaxed_addf16(_Float16 a, _Float16 b) {
|
||||
@@ -454,7 +450,3 @@ HEADER_SHIM void _numerics_optimization_barrier(const void *pointer) {
|
||||
}
|
||||
|
||||
#undef CLANG_RELAX_FP
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2017-2024 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2017-2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -281,11 +281,17 @@ extension DoubleWidth : FixedWidthInteger {
|
||||
by rhs: DoubleWidth
|
||||
) -> (partialValue: DoubleWidth, overflow: Bool) {
|
||||
let (carry, product) = multipliedFullWidth(by: rhs)
|
||||
let partialValue = DoubleWidth(truncatingIfNeeded: product)
|
||||
// Overflow has occured if carry is not just the sign-extension of
|
||||
// partialValue (which is zero when Base is unsigned).
|
||||
let overflow = carry != (partialValue >> DoubleWidth.bitWidth)
|
||||
return (partialValue, overflow)
|
||||
let result = DoubleWidth(truncatingIfNeeded: product)
|
||||
|
||||
let isNegative = DoubleWidth.isSigned &&
|
||||
(self < (0 as DoubleWidth)) != (rhs < (0 as DoubleWidth))
|
||||
let didCarry = isNegative
|
||||
? carry != ~(0 as DoubleWidth)
|
||||
: carry != (0 as DoubleWidth)
|
||||
let hadPositiveOverflow =
|
||||
DoubleWidth.isSigned && !isNegative && product.leadingZeroBitCount == 0
|
||||
|
||||
return (result, didCarry || hadPositiveOverflow)
|
||||
}
|
||||
|
||||
public func quotientAndRemainder(
|
||||
@@ -325,11 +331,7 @@ extension DoubleWidth : FixedWidthInteger {
|
||||
if DoubleWidth.isSigned && other == -1 && self == .min { return (0, true) }
|
||||
return (quotientAndRemainder(dividingBy: other).remainder, false)
|
||||
}
|
||||
|
||||
// When using a pre-Swift 6.0 runtime, `&*` is not a protocol requirement of
|
||||
// FixedWidthInteger, which results in the default implementation of this
|
||||
// operation ending up recursively calling itself forever. In order to avoid
|
||||
// this, we keep the concrete implementation around.
|
||||
|
||||
public func multipliedFullWidth(
|
||||
by other: DoubleWidth
|
||||
) -> (high: DoubleWidth, low: DoubleWidth.Magnitude) {
|
||||
@@ -451,21 +453,18 @@ extension DoubleWidth : FixedWidthInteger {
|
||||
|
||||
/// Returns this value "masked" by its bit width.
|
||||
///
|
||||
/// "Masking" notionally involves repeatedly incrementing or decrementing
|
||||
/// this value by `self.bitWidth` until the result is contained in the
|
||||
/// range `0..<self.bitWidth`.
|
||||
/// "Masking" notionally involves repeatedly incrementing or decrementing this
|
||||
/// value by `self.bitWidth` until the result is contained in the range
|
||||
/// `0..<self.bitWidth`.
|
||||
internal func _masked() -> DoubleWidth {
|
||||
let bits = DoubleWidth(DoubleWidth.bitWidth)
|
||||
// FIXME(integers): test types with bit widths that aren't powers of 2
|
||||
if DoubleWidth.bitWidth.nonzeroBitCount == 1 {
|
||||
return self & (bits &- 1)
|
||||
return self & DoubleWidth(DoubleWidth.bitWidth &- 1)
|
||||
}
|
||||
let reduced = self % bits
|
||||
// bitWidth is always positive, but the value being reduced might have
|
||||
// been negative, in which case reduced will also be negative. We need
|
||||
// the representative in [0, bitWidth), so conditionally add the count
|
||||
// to get the positive residue.
|
||||
if Base.isSigned && reduced < 0 { return reduced &+ bits }
|
||||
return reduced
|
||||
if DoubleWidth.isSigned && self._storage.high < (0 as High) {
|
||||
return self % DoubleWidth(DoubleWidth.bitWidth) + self
|
||||
}
|
||||
return self % DoubleWidth(DoubleWidth.bitWidth)
|
||||
}
|
||||
|
||||
public static func &<<=(lhs: inout DoubleWidth, rhs: DoubleWidth) {
|
||||
@@ -591,31 +590,6 @@ extension DoubleWidth : FixedWidthInteger {
|
||||
precondition(!overflow, "Overflow in %=")
|
||||
lhs = result
|
||||
}
|
||||
|
||||
public static func &+(
|
||||
lhs: DoubleWidth, rhs: DoubleWidth
|
||||
) -> DoubleWidth {
|
||||
let (low, carry) = lhs.low.addingReportingOverflow(rhs.low)
|
||||
let high = lhs.high &+ rhs.high &+ (carry ? 1 : 0)
|
||||
return DoubleWidth(high, low)
|
||||
}
|
||||
|
||||
public static func &-(
|
||||
lhs: DoubleWidth, rhs: DoubleWidth
|
||||
) -> DoubleWidth {
|
||||
let (low, borrow) = lhs.low.subtractingReportingOverflow(rhs.low)
|
||||
let high = lhs.high &- rhs.high &- (borrow ? 1 : 0)
|
||||
return DoubleWidth(high, low)
|
||||
}
|
||||
|
||||
public static func &*(
|
||||
lhs: DoubleWidth, rhs: DoubleWidth
|
||||
) -> DoubleWidth {
|
||||
let p00 = lhs.low.multipliedFullWidth(by: rhs.low)
|
||||
let p10 = lhs.high &* Base(truncatingIfNeeded: rhs.low)
|
||||
let p01 = Base(truncatingIfNeeded: lhs.low) &* rhs.high
|
||||
return DoubleWidth(p10 &+ p01 &+ Base(truncatingIfNeeded: p00.high), p00.low)
|
||||
}
|
||||
|
||||
public init(_truncatingBits bits: UInt) {
|
||||
_storage.low = Low(_truncatingBits: bits)
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//===--- Error.swift ------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//===--- Interval.swift ---------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
//===--- BigIntTests.swift ------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import BigIntModule
|
||||
import XCTest
|
||||
|
||||
extension BigInt {
|
||||
|
||||
static func fac(_ n: BigInt) -> BigInt {
|
||||
precondition(n >= 0, "Factorial of a negative integer is undefined")
|
||||
return stride(from: n, to: 1, by: -1).reduce(into: 1, { $0 *= $1 })
|
||||
}
|
||||
|
||||
// inspired by https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms
|
||||
static func pow(_ lhs: BigInt, _ rhs: BigInt) -> BigInt {
|
||||
let bits_of_n = {
|
||||
(n: BigInt) -> [Int] in
|
||||
var bits: [Int] = []
|
||||
var n = n
|
||||
while n != 0 {
|
||||
bits.append(Int(n % 2))
|
||||
n /= 2
|
||||
}
|
||||
|
||||
return bits
|
||||
}
|
||||
|
||||
var r: BigInt = 1
|
||||
for bit in bits_of_n(rhs).reversed() {
|
||||
r *= r
|
||||
if bit == 1 {
|
||||
r *= lhs
|
||||
}
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
}
|
||||
|
||||
final class BigIntTests: XCTestCase {
|
||||
|
||||
/// Python: `bitWidth = 1024; -(2 ** (bitWidth - 1))`
|
||||
static let descriptionInt1024Min: String =
|
||||
"""
|
||||
-89884656743115795386465259539451236680898848947115328636715040578866337902\
|
||||
750481566354238661203768010560056939935696678829394884407208311246423715319\
|
||||
737062188883946712432742638151109800623047059726541476042502884419075341171\
|
||||
231440736956555270413618581675255342293149119973622969239858152417678164812\
|
||||
112068608
|
||||
"""
|
||||
|
||||
/// Python: `bitWidth = 1024; (2 ** (bitWidth - 1)) - 1`
|
||||
static let descriptionInt1024Max: String =
|
||||
"""
|
||||
89884656743115795386465259539451236680898848947115328636715040578866337902\
|
||||
750481566354238661203768010560056939935696678829394884407208311246423715319\
|
||||
737062188883946712432742638151109800623047059726541476042502884419075341171\
|
||||
231440736956555270413618581675255342293149119973622969239858152417678164812\
|
||||
112068607
|
||||
"""
|
||||
|
||||
/// Python: `numpy.base_repr(math.factorial(512), base=36)`
|
||||
static let descriptionFactorial512_radix36: String =
|
||||
"""
|
||||
7FA5Y7EHR9XHMQ519MBHGYOF8XDYMUX8OZHO9WF1KCM0SSPXV2V45UA73BAFRYM2PFB8CZLTODV\
|
||||
OS3QWA7PYFJ7WAFBI4VF371E27N6XZ4LGWHMFDS4ZH1O3DGNFG4YABUE1G90ORGRTIOGSQVZLSQ\
|
||||
4TKHKHIQ262JVQ0J6LSKAPN5I65AJD33XODVHRNWJ1VSO0Q2FBOUNCPGQG2SFQKR17XHF1OLTV2\
|
||||
MVNJVTDAIYWVJ9ZH7KXT0EPS00IGIVC7MNCU25HFWE37KNMSJQUL5ALUCE5XZVPFQCQGEVEB93B\
|
||||
GA8LKG67PVZ7Q9QMQKIVNIMPT2973MVDTD1D1A0A4QT6NBZYR0TGSZXBV1PD0CHW4SKZJSLBS4Z\
|
||||
W5WCKDY8BCQCE17KKADVLCTVSQL1BZ2PL52DDPB8S5L0ZEG2ZAZF9V4TNJJNO1D9U9JU7B264QZ\
|
||||
5GLHC3Q0Y3BTECGTI8GRENQ2FV4HSEZKPM9OG302KLSY9MBCSOO0FN229AST84TT87LYWOOS71C\
|
||||
54RPJ9RTO9875Z9DE3HPH89EW5I3SV219O04UU09A4KME7DD7IH49ABO79NR4EXFX1VLL4YOHSA\
|
||||
7AHD1LS5YKZ66F4UPG0RCBGG000000000000000000000000000000000000000000000000000\
|
||||
000000000000000000000000000000000000000000000000000000000000000000000000000
|
||||
"""
|
||||
|
||||
// MARK: - Basic arithmetic
|
||||
|
||||
func testDivision() {
|
||||
let num1 = BigInt("18446744073709551616")!
|
||||
let den1 = BigInt(123)
|
||||
let expected1 = BigInt(UInt64(149973529054549200))
|
||||
XCTAssertEqual(num1 / den1, expected1)
|
||||
|
||||
let num2 = BigInt.pow(BigInt(10), 100)
|
||||
let den2: BigInt = 3
|
||||
let expected2: BigInt = BigInt(String(repeating: "3", count: 100))!
|
||||
let actual2 = num2 / den2
|
||||
XCTAssertEqual(actual2, expected2)
|
||||
|
||||
let num3 = BigInt.pow(BigInt(10), 97)
|
||||
let den3: BigInt = BigInt("33333333333333333333")!
|
||||
let expected3: BigInt = BigInt("300000000000000000003000000000000000000030000000000000000000300000000000000000")!
|
||||
let actual3 = num3 / den3
|
||||
XCTAssertEqual(actual3, expected3)
|
||||
|
||||
let foo = BigInt("12345678901234567890123456789012345678901234567890123456789012345678901234567890")!
|
||||
let bar = BigInt("351235231535161613134135135135")!
|
||||
let baz = foo / bar
|
||||
XCTAssertEqual(baz, BigInt("35149318157164029153358504918339691272847595997760")!)
|
||||
|
||||
XCTAssertNotNil(BigInt(exactly: 2.4e39))
|
||||
XCTAssertNotNil(BigInt(exactly: 1e38))
|
||||
XCTAssertEqual(BigInt(2.4e39) / BigInt(1e38), BigInt(24))
|
||||
|
||||
for _ in 0 ..< 100 {
|
||||
let expected = BigInt(Float64.random(in: 0x1p64 ... 0x1p255))
|
||||
let divisor = BigInt(Float64.random(in: 0x1p64 ... 0x1p128))
|
||||
let (quotient, remainder) = expected.quotientAndRemainder(dividingBy: divisor)
|
||||
let actual = divisor * quotient + remainder
|
||||
XCTAssertEqual(quotient, expected / divisor)
|
||||
XCTAssertEqual(remainder, expected % divisor)
|
||||
XCTAssertEqual(
|
||||
actual, expected,
|
||||
"""
|
||||
## FAILURE ##
|
||||
~~~~~~~~~~~~~
|
||||
actual: \(actual)
|
||||
!= expected: \(expected)
|
||||
~~~~~~~~~~~~~
|
||||
divisor: \(divisor)
|
||||
* quotient: \(quotient)
|
||||
+ remainder: \(remainder)
|
||||
~~~~~~~~~~~~~
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func testFactorial() {
|
||||
var expectedNumber: BigInt?
|
||||
var actualNumber: BigInt!
|
||||
var actualString: String!
|
||||
|
||||
measure {
|
||||
expectedNumber = BigInt(Self.descriptionFactorial512_radix36, radix: 36)
|
||||
actualNumber = BigInt.fac(512)
|
||||
actualString = String(actualNumber, radix: 36, uppercase: true)
|
||||
}
|
||||
|
||||
XCTAssertEqual(actualNumber, expectedNumber)
|
||||
XCTAssertEqual(actualString, Self.descriptionFactorial512_radix36)
|
||||
|
||||
XCTAssertEqual(BigInt.fac(0), 1)
|
||||
XCTAssertEqual(BigInt.fac(1), 1)
|
||||
XCTAssertEqual(BigInt.fac(2), 2)
|
||||
XCTAssertEqual(BigInt.fac(3), 6)
|
||||
XCTAssertEqual(BigInt.fac(4), 24)
|
||||
XCTAssertEqual(BigInt.fac(5), 120)
|
||||
XCTAssertEqual(BigInt.fac(6), 720)
|
||||
XCTAssertEqual(BigInt.fac(7), 5040)
|
||||
XCTAssertEqual(BigInt.fac(8), 40320)
|
||||
XCTAssertEqual(BigInt.fac(9), 362880)
|
||||
}
|
||||
|
||||
func testMath() {
|
||||
let foo = BigInt.pow(10, 20)
|
||||
let bar = BigInt("1234567890123456789012345678901234567890")!
|
||||
|
||||
let baz = foo + bar
|
||||
|
||||
XCTAssertEqual(baz, BigInt("1234567890123456789112345678901234567890")!)
|
||||
|
||||
let fooz = foo >> BigInt(10)
|
||||
XCTAssertEqual(fooz, foo / 1024)
|
||||
|
||||
let barz = BigInt(1) << 64
|
||||
XCTAssertEqual(barz, BigInt(UInt64.max) + 1)
|
||||
}
|
||||
|
||||
func testNegation() {
|
||||
let foo = BigInt("1234567890123456789012345678901234567890")!
|
||||
let bar = BigInt(0) - foo
|
||||
|
||||
XCTAssertEqual(-foo, bar)
|
||||
|
||||
var baz = foo
|
||||
baz.negate()
|
||||
XCTAssertEqual(baz, bar)
|
||||
}
|
||||
|
||||
func testSignum() {
|
||||
XCTAssertEqual(BigInt(-0x1p1023).signum(), -1)
|
||||
XCTAssertEqual(BigInt(Int64.min).signum(), -1)
|
||||
XCTAssertEqual(BigInt(Int32.min).signum(), -1)
|
||||
XCTAssertEqual(BigInt(Int16.min).signum(), -1)
|
||||
XCTAssertEqual(BigInt(Int8.min).signum(), -1)
|
||||
XCTAssertEqual(BigInt(-1).signum(), -1)
|
||||
XCTAssertEqual(BigInt(0).signum(), 0)
|
||||
XCTAssertEqual(BigInt(+1).signum(), +1)
|
||||
XCTAssertEqual(BigInt(Int8.max).signum(), +1)
|
||||
XCTAssertEqual(BigInt(Int16.max).signum(), +1)
|
||||
XCTAssertEqual(BigInt(Int32.max).signum(), +1)
|
||||
XCTAssertEqual(BigInt(Int64.max).signum(), +1)
|
||||
XCTAssertEqual(BigInt(+0x1p1023).signum(), +1)
|
||||
}
|
||||
|
||||
func testTrailingZeroCount() {
|
||||
let foo = BigInt(1) << 300
|
||||
XCTAssertEqual(foo.trailingZeroBitCount, 300)
|
||||
|
||||
let bar = (BigInt(1) << 300) + 0b101000
|
||||
XCTAssertEqual(bar.trailingZeroBitCount, 3)
|
||||
}
|
||||
|
||||
// MARK: - Comparing and hashing
|
||||
|
||||
func testComparable() {
|
||||
let foo = BigInt("1234567890123456789012345678901234567890")!
|
||||
let bar = foo * foo
|
||||
|
||||
XCTAssertLessThan(foo, bar)
|
||||
XCTAssertFalse(foo < foo)
|
||||
XCTAssertFalse(bar < bar)
|
||||
XCTAssertFalse(foo > foo)
|
||||
XCTAssertFalse(bar > bar)
|
||||
XCTAssertGreaterThan(bar, foo)
|
||||
|
||||
let baz = bar * -1
|
||||
|
||||
XCTAssertLessThan(baz, foo)
|
||||
XCTAssertNotEqual(bar, baz)
|
||||
XCTAssertFalse(baz < baz)
|
||||
}
|
||||
|
||||
func testComparison() {
|
||||
let foo = BigInt(-10)
|
||||
let bar = BigInt(-20)
|
||||
|
||||
XCTAssert(foo > bar)
|
||||
XCTAssert(bar < foo)
|
||||
XCTAssert(foo == BigInt(-10))
|
||||
|
||||
let baz = BigInt.pow(foo, -bar)
|
||||
XCTAssertEqual(baz, BigInt("100000000000000000000")!)
|
||||
}
|
||||
|
||||
func testExample() {
|
||||
let bar = BigInt(exactly: -100)
|
||||
XCTAssertNotNil(bar)
|
||||
if let bar = bar {
|
||||
XCTAssertLessThan(bar, 0)
|
||||
XCTAssertGreaterThan(-bar, 0)
|
||||
XCTAssertEqual(-bar, BigInt(100))
|
||||
}
|
||||
XCTAssertEqual(-BigInt("-1234567890123456789012345678901234567890")!,
|
||||
+BigInt("+1234567890123456789012345678901234567890")!)
|
||||
}
|
||||
|
||||
func testHashable() {
|
||||
let foo = BigInt("1234567890123456789012345678901234567890")!
|
||||
let bar = BigInt("1234567890123456789112345678901234567890")!
|
||||
let baz: BigInt = 153
|
||||
|
||||
let dict = [ foo: "Hello", bar: "World", baz: "!" ]
|
||||
|
||||
let hash = foo.hashValue
|
||||
print(hash)
|
||||
|
||||
XCTAssertEqual(dict[foo]!, "Hello")
|
||||
XCTAssertEqual(dict[bar]!, "World")
|
||||
}
|
||||
|
||||
func testClampingConversion() {
|
||||
XCTAssertEqual(BigInt(clamping: UInt64.max), BigInt(UInt64(18446744073709551615)))
|
||||
}
|
||||
|
||||
func testUIntConversion() {
|
||||
let foo = BigInt(UInt.max)
|
||||
XCTAssertNotEqual(foo, BigInt(-1))
|
||||
|
||||
let bar = BigInt(bitPattern: UInt.max)
|
||||
XCTAssertEqual(bar, BigInt(-1))
|
||||
}
|
||||
|
||||
// MARK: - Converting to/from textual representations
|
||||
|
||||
func testCodable() throws {
|
||||
let lowerBound = BigInt("-1234567890123456789012345678901234567890")!
|
||||
let upperBound = BigInt("+1234567890123456789012345678901234567890")!
|
||||
let expectedRange: Range<BigInt> = lowerBound ..< upperBound
|
||||
|
||||
let encoder = JSONEncoder()
|
||||
let decoder = JSONDecoder()
|
||||
let data = try encoder.encode(expectedRange)
|
||||
let actualRange = try decoder.decode(Range<BigInt>.self, from: data)
|
||||
|
||||
XCTAssertEqual(actualRange, expectedRange)
|
||||
}
|
||||
|
||||
func testCustomStringConvertible() {
|
||||
XCTAssertEqual("\(BigInt(UInt64.min) - 2)", "-2")
|
||||
XCTAssertEqual("\(BigInt(UInt64.min) - 1)", "-1")
|
||||
XCTAssertEqual("\(BigInt(UInt64.min) + 0)", "0")
|
||||
XCTAssertEqual("\(BigInt(UInt64.min) + 1)", "1")
|
||||
XCTAssertEqual("\(BigInt(UInt64.min) + 2)", "2")
|
||||
|
||||
XCTAssertEqual("\(BigInt(UInt64.max) - 2)", "18446744073709551613")
|
||||
XCTAssertEqual("\(BigInt(UInt64.max) - 1)", "18446744073709551614")
|
||||
XCTAssertEqual("\(BigInt(UInt64.max) + 0)", "18446744073709551615")
|
||||
XCTAssertEqual("\(BigInt(UInt64.max) + 1)", "18446744073709551616")
|
||||
XCTAssertEqual("\(BigInt(UInt64.max) + 2)", "18446744073709551617")
|
||||
|
||||
XCTAssertEqual("\(BigInt(Int64.min) - 2)", "-9223372036854775810")
|
||||
XCTAssertEqual("\(BigInt(Int64.min) - 1)", "-9223372036854775809")
|
||||
XCTAssertEqual("\(BigInt(Int64.min) + 0)", "-9223372036854775808")
|
||||
XCTAssertEqual("\(BigInt(Int64.min) + 1)", "-9223372036854775807")
|
||||
XCTAssertEqual("\(BigInt(Int64.min) + 2)", "-9223372036854775806")
|
||||
|
||||
XCTAssertEqual("\(BigInt(Int64.max) - 2)", "9223372036854775805")
|
||||
XCTAssertEqual("\(BigInt(Int64.max) - 1)", "9223372036854775806")
|
||||
XCTAssertEqual("\(BigInt(Int64.max) + 0)", "9223372036854775807")
|
||||
XCTAssertEqual("\(BigInt(Int64.max) + 1)", "9223372036854775808")
|
||||
XCTAssertEqual("\(BigInt(Int64.max) + 2)", "9223372036854775809")
|
||||
|
||||
XCTAssertEqual("\(-(BigInt(1) << 1023))", Self.descriptionInt1024Min)
|
||||
XCTAssertEqual("\(+(BigInt(1) << 1023) - 1)", Self.descriptionInt1024Max)
|
||||
}
|
||||
|
||||
func testLosslessStringConvertible() {
|
||||
XCTAssertNil(BigInt(""))
|
||||
XCTAssertNil(BigInt("-"))
|
||||
XCTAssertNil(BigInt("+"))
|
||||
XCTAssertNil(BigInt("A"))
|
||||
XCTAssertNil(BigInt(" 0"))
|
||||
XCTAssertNil(BigInt("0 "))
|
||||
|
||||
XCTAssertEqual(BigInt(UInt64.min) - 2, BigInt("-2"))
|
||||
XCTAssertEqual(BigInt(UInt64.min) - 1, BigInt("-1"))
|
||||
XCTAssertEqual(BigInt(UInt64.min) + 0, BigInt("0"))
|
||||
XCTAssertEqual(BigInt(UInt64.min) + 1, BigInt("1"))
|
||||
XCTAssertEqual(BigInt(UInt64.min) + 2, BigInt("2"))
|
||||
|
||||
XCTAssertEqual(BigInt(UInt64.max) - 2, BigInt("18446744073709551613"))
|
||||
XCTAssertEqual(BigInt(UInt64.max) - 1, BigInt("18446744073709551614"))
|
||||
XCTAssertEqual(BigInt(UInt64.max) + 0, BigInt("18446744073709551615"))
|
||||
XCTAssertEqual(BigInt(UInt64.max) + 1, BigInt("18446744073709551616"))
|
||||
XCTAssertEqual(BigInt(UInt64.max) + 2, BigInt("18446744073709551617"))
|
||||
|
||||
XCTAssertEqual(BigInt(Int64.min) - 2, BigInt("-9223372036854775810"))
|
||||
XCTAssertEqual(BigInt(Int64.min) - 1, BigInt("-9223372036854775809"))
|
||||
XCTAssertEqual(BigInt(Int64.min) + 0, BigInt("-9223372036854775808"))
|
||||
XCTAssertEqual(BigInt(Int64.min) + 1, BigInt("-9223372036854775807"))
|
||||
XCTAssertEqual(BigInt(Int64.min) + 2, BigInt("-9223372036854775806"))
|
||||
|
||||
XCTAssertEqual(BigInt(Int64.max) - 2, BigInt("9223372036854775805"))
|
||||
XCTAssertEqual(BigInt(Int64.max) - 1, BigInt("9223372036854775806"))
|
||||
XCTAssertEqual(BigInt(Int64.max) + 0, BigInt("9223372036854775807"))
|
||||
XCTAssertEqual(BigInt(Int64.max) + 1, BigInt("9223372036854775808"))
|
||||
XCTAssertEqual(BigInt(Int64.max) + 2, BigInt("9223372036854775809"))
|
||||
|
||||
XCTAssertEqual(-(BigInt(1) << 1023), BigInt(Self.descriptionInt1024Min))
|
||||
XCTAssertEqual(+(BigInt(1) << 1023) - 1, BigInt(Self.descriptionInt1024Max))
|
||||
}
|
||||
|
||||
func testRadicesAndNumerals() {
|
||||
for radix in 2 ... 36 {
|
||||
for uppercase in [false, true] {
|
||||
for _ in 0 ..< 100 {
|
||||
let expectedNumber = BigInt(Int.random(in: .min ... .max))
|
||||
let expectedString = String(expectedNumber,
|
||||
radix: radix,
|
||||
uppercase: uppercase)
|
||||
let actualNumber = BigInt(expectedString, radix: radix)
|
||||
XCTAssertEqual(actualNumber, expectedNumber)
|
||||
if radix == 10 {
|
||||
let actualString = expectedNumber.description
|
||||
XCTAssertEqual(actualString, expectedString)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Converting from floating-point binary types
|
||||
|
||||
func testBinaryFloatingPoint<T>(_ type: T.Type) where T: BinaryFloatingPoint {
|
||||
var expected = BigInt(T.greatestFiniteMagnitude.significandBitPattern)
|
||||
expected |= BigInt(1) << T.significandBitCount
|
||||
expected <<= T.greatestFiniteMagnitude.exponent
|
||||
expected >>= T.significandBitCount
|
||||
|
||||
XCTAssertEqual(BigInt(exactly: -T.greatestFiniteMagnitude), -expected)
|
||||
XCTAssertEqual(BigInt(exactly: +T.greatestFiniteMagnitude), +expected)
|
||||
XCTAssertEqual(BigInt(-T.greatestFiniteMagnitude), -expected)
|
||||
XCTAssertEqual(BigInt(+T.greatestFiniteMagnitude), +expected)
|
||||
|
||||
XCTAssertNil(BigInt(exactly: -T.infinity))
|
||||
XCTAssertNil(BigInt(exactly: +T.infinity))
|
||||
|
||||
XCTAssertNil(BigInt(exactly: -T.leastNonzeroMagnitude))
|
||||
XCTAssertNil(BigInt(exactly: +T.leastNonzeroMagnitude))
|
||||
XCTAssertEqual(BigInt(-T.leastNonzeroMagnitude), 0)
|
||||
XCTAssertEqual(BigInt(+T.leastNonzeroMagnitude), 0)
|
||||
|
||||
XCTAssertNil(BigInt(exactly: -T.leastNormalMagnitude))
|
||||
XCTAssertNil(BigInt(exactly: +T.leastNormalMagnitude))
|
||||
XCTAssertEqual(BigInt(-T.leastNormalMagnitude), 0)
|
||||
XCTAssertEqual(BigInt(+T.leastNormalMagnitude), 0)
|
||||
|
||||
XCTAssertNil(BigInt(exactly: T.nan))
|
||||
XCTAssertNil(BigInt(exactly: T.signalingNaN))
|
||||
|
||||
XCTAssertNil(BigInt(exactly: -T.pi))
|
||||
XCTAssertNil(BigInt(exactly: +T.pi))
|
||||
XCTAssertEqual(BigInt(-T.pi), -3)
|
||||
XCTAssertEqual(BigInt(+T.pi), +3)
|
||||
|
||||
XCTAssertNil(BigInt(exactly: -T.ulpOfOne))
|
||||
XCTAssertNil(BigInt(exactly: +T.ulpOfOne))
|
||||
XCTAssertEqual(BigInt(-T.ulpOfOne), 0)
|
||||
XCTAssertEqual(BigInt(+T.ulpOfOne), 0)
|
||||
|
||||
XCTAssertEqual(BigInt(exactly: -T.zero), 0)
|
||||
XCTAssertEqual(BigInt(exactly: +T.zero), 0)
|
||||
XCTAssertEqual(BigInt(-T.zero), 0)
|
||||
XCTAssertEqual(BigInt(+T.zero), 0)
|
||||
}
|
||||
|
||||
func testBinaryFloatingPoint() {
|
||||
testBinaryFloatingPoint(Float32.self)
|
||||
testBinaryFloatingPoint(Float64.self)
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
testBinaryFloatingPoint(Float80.self)
|
||||
#endif
|
||||
|
||||
for _ in 0 ..< 100 {
|
||||
let small = Float32.random(in: -10 ... +10)
|
||||
XCTAssertEqual(BigInt(small), BigInt(Int64(small)))
|
||||
|
||||
let large = Float32.random(in: -0x1p23 ... +0x1p23)
|
||||
XCTAssertEqual(BigInt(large), BigInt(Int64(large)))
|
||||
}
|
||||
|
||||
for _ in 0 ..< 100 {
|
||||
let small = Float64.random(in: -10 ... +10)
|
||||
XCTAssertEqual(BigInt(small), BigInt(Int64(small)))
|
||||
|
||||
let large = Float64.random(in: -0x1p52 ... +0x1p52)
|
||||
XCTAssertEqual(BigInt(large), BigInt(Int64(large)))
|
||||
}
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
for _ in 0 ..< 100 {
|
||||
let small = Float80.random(in: -10 ... +10)
|
||||
XCTAssertEqual(BigInt(small), BigInt(Int64(small)))
|
||||
|
||||
let large = Float80.random(in: -0x1p63 ..< +0x1p63)
|
||||
XCTAssertEqual(BigInt(large), BigInt(Int64(large)))
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
//===--- BigUIntTests.swift -----------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import BigIntModule
|
||||
import XCTest
|
||||
|
||||
extension BigUInt {
|
||||
|
||||
static func fac(_ n: BigUInt) -> BigUInt {
|
||||
return stride(from: n, to: 1, by: -1).reduce(into: 1, { $0 *= $1 })
|
||||
}
|
||||
|
||||
// inspired by https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms
|
||||
static func pow(_ lhs: BigUInt, _ rhs: BigUInt) -> BigUInt {
|
||||
let bits_of_n = { (n: BigUInt) -> [Int] in
|
||||
var bits: [Int] = []
|
||||
var n = n
|
||||
while n != 0 {
|
||||
bits.append(Int(n % 2))
|
||||
n /= 2
|
||||
}
|
||||
|
||||
return bits
|
||||
}
|
||||
|
||||
var r: BigUInt = 1
|
||||
for bit in bits_of_n(rhs).reversed() {
|
||||
r *= r
|
||||
if bit == 1 {
|
||||
r *= lhs
|
||||
}
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
}
|
||||
|
||||
final class BigUIntTests: XCTestCase {
|
||||
|
||||
/// Python: `bitWidth = 1024; -(2 ** (bitWidth - 1))`
|
||||
static let descriptionInt1024Min: String =
|
||||
"""
|
||||
-89884656743115795386465259539451236680898848947115328636715040578866337902\
|
||||
750481566354238661203768010560056939935696678829394884407208311246423715319\
|
||||
737062188883946712432742638151109800623047059726541476042502884419075341171\
|
||||
231440736956555270413618581675255342293149119973622969239858152417678164812\
|
||||
112068608
|
||||
"""
|
||||
|
||||
/// Python: `bitWidth = 1024; (2 ** (bitWidth - 1)) - 1`
|
||||
static let descriptionInt1024Max: String =
|
||||
"""
|
||||
89884656743115795386465259539451236680898848947115328636715040578866337902\
|
||||
750481566354238661203768010560056939935696678829394884407208311246423715319\
|
||||
737062188883946712432742638151109800623047059726541476042502884419075341171\
|
||||
231440736956555270413618581675255342293149119973622969239858152417678164812\
|
||||
112068607
|
||||
"""
|
||||
|
||||
/// Python: `numpy.base_repr(math.factorial(512), base=36)`
|
||||
static let descriptionFactorial512_radix36: String =
|
||||
"""
|
||||
7FA5Y7EHR9XHMQ519MBHGYOF8XDYMUX8OZHO9WF1KCM0SSPXV2V45UA73BAFRYM2PFB8CZLTODV\
|
||||
OS3QWA7PYFJ7WAFBI4VF371E27N6XZ4LGWHMFDS4ZH1O3DGNFG4YABUE1G90ORGRTIOGSQVZLSQ\
|
||||
4TKHKHIQ262JVQ0J6LSKAPN5I65AJD33XODVHRNWJ1VSO0Q2FBOUNCPGQG2SFQKR17XHF1OLTV2\
|
||||
MVNJVTDAIYWVJ9ZH7KXT0EPS00IGIVC7MNCU25HFWE37KNMSJQUL5ALUCE5XZVPFQCQGEVEB93B\
|
||||
GA8LKG67PVZ7Q9QMQKIVNIMPT2973MVDTD1D1A0A4QT6NBZYR0TGSZXBV1PD0CHW4SKZJSLBS4Z\
|
||||
W5WCKDY8BCQCE17KKADVLCTVSQL1BZ2PL52DDPB8S5L0ZEG2ZAZF9V4TNJJNO1D9U9JU7B264QZ\
|
||||
5GLHC3Q0Y3BTECGTI8GRENQ2FV4HSEZKPM9OG302KLSY9MBCSOO0FN229AST84TT87LYWOOS71C\
|
||||
54RPJ9RTO9875Z9DE3HPH89EW5I3SV219O04UU09A4KME7DD7IH49ABO79NR4EXFX1VLL4YOHSA\
|
||||
7AHD1LS5YKZ66F4UPG0RCBGG000000000000000000000000000000000000000000000000000\
|
||||
000000000000000000000000000000000000000000000000000000000000000000000000000
|
||||
"""
|
||||
|
||||
// MARK: - Basic arithmetic
|
||||
|
||||
func testDivision() {
|
||||
let num1 = BigUInt("18446744073709551616")!
|
||||
let den1 = BigUInt(123)
|
||||
let expected1 = BigUInt(UInt64(149973529054549200))
|
||||
XCTAssertEqual(num1 / den1, expected1)
|
||||
|
||||
let num2 = BigUInt.pow(BigUInt(10), 100)
|
||||
let den2: BigUInt = 3
|
||||
let expected2: BigUInt = BigUInt(String(repeating: "3", count: 100))!
|
||||
let actual2 = num2 / den2
|
||||
XCTAssertEqual(actual2, expected2)
|
||||
|
||||
let num3 = BigUInt.pow(BigUInt(10), 97)
|
||||
let den3: BigUInt = BigUInt("33333333333333333333")!
|
||||
let expected3: BigUInt = BigUInt("300000000000000000003000000000000000000030000000000000000000300000000000000000")!
|
||||
let actual3 = num3 / den3
|
||||
XCTAssertEqual(actual3, expected3)
|
||||
|
||||
let foo = BigUInt("12345678901234567890123456789012345678901234567890123456789012345678901234567890")!
|
||||
let bar = BigUInt("351235231535161613134135135135")!
|
||||
let baz = foo / bar
|
||||
XCTAssertEqual(baz, BigUInt("35149318157164029153358504918339691272847595997760")!)
|
||||
|
||||
XCTAssertNotNil(BigUInt(exactly: 2.4e39))
|
||||
XCTAssertNotNil(BigUInt(exactly: 1e38))
|
||||
XCTAssertEqual(BigUInt(2.4e39) / BigUInt(1e38), BigUInt(24))
|
||||
|
||||
for _ in 0 ..< 100 {
|
||||
let expected = BigUInt(Float64.random(in: 0x1p64 ... 0x1p255))
|
||||
let divisor = BigUInt(Float64.random(in: 0x1p64 ... 0x1p128))
|
||||
let (quotient, remainder) = expected.quotientAndRemainder(dividingBy: divisor)
|
||||
let actual = divisor * quotient + remainder
|
||||
XCTAssertEqual(quotient, expected / divisor)
|
||||
XCTAssertEqual(remainder, expected % divisor)
|
||||
XCTAssertEqual(
|
||||
actual, expected,
|
||||
"""
|
||||
## FAILURE ##
|
||||
~~~~~~~~~~~~~
|
||||
actual: \(actual)
|
||||
!= expected: \(expected)
|
||||
~~~~~~~~~~~~~
|
||||
divisor: \(divisor)
|
||||
* quotient: \(quotient)
|
||||
+ remainder: \(remainder)
|
||||
~~~~~~~~~~~~~
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func testFactorial() {
|
||||
var expectedNumber: BigUInt?
|
||||
var actualNumber: BigUInt!
|
||||
var actualString: String!
|
||||
|
||||
measure {
|
||||
expectedNumber = BigUInt(Self.descriptionFactorial512_radix36, radix: 36)
|
||||
actualNumber = BigUInt.fac(512)
|
||||
actualString = String(actualNumber, radix: 36, uppercase: true)
|
||||
}
|
||||
|
||||
XCTAssertEqual(actualNumber, expectedNumber)
|
||||
XCTAssertEqual(actualString, Self.descriptionFactorial512_radix36)
|
||||
|
||||
XCTAssertEqual(BigUInt.fac(0), 1)
|
||||
XCTAssertEqual(BigUInt.fac(1), 1)
|
||||
XCTAssertEqual(BigUInt.fac(2), 2)
|
||||
XCTAssertEqual(BigUInt.fac(3), 6)
|
||||
XCTAssertEqual(BigUInt.fac(4), 24)
|
||||
XCTAssertEqual(BigUInt.fac(5), 120)
|
||||
XCTAssertEqual(BigUInt.fac(6), 720)
|
||||
XCTAssertEqual(BigUInt.fac(7), 5040)
|
||||
XCTAssertEqual(BigUInt.fac(8), 40320)
|
||||
XCTAssertEqual(BigUInt.fac(9), 362880)
|
||||
}
|
||||
|
||||
func testMath() {
|
||||
let foo = BigUInt.pow(10, 20)
|
||||
let bar = BigUInt("1234567890123456789012345678901234567890")!
|
||||
|
||||
let baz = foo + bar
|
||||
|
||||
XCTAssertEqual(baz, BigUInt("1234567890123456789112345678901234567890")!)
|
||||
|
||||
let fooz = foo >> BigUInt(10)
|
||||
XCTAssertEqual(fooz, foo / 1024)
|
||||
|
||||
let barz = BigUInt(1) << 64
|
||||
XCTAssertEqual(barz, BigUInt(UInt64.max) + 1)
|
||||
}
|
||||
|
||||
func testTrailingZeroCount() {
|
||||
let foo = BigUInt(1) << 300
|
||||
XCTAssertEqual(foo.trailingZeroBitCount, 300)
|
||||
|
||||
let bar = (BigUInt(1) << 300) + 0b101000
|
||||
XCTAssertEqual(bar.trailingZeroBitCount, 3)
|
||||
}
|
||||
|
||||
// MARK: - Comparing and hashing
|
||||
|
||||
func testComparable() {
|
||||
let foo = BigUInt("1234567890123456789012345678901234567890")!
|
||||
let bar = foo * foo
|
||||
|
||||
XCTAssertLessThan(foo, bar)
|
||||
XCTAssertFalse(foo < foo)
|
||||
XCTAssertFalse(bar < bar)
|
||||
XCTAssertFalse(foo > foo)
|
||||
XCTAssertFalse(bar > bar)
|
||||
XCTAssertGreaterThan(bar, foo)
|
||||
}
|
||||
|
||||
func testHashable() {
|
||||
let foo = BigInt("1234567890123456789012345678901234567890")!
|
||||
let bar = BigInt("1234567890123456789112345678901234567890")!
|
||||
let baz: BigInt = 153
|
||||
|
||||
let dict = [foo: "Hello", bar: "World", baz: "!"]
|
||||
let hash = foo.hashValue
|
||||
print(hash)
|
||||
|
||||
XCTAssertEqual(dict[foo]!, "Hello")
|
||||
XCTAssertEqual(dict[bar]!, "World")
|
||||
}
|
||||
|
||||
func testClampingConversion() {
|
||||
XCTAssertEqual(BigUInt(clamping: UInt64.max), BigUInt(UInt64(18446744073709551615)))
|
||||
}
|
||||
|
||||
// MARK: - Converting to/from textual representations
|
||||
|
||||
func testCodable() throws {
|
||||
let lowerBound = BigUInt("0")!
|
||||
let upperBound = BigUInt("+1234567890123456789012345678901234567890")!
|
||||
let expectedRange: Range<BigUInt> = lowerBound ..< upperBound
|
||||
|
||||
let encoder = JSONEncoder()
|
||||
let decoder = JSONDecoder()
|
||||
let data = try encoder.encode(expectedRange)
|
||||
let actualRange = try decoder.decode(Range<BigUInt>.self, from: data)
|
||||
|
||||
XCTAssertEqual(actualRange, expectedRange)
|
||||
}
|
||||
|
||||
func testCustomStringConvertible() {
|
||||
XCTAssertEqual("\(BigUInt(UInt64.min) + 0)", "0")
|
||||
XCTAssertEqual("\(BigUInt(UInt64.min) + 1)", "1")
|
||||
XCTAssertEqual("\(BigUInt(UInt64.min) + 2)", "2")
|
||||
|
||||
XCTAssertEqual("\(BigUInt(UInt64.max) - 2)", "18446744073709551613")
|
||||
XCTAssertEqual("\(BigUInt(UInt64.max) - 1)", "18446744073709551614")
|
||||
XCTAssertEqual("\(BigUInt(UInt64.max) + 0)", "18446744073709551615")
|
||||
XCTAssertEqual("\(BigUInt(UInt64.max) + 1)", "18446744073709551616")
|
||||
XCTAssertEqual("\(BigUInt(UInt64.max) + 2)", "18446744073709551617")
|
||||
|
||||
XCTAssertEqual("\(BigUInt(Int64.max) - 2)", "9223372036854775805")
|
||||
XCTAssertEqual("\(BigUInt(Int64.max) - 1)", "9223372036854775806")
|
||||
XCTAssertEqual("\(BigUInt(Int64.max) + 0)", "9223372036854775807")
|
||||
XCTAssertEqual("\(BigUInt(Int64.max) + 1)", "9223372036854775808")
|
||||
XCTAssertEqual("\(BigUInt(Int64.max) + 2)", "9223372036854775809")
|
||||
|
||||
XCTAssertEqual("\(+(BigUInt(1) << 1023) - 1)", Self.descriptionInt1024Max)
|
||||
}
|
||||
|
||||
func testLosslessStringConvertible() {
|
||||
XCTAssertNil(BigUInt(""))
|
||||
XCTAssertNil(BigUInt("+"))
|
||||
XCTAssertNil(BigUInt("A"))
|
||||
XCTAssertNil(BigUInt(" 0"))
|
||||
XCTAssertNil(BigUInt("0 "))
|
||||
|
||||
XCTAssertEqual(BigUInt(UInt64.min) + 0, BigUInt("0"))
|
||||
XCTAssertEqual(BigUInt(UInt64.min) + 1, BigUInt("1"))
|
||||
XCTAssertEqual(BigUInt(UInt64.min) + 2, BigUInt("2"))
|
||||
|
||||
XCTAssertEqual(BigUInt(UInt64.max) - 2, BigUInt("18446744073709551613"))
|
||||
XCTAssertEqual(BigUInt(UInt64.max) - 1, BigUInt("18446744073709551614"))
|
||||
XCTAssertEqual(BigUInt(UInt64.max) + 0, BigUInt("18446744073709551615"))
|
||||
XCTAssertEqual(BigUInt(UInt64.max) + 1, BigUInt("18446744073709551616"))
|
||||
XCTAssertEqual(BigUInt(UInt64.max) + 2, BigUInt("18446744073709551617"))
|
||||
|
||||
XCTAssertEqual(BigUInt(Int64.max) - 2, BigUInt("9223372036854775805"))
|
||||
XCTAssertEqual(BigUInt(Int64.max) - 1, BigUInt("9223372036854775806"))
|
||||
XCTAssertEqual(BigUInt(Int64.max) + 0, BigUInt("9223372036854775807"))
|
||||
XCTAssertEqual(BigUInt(Int64.max) + 1, BigUInt("9223372036854775808"))
|
||||
XCTAssertEqual(BigUInt(Int64.max) + 2, BigUInt("9223372036854775809"))
|
||||
|
||||
XCTAssertEqual(+(BigUInt(1) << 1023) - 1, BigUInt(Self.descriptionInt1024Max))
|
||||
}
|
||||
|
||||
func testRadicesAndNumerals() {
|
||||
for radix in 2 ... 36 {
|
||||
for uppercase in [false, true] {
|
||||
for _ in 0 ..< 100 {
|
||||
let expectedNumber = BigUInt(UInt.random(in: .min ... .max))
|
||||
let expectedString = String(expectedNumber,
|
||||
radix: radix,
|
||||
uppercase: uppercase)
|
||||
let actualNumber = BigUInt(expectedString, radix: radix)
|
||||
XCTAssertEqual(actualNumber, expectedNumber)
|
||||
if radix == 10 {
|
||||
let actualString = expectedNumber.description
|
||||
XCTAssertEqual(actualString, expectedString)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Converting from floating-point binary types
|
||||
|
||||
func testBinaryFloatingPoint<T>(_ type: T.Type) where T: BinaryFloatingPoint {
|
||||
var expected = BigUInt(T.greatestFiniteMagnitude.significandBitPattern)
|
||||
expected |= BigUInt(1) << T.significandBitCount
|
||||
expected <<= T.greatestFiniteMagnitude.exponent
|
||||
expected >>= T.significandBitCount
|
||||
|
||||
XCTAssertEqual(BigUInt(exactly: +T.greatestFiniteMagnitude), +expected)
|
||||
XCTAssertEqual(BigUInt(+T.greatestFiniteMagnitude), +expected)
|
||||
|
||||
XCTAssertNil(BigUInt(exactly: +T.infinity))
|
||||
|
||||
XCTAssertNil(BigUInt(exactly: +T.leastNonzeroMagnitude))
|
||||
XCTAssertEqual(BigUInt(+T.leastNonzeroMagnitude), 0)
|
||||
|
||||
XCTAssertNil(BigUInt(exactly: +T.leastNormalMagnitude))
|
||||
XCTAssertEqual(BigUInt(+T.leastNormalMagnitude), 0)
|
||||
|
||||
XCTAssertNil(BigUInt(exactly: T.nan))
|
||||
XCTAssertNil(BigUInt(exactly: T.signalingNaN))
|
||||
|
||||
XCTAssertNil(BigUInt(exactly: +T.pi))
|
||||
XCTAssertEqual(BigUInt(+T.pi), +3)
|
||||
|
||||
XCTAssertNil(BigUInt(exactly: +T.ulpOfOne))
|
||||
XCTAssertEqual(BigUInt(+T.ulpOfOne), 0)
|
||||
|
||||
XCTAssertEqual(BigUInt(exactly: +T.zero), 0)
|
||||
XCTAssertEqual(BigUInt(+T.zero), 0)
|
||||
}
|
||||
|
||||
func testBinaryFloatingPoint() {
|
||||
testBinaryFloatingPoint(Float32.self)
|
||||
testBinaryFloatingPoint(Float64.self)
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
testBinaryFloatingPoint(Float80.self)
|
||||
#endif
|
||||
|
||||
for _ in 0 ..< 100 {
|
||||
let small = Float32.random(in: 0 ... +10)
|
||||
XCTAssertEqual(BigUInt(small), BigUInt(Int64(small)))
|
||||
|
||||
let large = Float32.random(in: 0 ... +0x1p23)
|
||||
XCTAssertEqual(BigUInt(large), BigUInt(Int64(large)))
|
||||
}
|
||||
|
||||
for _ in 0 ..< 100 {
|
||||
let small = Float64.random(in: 0 ... +10)
|
||||
XCTAssertEqual(BigUInt(small), BigUInt(Int64(small)))
|
||||
|
||||
let large = Float64.random(in: -0x1p52 ... +0x1p52)
|
||||
XCTAssertEqual(BigInt(large), BigInt(Int64(large)))
|
||||
}
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
for _ in 0 ..< 100 {
|
||||
let small = Float80.random(in: 0 ... +10)
|
||||
XCTAssertEqual(BigUInt(small), BigUInt(Int64(small)))
|
||||
|
||||
let large = Float80.random(in: 0 ..< +0x1p63)
|
||||
XCTAssertEqual(BigUInt(large), BigUInt(Int64(large)))
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#[[
|
||||
This source file is part of the Swift Numerics open source project
|
||||
|
||||
Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
find_package(dispatch CONFIG QUIET)
|
||||
find_package(Foundation CONFIG QUIET)
|
||||
find_package(XCTest CONFIG QUIET)
|
||||
|
||||
add_subdirectory(ComplexTests)
|
||||
add_subdirectory(IntegerUtilitiesTests)
|
||||
add_subdirectory(RealTests)
|
||||
|
||||
add_executable(SwiftNumericsTestRunner
|
||||
WindowsMain.swift)
|
||||
target_link_libraries(SwiftNumericsTestRunner PRIVATE
|
||||
ComplexTests
|
||||
IntegerUtilitiesTests
|
||||
RealTests)
|
||||
|
||||
add_test(NAME SwiftNumericsTestRunner
|
||||
COMMAND SwiftNumericsTestRunner)
|
||||
@@ -1,8 +1,8 @@
|
||||
//===--- ApproximateEqualityTests.swift -----------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2024 Apple Inc. and the Swift Numerics project authors
|
||||
// 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
|
||||
@@ -13,23 +13,11 @@ import XCTest
|
||||
import ComplexModule
|
||||
import RealModule
|
||||
|
||||
func ulpsFromInfinity<T: Real>(_ a: T) -> T {
|
||||
(.greatestFiniteMagnitude - a) / .greatestFiniteMagnitude.ulp + 1
|
||||
}
|
||||
|
||||
// TODO: improve this to be a general-purpose complex comparison with tolerance
|
||||
func relativeError<T>(_ a: Complex<T>, _ b: Complex<T>) -> T {
|
||||
if a == b { return 0 }
|
||||
if a.isFinite && b.isFinite {
|
||||
let scale = max(a.magnitude, b.magnitude, T.leastNormalMagnitude).ulp
|
||||
return (a - b).magnitude / scale
|
||||
} else {
|
||||
if a.isFinite {
|
||||
return ulpsFromInfinity(a.magnitude)
|
||||
} else {
|
||||
return ulpsFromInfinity(b.magnitude)
|
||||
}
|
||||
}
|
||||
let scale = max(a.magnitude, b.magnitude, T.leastNormalMagnitude).ulp
|
||||
return (a - b).magnitude / scale
|
||||
}
|
||||
|
||||
func closeEnough<T: Real>(_ a: T, _ b: T, ulps allowed: T) -> Bool {
|
||||
@@ -41,15 +29,11 @@ func checkMultiply<T>(
|
||||
_ a: Complex<T>, _ b: Complex<T>, expected: Complex<T>, ulps allowed: T
|
||||
) -> Bool {
|
||||
let observed = a*b
|
||||
if observed == expected { return false }
|
||||
// Even if the expected result is finite, we allow overflow if
|
||||
// the two-norm of the expected result overflows.
|
||||
if !observed.isFinite && !expected.length.isFinite { return false }
|
||||
let rel = relativeError(observed, expected)
|
||||
guard rel <= allowed else {
|
||||
if rel > allowed {
|
||||
print("Over-large error in \(a)*\(b)")
|
||||
print("Expected: \(expected)\nObserved: \(observed)")
|
||||
print("Relative error was \(rel) (tolerance: \(allowed)).")
|
||||
print("Relative error was \(rel) (tolerance: \(allowed).")
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -59,15 +43,11 @@ func checkDivide<T>(
|
||||
_ a: Complex<T>, _ b: Complex<T>, expected: Complex<T>, ulps allowed: T
|
||||
) -> Bool {
|
||||
let observed = a/b
|
||||
if observed == expected { return false }
|
||||
// Even if the expected result is finite, we allow overflow if
|
||||
// the two-norm of the expected result overflows.
|
||||
if !observed.isFinite && !expected.length.isFinite { return false }
|
||||
let rel = relativeError(observed, expected)
|
||||
guard rel <= allowed else {
|
||||
if rel > allowed {
|
||||
print("Over-large error in \(a)/\(b)")
|
||||
print("Expected: \(expected)\nObserved: \(observed)")
|
||||
print("Relative error was \(rel) (tolerance: \(allowed)).")
|
||||
print("Relative error was \(rel) (tolerance: \(allowed).")
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -83,6 +63,7 @@ final class ArithmeticTests: XCTestCase {
|
||||
func testPolar<T>(_ type: T.Type)
|
||||
where T: BinaryFloatingPoint, T: Real,
|
||||
T.Exponent: FixedWidthInteger, T.RawSignificand: FixedWidthInteger {
|
||||
|
||||
// In order to support round-tripping from rectangular to polar coordinate
|
||||
// systems, as a special case phase can be non-finite when length is
|
||||
// either zero or infinity.
|
||||
@@ -95,9 +76,10 @@ final class ArithmeticTests: XCTestCase {
|
||||
XCTAssertEqual(Complex<T>(length:-.infinity, phase: .infinity), .infinity)
|
||||
XCTAssertEqual(Complex<T>(length:-.infinity, phase:-.infinity), .infinity)
|
||||
XCTAssertEqual(Complex<T>(length:-.infinity, phase: .nan ), .infinity)
|
||||
|
||||
|
||||
let exponentRange =
|
||||
T.leastNormalMagnitude.exponent ... T.greatestFiniteMagnitude.exponent
|
||||
(T.leastNormalMagnitude.exponent + T.Exponent(T.significandBitCount)) ...
|
||||
T.greatestFiniteMagnitude.exponent
|
||||
let inputs = (0..<100).map { _ in
|
||||
Polar(length: T(
|
||||
sign: .plus,
|
||||
@@ -154,29 +136,20 @@ final class ArithmeticTests: XCTestCase {
|
||||
// Now test multiplication and division using the polar inputs:
|
||||
for q in inputs {
|
||||
let w = Complex(length: q.length, phase: q.phase)
|
||||
var product = Complex(length: p.length, phase: p.phase + q.phase)
|
||||
product.real *= q.length
|
||||
product.imaginary *= q.length
|
||||
let product = Complex(length: p.length * q.length, phase: p.phase + q.phase)
|
||||
if checkMultiply(z, w, expected: product, ulps: 16) { XCTFail() }
|
||||
var quotient = Complex(length: p.length, phase: p.phase - q.phase)
|
||||
quotient.real /= q.length
|
||||
quotient.imaginary /= q.length
|
||||
let quotient = Complex(length: p.length / q.length, phase: p.phase - q.phase)
|
||||
if checkDivide(z, w, expected: quotient, ulps: 16) { XCTFail() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testPolar() {
|
||||
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64)) && LONG_TESTS
|
||||
if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
|
||||
testPolar(Float16.self)
|
||||
}
|
||||
#endif
|
||||
testPolar(Float.self)
|
||||
testPolar(Double.self)
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
testPolar(Float80.self)
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
func testBaudinSmith() {
|
||||
@@ -218,38 +191,16 @@ final class ArithmeticTests: XCTestCase {
|
||||
Complex(1.02951151789360578e-84, 6.97145987515076231e-220)),
|
||||
]
|
||||
for test in vectors {
|
||||
if checkDivide(test.a, test.b, expected: test.c, ulps: 1.0) { XCTFail() }
|
||||
if checkDivide(test.a, test.b, expected: test.c, ulps: 0.5) { XCTFail() }
|
||||
if checkDivide(test.a, test.c, expected: test.b, ulps: 1.0) { XCTFail() }
|
||||
if checkMultiply(test.b, test.c, expected: test.a, ulps: 1.0) { XCTFail() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testDivisionByZero() {
|
||||
XCTAssertFalse((Complex(0, 0) / Complex(0, 0)).isFinite)
|
||||
XCTAssertFalse((Complex(1, 1) / Complex(0, 0)).isFinite)
|
||||
XCTAssertFalse((Complex.infinity / Complex(0, 0)).isFinite)
|
||||
XCTAssertFalse((Complex.i / Complex(0, 0)).isFinite)
|
||||
|
||||
}
|
||||
|
||||
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64)) && LONG_TESTS
|
||||
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
|
||||
func testFloat16DivisionSemiExhaustive() {
|
||||
func complex(bitPattern: UInt32) -> Complex<Float16> {
|
||||
Complex(
|
||||
Float16(bitPattern: UInt16(truncatingIfNeeded: bitPattern)),
|
||||
Float16(bitPattern: UInt16(truncatingIfNeeded: bitPattern >> 16))
|
||||
)
|
||||
}
|
||||
for bits in 0 ... UInt32.max {
|
||||
let a = complex(bitPattern: bits)
|
||||
if bits & 0xfffff == 0 { print(a) }
|
||||
let b = complex(bitPattern: UInt32.random(in: 0 ... .max))
|
||||
var q = Complex<Float>(a)/Complex<Float>(b)
|
||||
if checkDivide(a, b, expected: Complex<Float16>(q), ulps: 4) { XCTFail() }
|
||||
q = Complex<Float>(b)/Complex<Float>(a)
|
||||
if checkDivide(b, a, expected: Complex<Float16>(q), ulps: 4) { XCTFail() }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
//===--- ElementaryFunctionTests.swift ------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
//===--- main.swift -------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Numerics
|
||||
import _TestSupport
|
||||
|
||||
#if DEBUG
|
||||
fatalError("Run this test in Release configuration")
|
||||
#else
|
||||
|
||||
var componentError = Double(Float.ulpOfOne/2)
|
||||
var complexError = Double(Float.ulpOfOne/2)
|
||||
var componentMaxInput = Complex<Float>.zero
|
||||
var complexMaxInput = Complex<Float>.zero
|
||||
|
||||
func test(_ z: Complex<Float>) {
|
||||
let tst = Complex.log(z)
|
||||
// TODO: we _should_ be able to say Complex<Double>(z), but that goes through
|
||||
// the slow, generic path for BinaryFloatingPoint conversion; once we get
|
||||
// that resolved in the standard library, we can replace the conversion on
|
||||
// this and the next line. Currently it dominate testing time if we do that.
|
||||
let ref = Complex.log(Complex(Double(z.real), Double(z.imaginary)))
|
||||
if tst == Complex(Float(ref.real), Float(ref.imaginary)) { return }
|
||||
let thisError = relativeError(tst, ref)
|
||||
if thisError > complexError {
|
||||
complexMaxInput = z
|
||||
complexError = thisError
|
||||
}
|
||||
let thisComponentError = componentwiseError(tst, ref)
|
||||
if thisComponentError > componentError {
|
||||
componentMaxInput = z
|
||||
componentError = thisComponentError
|
||||
}
|
||||
}
|
||||
|
||||
func testWithSymmetries(_ x: Float, _ y: Float) {
|
||||
test(Complex( x, y))
|
||||
test(Complex( y, x))
|
||||
test(Complex(-y, x))
|
||||
test(Complex(-x, y))
|
||||
test(Complex(-x,-y))
|
||||
test(Complex(-y,-x))
|
||||
test(Complex( y,-x))
|
||||
test(Complex( x,-y))
|
||||
}
|
||||
|
||||
// The hardest to evaluate cases for log are those close to the unit circle,
|
||||
// where log(z) is nearly zero. We want to have plausibly dense test coverage
|
||||
// close to the circle.
|
||||
let radii: [Float] = [0.9,
|
||||
0.95,
|
||||
0.99,
|
||||
0.999,
|
||||
0.9999,
|
||||
1 - 10 * .ulpOfOne,
|
||||
1,
|
||||
1 + 10 * .ulpOfOne,
|
||||
1.0001,
|
||||
1.001,
|
||||
1.01,
|
||||
1.05,
|
||||
1.1]
|
||||
|
||||
for r in radii {
|
||||
for x in Interval(from: 1/Float.sqrt(2), to: r) {
|
||||
// Generate the two y values that put us closest to the circle of radius r
|
||||
let base = Double.sqrt(Double(r).addingProduct(Double(-x), Double(x)))
|
||||
let a, b: Float
|
||||
if Double(Float(base)) < base { a = Float(base); b = a.nextUp }
|
||||
else { b = Float(base); a = b.nextDown }
|
||||
testWithSymmetries(x, a)
|
||||
testWithSymmetries(x, b)
|
||||
}
|
||||
}
|
||||
|
||||
// Away from the unit circle is "easy" but we still want to get some coverage.
|
||||
// Generate 1 million uniform random points inside the circle, and then test
|
||||
// both z and 1/z.
|
||||
var g = SystemRandomNumberGenerator()
|
||||
var count = 0
|
||||
while count < 1_000_000 {
|
||||
let z = Complex<Float>(.random(in: -1 ... 1, using: &g), .random(in: -1 ... 1, using: &g))
|
||||
if z.length > 1 { continue }
|
||||
count += 1
|
||||
test(z)
|
||||
test(1/z)
|
||||
}
|
||||
|
||||
print("Worst complex norm error seen for log was \(complexError)")
|
||||
print("For input \(complexMaxInput).")
|
||||
print("Reference result: \(Complex.log(Complex<Double>(complexMaxInput)))")
|
||||
print(" Observed result: \(Complex.log(complexMaxInput))")
|
||||
|
||||
print("Worst componentwise error seen for log was \(componentError)")
|
||||
print("For input \(componentMaxInput).")
|
||||
print("Reference result: \(Complex.log(Complex<Double>(componentMaxInput)))")
|
||||
print(" Observed result: \(Complex.log(componentMaxInput))")
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,108 @@
|
||||
//===--- main.swift -------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Numerics
|
||||
import _TestSupport
|
||||
|
||||
#if DEBUG
|
||||
fatalError("Run this test in Release configuration")
|
||||
#else
|
||||
|
||||
var componentError = Double(Float.ulpOfOne/2)
|
||||
var complexError = Double(Float.ulpOfOne/2)
|
||||
var componentMaxInput = Complex<Float>.zero
|
||||
var complexMaxInput = Complex<Float>.zero
|
||||
|
||||
func test(_ z: Complex<Float>) {
|
||||
let tst = Complex.log(onePlus: z)
|
||||
// TODO: we _should_ be able to say Complex<Double>(z), but that goes through
|
||||
// the slow, generic path for BinaryFloatingPoint conversion; once we get
|
||||
// that resolved in the standard library, we can replace the conversion on
|
||||
// this and the next line. Currently it dominate testing time if we do that.
|
||||
let ref = Complex.log(onePlus: Complex(Double(z.real), Double(z.imaginary)))
|
||||
if tst == Complex(Float(ref.real), Float(ref.imaginary)) { return }
|
||||
let thisError = relativeError(tst, ref)
|
||||
if thisError > complexError {
|
||||
complexMaxInput = z
|
||||
complexError = thisError
|
||||
}
|
||||
let thisComponentError = componentwiseError(tst, ref)
|
||||
if thisComponentError > componentError {
|
||||
componentMaxInput = z
|
||||
componentError = thisComponentError
|
||||
}
|
||||
}
|
||||
|
||||
func testWithSymmetry(_ x: Float, _ y: Float) {
|
||||
test(Complex( x-1, y))
|
||||
test(Complex( y-1, x))
|
||||
test(Complex(-y-1, x))
|
||||
test(Complex(-x-1, y))
|
||||
test(Complex(-x-1,-y))
|
||||
test(Complex(-y-1,-x))
|
||||
test(Complex( y-1,-x))
|
||||
test(Complex( x-1,-y))
|
||||
}
|
||||
|
||||
// The hardest to evaluate cases for log are those close to the unit circle
|
||||
// centered at -1, where log(1+z) is nearly zero. We want to have plausibly
|
||||
// dense test coverage close to the circle.
|
||||
let radii: [Float] = [0.9,
|
||||
0.95,
|
||||
0.99,
|
||||
0.999,
|
||||
0.9999,
|
||||
1 - 10 * .ulpOfOne,
|
||||
1,
|
||||
1 + 10 * .ulpOfOne,
|
||||
1.0001,
|
||||
1.001,
|
||||
1.01,
|
||||
1.05,
|
||||
1.1]
|
||||
|
||||
for r in radii {
|
||||
for x in Interval(from: 1/Float.sqrt(2), to: r) {
|
||||
// Generate the two y values that put us closest to the circle of radius r
|
||||
let base = Double.sqrt(Double(r).addingProduct(Double(-x), Double(x)))
|
||||
let a, b: Float
|
||||
if Double(Float(base)) < base { a = Float(base); b = a.nextUp }
|
||||
else { b = Float(base); a = b.nextDown }
|
||||
testWithSymmetry(x, a)
|
||||
testWithSymmetry(x, b)
|
||||
}
|
||||
}
|
||||
|
||||
// Away from the unit circle is "easy" but we still want to get some coverage.
|
||||
// Generate 1 million uniform random points inside the circle, and then test
|
||||
// both z and 1/z.
|
||||
var g = SystemRandomNumberGenerator()
|
||||
var count = 0
|
||||
while count < 1_000_000 {
|
||||
let z = Complex<Float>(.random(in: -1 ... 1, using: &g), .random(in: -1 ... 1, using: &g))
|
||||
if z.length > 1 { continue }
|
||||
count += 1
|
||||
test(z - 1)
|
||||
test(1/z - 1)
|
||||
}
|
||||
|
||||
print("Worst complex norm error seen for log(onePlus:) was \(complexError)")
|
||||
print("For input \(complexMaxInput).")
|
||||
print("Reference result: \(Complex.log(onePlus: Complex<Double>(complexMaxInput)))")
|
||||
print(" Observed result: \(Complex.log(onePlus: complexMaxInput))")
|
||||
|
||||
print("Worst componentwise error seen for log(onePlus:) was \(componentError)")
|
||||
print("For input \(componentMaxInput).")
|
||||
print("Reference result: \(Complex.log(onePlus: Complex<Double>(componentMaxInput)))")
|
||||
print(" Observed result: \(Complex.log(onePlus: componentMaxInput))")
|
||||
|
||||
#endif
|
||||
@@ -1,8 +1,8 @@
|
||||
//===--- DivideTests.swift ------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -11,7 +11,6 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IntegerUtilities
|
||||
import _TestSupport
|
||||
import XCTest
|
||||
|
||||
final class IntegerUtilitiesDivideTests: XCTestCase {
|
||||
@@ -26,14 +25,14 @@ final class IntegerUtilitiesDivideTests: XCTestCase {
|
||||
let ref = a - q*b1 - q*b2
|
||||
if r != ref {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b)) failed the division rule.
|
||||
\(a).divided(by: \(b), rounding: .down) failed the division rule.
|
||||
a - qb was \(ref), but r is \(r).
|
||||
""")
|
||||
return false
|
||||
}
|
||||
if r.magnitude >= b.magnitude {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b)) failed check on r.
|
||||
\(a).divided(by: \(b), rounding: .down) failed check on r.
|
||||
|remainder| must be smaller than |divisor|, but was \(r).
|
||||
""")
|
||||
return false
|
||||
@@ -47,15 +46,6 @@ final class IntegerUtilitiesDivideTests: XCTestCase {
|
||||
// Skip any SignedInt.min / -1 cases, because those will trap.
|
||||
if a == .min && b == -1 { continue }
|
||||
let (q, r) = a.divided(by: b, rounding: .down)
|
||||
let justq = a.divided(by: b, rounding: .down)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .down) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
if divisionRuleHolds(a, b, q, r) {
|
||||
// We know a = bq + r with |r| < |b|. Now validate sign(r) == sign(b).
|
||||
guard r == 0 || r.signum() == b.signum() else {
|
||||
@@ -76,15 +66,6 @@ final class IntegerUtilitiesDivideTests: XCTestCase {
|
||||
// Skip any SignedInt.min / -1 cases, because those will trap.
|
||||
if a == .min && b == -1 { continue }
|
||||
let (q, r) = a.divided(by: b, rounding: .up)
|
||||
let justq = a.divided(by: b, rounding: .up)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .up) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
if divisionRuleHolds(a, b, q, r) {
|
||||
// We know a = bq + r with |r| < |b|. Now validate sign(r) != sign(b).
|
||||
guard r == 0 || r.signum() != b.signum() else {
|
||||
@@ -105,15 +86,6 @@ final class IntegerUtilitiesDivideTests: XCTestCase {
|
||||
// Skip any SignedInt.min / -1 cases, because those will trap.
|
||||
if a == .min && b == -1 { continue }
|
||||
let (q, r) = a.divided(by: b, rounding: .towardZero)
|
||||
let justq = a.divided(by: b, rounding: .towardZero)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .towardZero) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
if divisionRuleHolds(a, b, q, r) {
|
||||
// We know a = bq + r with |r| < |b|. Now validate sign(r) == sign(a).
|
||||
guard r == 0 || r.signum() == a.signum() else {
|
||||
@@ -134,15 +106,6 @@ final class IntegerUtilitiesDivideTests: XCTestCase {
|
||||
// Skip any SignedInt.min / -1 cases, because those will trap.
|
||||
if a == .min && b == -1 { continue }
|
||||
let (q, r) = a.divided(by: b, rounding: .awayFromZero)
|
||||
let justq = a.divided(by: b, rounding: .awayFromZero)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .awayFromZero) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
if divisionRuleHolds(a, b, q, r) {
|
||||
// We know a = bq + r with |r| < |b|. Now validate sign(r) != sign(a).
|
||||
guard r == 0 || r.signum() != a.signum() else {
|
||||
@@ -157,111 +120,19 @@ final class IntegerUtilitiesDivideTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testDivideToNearestOrDown<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
|
||||
func testDivideToOdd<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
|
||||
for a in values {
|
||||
for b in values where b != 0 {
|
||||
// Skip any SignedInt.min / -1 cases, because those will trap.
|
||||
if a == .min && b == -1 { continue }
|
||||
let (q, r) = a.divided(by: b, rounding: .toNearestOrDown)
|
||||
let justq = a.divided(by: b, rounding: .toNearestOrDown)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrDown) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
|
||||
XCTAssertEqual(q, justq)
|
||||
let (q, r) = a.divided(by: b, rounding: .toOdd)
|
||||
if divisionRuleHolds(a, b, q, r) {
|
||||
// We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2
|
||||
// with equality only if q rounded down.
|
||||
if 2*r.magnitude > b.magnitude {
|
||||
// We know a = bq + r with |r| < |b|. Now validate q is odd if r is
|
||||
// non-zero.
|
||||
guard r == 0 || q & 1 == 1 else {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrDown) failed check:
|
||||
|remainder| must be less than or equal to |divisor|/2, but remainder was \(r).
|
||||
""")
|
||||
return
|
||||
}
|
||||
if 2*r.magnitude == b.magnitude && r.signum() != b.signum() {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrDown) failed check:
|
||||
If |remainder| equals |divisor|/2, remainder must have same sign as divisor, but was \(r).
|
||||
""")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDivideToNearestOrUp<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
|
||||
for a in values {
|
||||
for b in values where b != 0 {
|
||||
// Skip any SignedInt.min / -1 cases, because those will trap.
|
||||
if a == .min && b == -1 { continue }
|
||||
let (q, r) = a.divided(by: b, rounding: .toNearestOrUp)
|
||||
let justq = a.divided(by: b, rounding: .toNearestOrUp)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrUp) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
if divisionRuleHolds(a, b, q, r) {
|
||||
// We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2
|
||||
// with equality only if q rounded up.
|
||||
if 2*r.magnitude > b.magnitude {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrUp) failed check:
|
||||
|remainder| must be less than or equal to |divisor|/2, but remainder was \(r).
|
||||
""")
|
||||
return
|
||||
}
|
||||
if 2*r.magnitude == b.magnitude && r.signum() == b.signum() {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrUp) failed check:
|
||||
If |remainder| equals |divisor|/2, remainder must have opposite sign of divisor, but was \(r).
|
||||
""")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDivideToNearestOrZero<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
|
||||
for a in values {
|
||||
for b in values where b != 0 {
|
||||
// Skip any SignedInt.min / -1 cases, because those will trap.
|
||||
if a == .min && b == -1 { continue }
|
||||
let (q, r) = a.divided(by: b, rounding: .toNearestOrZero)
|
||||
let justq = a.divided(by: b, rounding: .toNearestOrZero)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrZero) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
if divisionRuleHolds(a, b, q, r) {
|
||||
// We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2
|
||||
// with equality only if sign(r) == sign(a).
|
||||
if 2*r.magnitude > b.magnitude {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrZero) failed check:
|
||||
|remainder| must be less than or equal to |divisor|/2, but remainder was \(r).
|
||||
""")
|
||||
return
|
||||
}
|
||||
if 2*r.magnitude == b.magnitude && r.signum() != a.signum() {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrZero) failed check:
|
||||
If |remainder| equals |divisor|/2, remainder must match sign of dividend, but was \(r).
|
||||
\(a).divided(by: \(b), rounding: .toOdd) failed check:
|
||||
quotient must be odd if remainder is non-zero, but quotient was \(q) and remainder was \(r).
|
||||
""")
|
||||
return
|
||||
}
|
||||
@@ -275,29 +146,20 @@ final class IntegerUtilitiesDivideTests: XCTestCase {
|
||||
for b in values where b != 0 {
|
||||
// Skip any SignedInt.min / -1 cases, because those will trap.
|
||||
if a == .min && b == -1 { continue }
|
||||
let (q, r) = a.divided(by: b, rounding: .toNearestOrAway)
|
||||
let justq = a.divided(by: b, rounding: .toNearestOrAway)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrAway) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
let (q, r) = a.divided(by: b, rounding: .toNearestOrAwayFromZero)
|
||||
if divisionRuleHolds(a, b, q, r) {
|
||||
// We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2
|
||||
// with equality only if sign(r) != sign(a).
|
||||
if 2*r.magnitude > b.magnitude {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrAway) failed check:
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrAwayFromZero) failed check:
|
||||
|remainder| must be less than or equal to |divisor|/2, but remainder was \(r).
|
||||
""")
|
||||
return
|
||||
}
|
||||
if 2*r.magnitude == b.magnitude && r.signum() == a.signum() {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrAway) failed check:
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrAwayFromZero) failed check:
|
||||
If |remainder| equals |divisor|/2, remainder must oppose sign of dividend, but was \(r).
|
||||
""")
|
||||
return
|
||||
@@ -313,18 +175,9 @@ final class IntegerUtilitiesDivideTests: XCTestCase {
|
||||
// Skip any SignedInt.min / -1 cases, because those will trap.
|
||||
if a == .min && b == -1 { continue }
|
||||
let (q, r) = a.divided(by: b, rounding: .toNearestOrEven)
|
||||
let justq = a.divided(by: b, rounding: .toNearestOrEven)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrEven) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
if divisionRuleHolds(a, b, q, r) {
|
||||
// We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2
|
||||
// with equality only if q is even.
|
||||
// with equality only if sign(r) != sign(a).
|
||||
if 2*r.magnitude > b.magnitude {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toNearestOrEven) failed check:
|
||||
@@ -344,32 +197,13 @@ final class IntegerUtilitiesDivideTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testDivideToOdd<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
|
||||
func testDivideStochastic<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
|
||||
for a in values {
|
||||
for b in values where b != 0 {
|
||||
// Skip any SignedInt.min / -1 cases, because those will trap.
|
||||
if a == .min && b == -1 { continue }
|
||||
let (q, r) = a.divided(by: b, rounding: .toOdd)
|
||||
let justq = a.divided(by: b, rounding: .toOdd)
|
||||
if q != justq {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toOdd) failed check:
|
||||
BinaryInteger overload did not produce the same quotient as SignedInteger.
|
||||
BinaryInteger result was \(justq), but SignedInteger was \(q).
|
||||
""")
|
||||
return
|
||||
}
|
||||
if divisionRuleHolds(a, b, q, r) {
|
||||
// We know a = bq + r with |r| < |b|. Now validate q is odd if r is
|
||||
// non-zero.
|
||||
guard r == 0 || q & 1 == 1 else {
|
||||
XCTFail("""
|
||||
\(a).divided(by: \(b), rounding: .toOdd) failed check:
|
||||
quotient must be odd if remainder is non-zero, but quotient was \(q) and remainder was \(r).
|
||||
""")
|
||||
return
|
||||
}
|
||||
}
|
||||
let (q, r) = a.divided(by: b, rounding: .stochastically)
|
||||
let _ = divisionRuleHolds(a, b, q, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -395,12 +229,10 @@ final class IntegerUtilitiesDivideTests: XCTestCase {
|
||||
testDivideUp(values)
|
||||
testDivideTowardZero(values)
|
||||
testDivideAwayFromZero(values)
|
||||
testDivideToNearestOrDown(values)
|
||||
testDivideToNearestOrUp(values)
|
||||
testDivideToNearestOrZero(values)
|
||||
testDivideToOdd(values)
|
||||
testDivideToNearestOrAway(values)
|
||||
testDivideToNearestOrEven(values)
|
||||
testDivideToOdd(values)
|
||||
testDivideStochastic(values)
|
||||
testDivideExact(values)
|
||||
}
|
||||
|
||||
@@ -415,32 +247,10 @@ final class IntegerUtilitiesDivideTests: XCTestCase {
|
||||
testDivideUp(values)
|
||||
testDivideTowardZero(values)
|
||||
testDivideAwayFromZero(values)
|
||||
testDivideToNearestOrDown(values)
|
||||
testDivideToNearestOrUp(values)
|
||||
testDivideToNearestOrZero(values)
|
||||
testDivideToOdd(values)
|
||||
testDivideToNearestOrAway(values)
|
||||
testDivideToNearestOrEven(values)
|
||||
testDivideToOdd(values)
|
||||
testDivideExact(values)
|
||||
}
|
||||
|
||||
func testDivideInt128() {
|
||||
var values = [DoubleWidth<Int64>](repeating: 0, count: 64)
|
||||
for i in 0 ..< values.count {
|
||||
while values[i] == 0 {
|
||||
values[i] = .random(in: .min ... .max)
|
||||
}
|
||||
}
|
||||
testDivideDown(values)
|
||||
testDivideUp(values)
|
||||
testDivideTowardZero(values)
|
||||
testDivideAwayFromZero(values)
|
||||
testDivideToNearestOrDown(values)
|
||||
testDivideToNearestOrUp(values)
|
||||
testDivideToNearestOrZero(values)
|
||||
testDivideToNearestOrAway(values)
|
||||
testDivideToNearestOrEven(values)
|
||||
testDivideToOdd(values)
|
||||
testDivideStochastic(values)
|
||||
testDivideExact(values)
|
||||
}
|
||||
|
||||
@@ -465,20 +275,80 @@ final class IntegerUtilitiesDivideTests: XCTestCase {
|
||||
divideUInt8(a, b, rounding: .up)
|
||||
divideUInt8(a, b, rounding: .towardZero)
|
||||
divideUInt8(a, b, rounding: .awayFromZero)
|
||||
divideUInt8(a, b, rounding: .toNearestOrDown)
|
||||
divideUInt8(a, b, rounding: .toNearestOrUp)
|
||||
divideUInt8(a, b, rounding: .toNearestOrZero)
|
||||
divideUInt8(a, b, rounding: .toNearestOrAway)
|
||||
divideUInt8(a, b, rounding: .toNearestOrEven)
|
||||
divideUInt8(a, b, rounding: .toOdd)
|
||||
divideUInt8(a, b, rounding: .toNearestOrAwayFromZero)
|
||||
divideUInt8(a, b, rounding: .toNearestOrEven)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stochastically rounding doesn't have a deterministic "expected" answer,
|
||||
// but we know that the result must be either the floor or the ceiling.
|
||||
// The above tests ensure that, but that's not a very strong guarantee;
|
||||
// an implementation could just implement it as self / other and pass
|
||||
// that test.
|
||||
//
|
||||
// Here we round the _same_ value many times, compute the average, and
|
||||
// check that it is acceptably close to the exact expected value; simple
|
||||
// use of any deterministic rounding rule will not achieve this.
|
||||
func testStochasticDivide<T: FixedWidthInteger>(_ a: T, _ b: T) -> Bool {
|
||||
let sum = (0..<1024).reduce(into: 0.0) { sum, _ in
|
||||
let rounded = a.divided(by: b, rounding: .stochastically)
|
||||
sum += Double(rounded)
|
||||
}
|
||||
let expected = 1024 * Double(a) / Double(b)
|
||||
let difference = abs(sum - expected)
|
||||
// Waving my hands slightly instead of giving a precise explanation
|
||||
// here, the expectation is that difference should be about
|
||||
// 1/2 sqrt(1024). If we're more than a couple standard deviations
|
||||
// off, we should flag that. This isn't _necessarily_ a problem,
|
||||
// but if you see a repeated failure, that's almost surely a real bug.
|
||||
//
|
||||
// TODO: precise justification of thresholds
|
||||
XCTAssertLessThanOrEqual(difference, 64,
|
||||
"Accumulated error (\(difference)) was unexpectedly large in \(a).divided(by: \(b))"
|
||||
)
|
||||
return difference > 16
|
||||
}
|
||||
|
||||
func testDivideStochasticInt8() {
|
||||
var values = [Int8](repeating: 0, count: 32)
|
||||
for i in 0 ..< values.count {
|
||||
while values[i] == 0 {
|
||||
values[i] = .random(in: .min ... .max)
|
||||
}
|
||||
}
|
||||
var fails = 0
|
||||
for a in values {
|
||||
for b in values {
|
||||
if a == .min && b == -1 { continue }
|
||||
fails += testStochasticDivide(a, b) ? 1 : 0
|
||||
}
|
||||
}
|
||||
XCTAssertLessThanOrEqual(fails, 32*16)
|
||||
}
|
||||
|
||||
func testDivideStochasticUInt32() {
|
||||
var values = [UInt32](repeating: 0, count: 32)
|
||||
for i in 0 ..< values.count {
|
||||
while values[i] == 0 {
|
||||
values[i] = .random(in: .min ... .max)
|
||||
}
|
||||
}
|
||||
var fails = 0
|
||||
for a in values {
|
||||
for b in values {
|
||||
fails += testStochasticDivide(a, b) ? 1 : 0
|
||||
}
|
||||
}
|
||||
XCTAssertLessThanOrEqual(fails, 32*16)
|
||||
}
|
||||
|
||||
func testRemainderByMinusOne() {
|
||||
// These would trap if implemented as a - bq or similar, even though
|
||||
// the remainder is well-defined.
|
||||
XCTAssertEqual(0, Int.min.remainder(dividingBy: -1))
|
||||
XCTAssertEqual(0, Int.min.remainder(dividingBy: -1, rounding: .up))
|
||||
XCTAssertEqual(0, Int.min.remainder(dividingBy: -1, rounding: .stochastically))
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2017-2024 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2017-2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -522,8 +522,4 @@ final class DoubleWidthTests: XCTestCase {
|
||||
checkUnsignedIntegerConformance(0 as _UInt128)
|
||||
checkUnsignedIntegerConformance(0 as _UInt1024)
|
||||
}
|
||||
|
||||
func testMultiplyOverflow() {
|
||||
XCTAssertFalse(_Int128(-1).multipliedReportingOverflow(by: 0).overflow)
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
//===--- GCDTests.swift ---------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//===--- RotateTests.swift ------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
//===--- RoundingTests.swift ----------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2024 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IntegerUtilities
|
||||
import _TestSupport
|
||||
import XCTest
|
||||
|
||||
final class IntegerUtilitiesRoundingTests: XCTestCase {
|
||||
func testRoundingDirected<T: BinaryFloatingPoint>(_ type: T.Type) {
|
||||
let inf = T.infinity
|
||||
let gfm = T.greatestFiniteMagnitude
|
||||
let big: T = 1 / .ulpOfOne
|
||||
let two: T = 2
|
||||
let threeHalves: T = 1.5
|
||||
let one: T = 1
|
||||
let half: T = 0.5
|
||||
let nrm = T.leastNormalMagnitude
|
||||
let lnm = T.leastNonzeroMagnitude
|
||||
let vectors: [(input: T, down: T, up: T, zero: T, away: T)] = [
|
||||
(-inf, -inf, -inf, -inf, -inf),
|
||||
(-gfm, -gfm, -gfm, -gfm, -gfm),
|
||||
(-big.nextUp, -big-1, -big-1, -big-1, -big-1),
|
||||
(-big, -big, -big, -big, -big),
|
||||
(-big.nextDown, -big, -big+1, -big+1, -big),
|
||||
(-two, -two, -two, -two, -two),
|
||||
(-two.nextDown, -two, -one, -one, -two),
|
||||
(-threeHalves.nextUp, -two, -one, -one, -two),
|
||||
(-threeHalves, -two, -one, -one, -two),
|
||||
(-threeHalves.nextDown, -two, -one, -one, -two),
|
||||
(-one.nextUp, -two, -one, -one, -two),
|
||||
(-one, -one, -one, -one, -one),
|
||||
(-one.nextDown, -one, 0, 0, -one),
|
||||
(-half.nextUp, -one, 0, 0, -one),
|
||||
(-half, -one, 0, 0, -one),
|
||||
(-half.nextDown, -one, 0, 0, -one),
|
||||
(-nrm, -one, 0, 0, -one),
|
||||
(-lnm, -one, 0, 0, -one),
|
||||
(-.zero, 0, 0, 0, 0),
|
||||
( .zero, 0, 0, 0, 0),
|
||||
( lnm, 0, one, 0, one),
|
||||
( nrm, 0, one, 0, one),
|
||||
( half.nextDown, 0, one, 0, one),
|
||||
( half, 0, one, 0, one),
|
||||
( half.nextUp, 0, one, 0, one),
|
||||
( one.nextDown, 0, one, 0, one),
|
||||
( one, one, one, one, one),
|
||||
( one.nextUp, one, two, one, two),
|
||||
( threeHalves.nextDown, one, two, one, two),
|
||||
( threeHalves, one, two, one, two),
|
||||
( threeHalves.nextUp, one, two, one, two),
|
||||
( two.nextDown, one, two, one, two),
|
||||
( two, two, two, two, two),
|
||||
( big.nextDown, big-1, big, big-1, big),
|
||||
( big, big, big, big, big),
|
||||
( big.nextUp, big+1, big+1, big+1, big+1),
|
||||
( gfm, gfm, gfm, gfm, gfm),
|
||||
( inf, inf, inf, inf, inf),
|
||||
]
|
||||
for vector in vectors {
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.down), vector.down)
|
||||
if vector.down == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.down).sign, vector.input.sign)
|
||||
}
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.up), vector.up)
|
||||
if vector.up == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.up).sign, vector.input.sign)
|
||||
}
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.towardZero), vector.zero)
|
||||
if vector.zero == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.towardZero).sign, vector.input.sign)
|
||||
}
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.awayFromZero), vector.away)
|
||||
if vector.away == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.awayFromZero).sign, vector.input.sign)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testRoundingDirected() {
|
||||
testRoundingDirected(Float.self)
|
||||
testRoundingDirected(Double.self)
|
||||
}
|
||||
|
||||
func testRoundingNearest<T: BinaryFloatingPoint>(_ type: T.Type) {
|
||||
let inf = T.infinity
|
||||
let gfm = T.greatestFiniteMagnitude
|
||||
let big: T = 1 / .ulpOfOne
|
||||
let two: T = 2
|
||||
let threeHalves: T = 1.5
|
||||
let one: T = 1
|
||||
let half: T = 0.5
|
||||
let nrm = T.leastNormalMagnitude
|
||||
let lnm = T.leastNonzeroMagnitude
|
||||
let vectors: [(input: T, down: T, up: T, zero: T, away: T, even: T)] = [
|
||||
(-inf, -inf, -inf, -inf, -inf, -inf),
|
||||
(-gfm, -gfm, -gfm, -gfm, -gfm, -gfm),
|
||||
(-big.nextUp, -big-1, -big-1, -big-1, -big-1, -big-1),
|
||||
(-big, -big, -big, -big, -big, -big),
|
||||
(-big.nextDown, -big, -big+1, -big+1, -big, -big),
|
||||
(-two, -two, -two, -two, -two, -two),
|
||||
(-two.nextDown, -two, -two, -two, -two, -two),
|
||||
(-threeHalves.nextUp, -two, -two, -two, -two, -two),
|
||||
(-threeHalves, -two, -one, -one, -two, -two),
|
||||
(-threeHalves.nextDown, -one, -one, -one, -one, -one),
|
||||
(-one.nextUp, -one, -one, -one, -one, -one),
|
||||
(-one, -one, -one, -one, -one, -one),
|
||||
(-one.nextDown, -one, -one, -one, -one, -one),
|
||||
(-half.nextUp, -one, -one, -one, -one, -one),
|
||||
(-half, -one, 0, 0, -one, 0),
|
||||
(-half.nextDown, 0, 0, 0, 0, 0),
|
||||
(-nrm, 0, 0, 0, 0, 0),
|
||||
(-lnm, 0, 0, 0, 0, 0),
|
||||
(-.zero, 0, 0, 0, 0, 0),
|
||||
( .zero, 0, 0, 0, 0, 0),
|
||||
( lnm, 0, 0, 0, 0, 0),
|
||||
( nrm, 0, 0, 0, 0, 0),
|
||||
( half.nextDown, 0, 0, 0, 0, 0),
|
||||
( half, 0, one, 0, one, 0),
|
||||
( half.nextUp, one, one, one, one, one),
|
||||
( one.nextDown, one, one, one, one, one),
|
||||
( one, one, one, one, one, one),
|
||||
( one.nextUp, one, one, one, one, one),
|
||||
( threeHalves.nextDown, one, one, one, one, one),
|
||||
( threeHalves, one, two, one, two, two),
|
||||
( threeHalves.nextUp, two, two, two, two, two),
|
||||
( two.nextDown, two, two, two, two, two),
|
||||
( two, two, two, two, two, two),
|
||||
( big.nextDown, big-1, big, big-1, big, big),
|
||||
( big, big, big, big, big, big),
|
||||
( big.nextUp, big+1, big+1, big+1, big+1, big+1),
|
||||
( gfm, gfm, gfm, gfm, gfm, gfm),
|
||||
( inf, inf, inf, inf, inf, inf),
|
||||
]
|
||||
for vector in vectors {
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrDown), vector.down, "\(vector.input).rounding(.toNearestOrDown)")
|
||||
if vector.down == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrDown).sign, vector.input.sign, "\(vector.input).rounding(.toNearestOrDown)")
|
||||
}
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrUp), vector.up, "\(vector.input).rounding(.toNearestOrUp)")
|
||||
if vector.up == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrUp).sign, vector.input.sign, "\(vector.input).rounding(.toNearestOrUp)")
|
||||
}
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrZero), vector.zero, "\(vector.input).rounding(.toNearestOrZero)")
|
||||
if vector.zero == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrZero).sign, vector.input.sign, "\(vector.input).rounding(.toNearestOrZero)")
|
||||
}
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrAway), vector.away, "\(vector.input).rounding(.toNearestOrAway)")
|
||||
if vector.away == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrAway).sign, vector.input.sign, "\(vector.input).rounding(.toNearestOrAway)")
|
||||
}
|
||||
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrEven), vector.even, "\(vector.input).rounding(.toNearestOrEven)")
|
||||
if vector.even == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.toNearestOrEven).sign, vector.input.sign, "\(vector.input).rounding(.toNearestOrEven)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testRoundingNearest() {
|
||||
testRoundingNearest(Float.self)
|
||||
testRoundingNearest(Double.self)
|
||||
}
|
||||
|
||||
func testRoundingOdd<T: BinaryFloatingPoint>(_ type: T.Type) {
|
||||
let inf = T.infinity
|
||||
let gfm = T.greatestFiniteMagnitude
|
||||
let big: T = 1 / .ulpOfOne
|
||||
let two: T = 2
|
||||
let threeHalves: T = 1.5
|
||||
let one: T = 1
|
||||
let half: T = 0.5
|
||||
let nrm = T.leastNormalMagnitude
|
||||
let lnm = T.leastNonzeroMagnitude
|
||||
let vectors: [(input: T, odd: T)] = [
|
||||
(-inf, -inf),
|
||||
(-gfm, -gfm),
|
||||
(-big.nextUp, -big-1),
|
||||
(-big, -big),
|
||||
(-big.nextDown, -big+1),
|
||||
(-two, -two),
|
||||
(-two.nextDown, -one),
|
||||
(-threeHalves.nextUp, -one),
|
||||
(-threeHalves, -one),
|
||||
(-threeHalves.nextDown, -one),
|
||||
(-one.nextUp, -one),
|
||||
(-one, -one),
|
||||
(-one.nextDown, -one),
|
||||
(-half.nextUp, -one),
|
||||
(-half, -one),
|
||||
(-half.nextDown, -one),
|
||||
(-nrm, -one),
|
||||
(-lnm, -one),
|
||||
(-.zero, 0),
|
||||
( .zero, 0),
|
||||
( lnm, one),
|
||||
( nrm, one),
|
||||
( half.nextDown, one),
|
||||
( half, one),
|
||||
( half.nextUp, one),
|
||||
( one.nextDown, one),
|
||||
( one, one),
|
||||
( one.nextUp, one),
|
||||
( threeHalves.nextDown, one),
|
||||
( threeHalves, one),
|
||||
( threeHalves.nextUp, one),
|
||||
( two.nextDown, one),
|
||||
( two, two),
|
||||
( big.nextDown, big-1),
|
||||
( big, big),
|
||||
( big.nextUp, big+1),
|
||||
( gfm, gfm),
|
||||
( inf, inf)
|
||||
]
|
||||
for vector in vectors {
|
||||
XCTAssertEqual(vector.input.rounding(.toOdd), vector.odd, "\(vector.input).rounding(.toOdd)")
|
||||
if vector.odd == 0 {
|
||||
XCTAssertEqual(vector.input.rounding(.toOdd).sign, vector.input.sign, "\(vector.input).rounding(.toOdd)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testRoundingOdd() {
|
||||
testRoundingOdd(Float.self)
|
||||
testRoundingOdd(Double.self)
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
//===--- SaturatingArithmeticTests.swift ----------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2023 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2023 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//===--- ShiftTests.swift -------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2021-2024 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -24,44 +24,20 @@ final class IntegerUtilitiesShiftTests: XCTestCase {
|
||||
let exact = count <= 0 || lost == 0
|
||||
let ceiling = exact ? floor : floor &+ 1
|
||||
let expected: T
|
||||
if exact { expected = floor }
|
||||
else {
|
||||
switch rule {
|
||||
case .down:
|
||||
expected = floor
|
||||
case .up:
|
||||
expected = ceiling
|
||||
case .towardZero:
|
||||
expected = value < 0 ? ceiling : floor
|
||||
case .awayFromZero:
|
||||
expected = value > 0 ? ceiling : floor
|
||||
case .toOdd:
|
||||
expected = floor | (exact ? 0 : 1)
|
||||
case .toNearestOrDown:
|
||||
let step = value.shifted(rightBy: count - 2, rounding: .toOdd)
|
||||
switch step & 0b11 {
|
||||
case 0b01: expected = floor
|
||||
case 0b10: expected = floor
|
||||
case 0b11: expected = ceiling
|
||||
default: preconditionFailure()
|
||||
}
|
||||
case .toNearestOrUp:
|
||||
let step = value.shifted(rightBy: count - 2, rounding: .toOdd)
|
||||
switch step & 0b11 {
|
||||
case 0b01: expected = floor
|
||||
case 0b10: expected = ceiling
|
||||
case 0b11: expected = ceiling
|
||||
default: preconditionFailure()
|
||||
}
|
||||
case .toNearestOrZero:
|
||||
let step = value.shifted(rightBy: count - 2, rounding: .toOdd)
|
||||
switch step & 0b11 {
|
||||
case 0b01: expected = floor
|
||||
case 0b10: expected = value > 0 ? floor : ceiling
|
||||
case 0b11: expected = ceiling
|
||||
default: preconditionFailure()
|
||||
}
|
||||
case .toNearestOrAway:
|
||||
switch rule {
|
||||
case .down:
|
||||
expected = floor
|
||||
case .up:
|
||||
expected = ceiling
|
||||
case .towardZero:
|
||||
expected = value < 0 ? ceiling : floor
|
||||
case .awayFromZero:
|
||||
expected = value > 0 ? ceiling : floor
|
||||
case .toOdd:
|
||||
expected = floor | (exact ? 0 : 1)
|
||||
case .toNearestOrAwayFromZero:
|
||||
if exact { expected = floor }
|
||||
else {
|
||||
let step = value.shifted(rightBy: count - 2, rounding: .toOdd)
|
||||
switch step & 0b11 {
|
||||
case 0b01: expected = floor
|
||||
@@ -69,7 +45,10 @@ final class IntegerUtilitiesShiftTests: XCTestCase {
|
||||
case 0b11: expected = ceiling
|
||||
default: preconditionFailure()
|
||||
}
|
||||
case .toNearestOrEven:
|
||||
}
|
||||
case .toNearestOrEven:
|
||||
if exact { expected = floor }
|
||||
else {
|
||||
let step = value.shifted(rightBy: count - 2, rounding: .toOdd)
|
||||
switch step & 0b11 {
|
||||
case 0b01: expected = floor
|
||||
@@ -77,79 +56,142 @@ final class IntegerUtilitiesShiftTests: XCTestCase {
|
||||
case 0b11: expected = ceiling
|
||||
default: preconditionFailure()
|
||||
}
|
||||
case .requireExact:
|
||||
preconditionFailure()
|
||||
}
|
||||
let observed = value.shifted(rightBy: count, rounding: rule)
|
||||
if observed != expected {
|
||||
print("Error found in \(T.self).shifted(rightBy: \(count), rounding: \(rule)).")
|
||||
print(" Value: \(String(value, radix: 2))")
|
||||
print("Expected: \(String(expected, radix: 2))")
|
||||
print("Observed: \(String(observed, radix: 2))")
|
||||
XCTFail()
|
||||
case .stochastically:
|
||||
// Just test that it's floor if exact, otherwise either floor
|
||||
// or ceiling.
|
||||
if exact { expected = floor }
|
||||
else {
|
||||
let observed = value.shifted(rightBy: count, rounding: rule)
|
||||
if observed != floor && observed != ceiling {
|
||||
print("Error found in \(T.self).shifted(rightBy: \(count), rounding: \(rule)).")
|
||||
print(" Value: \(String(value, radix: 16))")
|
||||
print("Expected: \(String(floor, radix: 16)) or \(String(ceiling, radix: 16))")
|
||||
print("Observed: \(String(observed, radix: 16))")
|
||||
XCTFail()
|
||||
}
|
||||
return
|
||||
}
|
||||
case .requireExact:
|
||||
preconditionFailure()
|
||||
}
|
||||
let observed = value.shifted(rightBy: count, rounding: rule)
|
||||
if observed != expected {
|
||||
print("Error found in \(T.self).shifted(rightBy: \(count), rounding: \(rule)).")
|
||||
print(" Value: \(String(value, radix: 16))")
|
||||
print("Expected: \(String(expected, radix: 16))")
|
||||
print("Observed: \(String(observed, radix: 16))")
|
||||
XCTFail()
|
||||
}
|
||||
}
|
||||
|
||||
func testRoundingShift<T: FixedWidthInteger>(
|
||||
_ type: T.Type, rounding rule: RoundingRule
|
||||
) {
|
||||
for count in -2*T.bitWidth ... 2*T.bitWidth {
|
||||
// zero shifted by anything is always zero
|
||||
XCTAssertEqual(0, (0 as T).shifted(rightBy: count, rounding: rule))
|
||||
for _ in 0 ..< 100 {
|
||||
testRoundingShift(T.random(in: .min ... .max), count, rounding: rule)
|
||||
}
|
||||
}
|
||||
|
||||
for count in Int8.min ... .max {
|
||||
|
||||
func testRoundingShift<T: FixedWidthInteger>(
|
||||
_ type: T.Type, rounding rule: RoundingRule
|
||||
) {
|
||||
for count in -2*T.bitWidth ... 2*T.bitWidth {
|
||||
// zero shifted by anything is always zero
|
||||
XCTAssertEqual(0, (0 as T).shifted(rightBy: count, rounding: rule))
|
||||
for _ in 0 ..< 100 {
|
||||
testRoundingShift(T.random(in: .min ... .max), count, rounding: rule)
|
||||
}
|
||||
}
|
||||
|
||||
func testRoundingShifts() {
|
||||
testRoundingShift(Int8.self, rounding: .down)
|
||||
testRoundingShift(Int8.self, rounding: .up)
|
||||
testRoundingShift(Int8.self, rounding: .towardZero)
|
||||
testRoundingShift(Int8.self, rounding: .awayFromZero)
|
||||
testRoundingShift(Int8.self, rounding: .toNearestOrUp)
|
||||
testRoundingShift(Int8.self, rounding: .toNearestOrDown)
|
||||
testRoundingShift(Int8.self, rounding: .toNearestOrZero)
|
||||
testRoundingShift(Int8.self, rounding: .toNearestOrAway)
|
||||
testRoundingShift(Int8.self, rounding: .toNearestOrEven)
|
||||
testRoundingShift(Int8.self, rounding: .toOdd)
|
||||
|
||||
testRoundingShift(UInt8.self, rounding: .down)
|
||||
testRoundingShift(UInt8.self, rounding: .up)
|
||||
testRoundingShift(UInt8.self, rounding: .towardZero)
|
||||
testRoundingShift(UInt8.self, rounding: .awayFromZero)
|
||||
testRoundingShift(UInt8.self, rounding: .toNearestOrUp)
|
||||
testRoundingShift(UInt8.self, rounding: .toNearestOrDown)
|
||||
testRoundingShift(UInt8.self, rounding: .toNearestOrZero)
|
||||
testRoundingShift(UInt8.self, rounding: .toNearestOrAway)
|
||||
testRoundingShift(UInt8.self, rounding: .toNearestOrEven)
|
||||
testRoundingShift(UInt8.self, rounding: .toOdd)
|
||||
|
||||
testRoundingShift(Int.self, rounding: .down)
|
||||
testRoundingShift(Int.self, rounding: .up)
|
||||
testRoundingShift(Int.self, rounding: .towardZero)
|
||||
testRoundingShift(Int.self, rounding: .awayFromZero)
|
||||
testRoundingShift(Int.self, rounding: .toNearestOrUp)
|
||||
testRoundingShift(Int.self, rounding: .toNearestOrDown)
|
||||
testRoundingShift(Int.self, rounding: .toNearestOrZero)
|
||||
testRoundingShift(Int.self, rounding: .toNearestOrAway)
|
||||
testRoundingShift(Int.self, rounding: .toNearestOrEven)
|
||||
testRoundingShift(Int.self, rounding: .toOdd)
|
||||
|
||||
testRoundingShift(UInt.self, rounding: .down)
|
||||
testRoundingShift(UInt.self, rounding: .up)
|
||||
testRoundingShift(UInt.self, rounding: .towardZero)
|
||||
testRoundingShift(UInt.self, rounding: .awayFromZero)
|
||||
testRoundingShift(UInt.self, rounding: .toNearestOrUp)
|
||||
testRoundingShift(UInt.self, rounding: .toNearestOrDown)
|
||||
testRoundingShift(UInt.self, rounding: .toNearestOrZero)
|
||||
testRoundingShift(UInt.self, rounding: .toNearestOrAway)
|
||||
testRoundingShift(UInt.self, rounding: .toNearestOrEven)
|
||||
testRoundingShift(UInt.self, rounding: .toOdd)
|
||||
for count in Int8.min ... .max {
|
||||
testRoundingShift(T.random(in: .min ... .max), count, rounding: rule)
|
||||
}
|
||||
}
|
||||
|
||||
func testRoundingShifts() {
|
||||
testRoundingShift(Int8.self, rounding: .down)
|
||||
testRoundingShift(Int8.self, rounding: .up)
|
||||
testRoundingShift(Int8.self, rounding: .towardZero)
|
||||
testRoundingShift(Int8.self, rounding: .awayFromZero)
|
||||
testRoundingShift(Int8.self, rounding: .toOdd)
|
||||
testRoundingShift(Int8.self, rounding: .toNearestOrAwayFromZero)
|
||||
testRoundingShift(Int8.self, rounding: .toNearestOrEven)
|
||||
testRoundingShift(Int8.self, rounding: .stochastically)
|
||||
|
||||
testRoundingShift(UInt8.self, rounding: .down)
|
||||
testRoundingShift(UInt8.self, rounding: .up)
|
||||
testRoundingShift(UInt8.self, rounding: .towardZero)
|
||||
testRoundingShift(UInt8.self, rounding: .awayFromZero)
|
||||
testRoundingShift(UInt8.self, rounding: .toOdd)
|
||||
testRoundingShift(UInt8.self, rounding: .toNearestOrAwayFromZero)
|
||||
testRoundingShift(UInt8.self, rounding: .toNearestOrEven)
|
||||
testRoundingShift(UInt8.self, rounding: .stochastically)
|
||||
|
||||
testRoundingShift(Int.self, rounding: .down)
|
||||
testRoundingShift(Int.self, rounding: .up)
|
||||
testRoundingShift(Int.self, rounding: .towardZero)
|
||||
testRoundingShift(Int.self, rounding: .awayFromZero)
|
||||
testRoundingShift(Int.self, rounding: .toOdd)
|
||||
testRoundingShift(Int.self, rounding: .toNearestOrAwayFromZero)
|
||||
testRoundingShift(Int.self, rounding: .toNearestOrEven)
|
||||
testRoundingShift(Int.self, rounding: .stochastically)
|
||||
|
||||
testRoundingShift(UInt.self, rounding: .down)
|
||||
testRoundingShift(UInt.self, rounding: .up)
|
||||
testRoundingShift(UInt.self, rounding: .towardZero)
|
||||
testRoundingShift(UInt.self, rounding: .awayFromZero)
|
||||
testRoundingShift(UInt.self, rounding: .toOdd)
|
||||
testRoundingShift(UInt.self, rounding: .toNearestOrAwayFromZero)
|
||||
testRoundingShift(UInt.self, rounding: .toNearestOrEven)
|
||||
testRoundingShift(UInt.self, rounding: .stochastically)
|
||||
}
|
||||
|
||||
// Stochastic rounding doesn't have a deterministic "expected" answer,
|
||||
// but we know that the result must be either the floor or the ceiling.
|
||||
// The above tests ensure that, but that's not a very strong guarantee;
|
||||
// an implementation could just implement it as self >> count and pass
|
||||
// that test.
|
||||
//
|
||||
// Here we round the _same_ value many times, compute the average, and
|
||||
// check that it is acceptably close to the exact expected value; simple
|
||||
// use of any deterministic rounding rule will not achieve this.
|
||||
func testStochasticAverage<T: FixedWidthInteger>(_ value: T) {
|
||||
var fails = 0
|
||||
for count in 1 ... T.bitWidth {
|
||||
let sum = (0..<256).reduce(into: DoubleWidth<T>.zero) { sum, _ in
|
||||
let rounded = value.shifted(rightBy: count, rounding: .stochastically)
|
||||
sum += DoubleWidth(rounded)
|
||||
}
|
||||
let expected = DoubleWidth<T>(value) << (8 - count)
|
||||
let difference = sum >= expected ? sum - expected : expected - sum
|
||||
// Waving my hands slightly instead of giving a precise explanation
|
||||
// here, the expectation is that difference should be about
|
||||
// 1/2 sqrt(256). If it's repeatedly bigger than that, we _may_
|
||||
// have a problem, but it's OK for this to fail occasionally.
|
||||
//
|
||||
// TODO: precise justification of thresholds
|
||||
if difference > 8 { fails += 1 }
|
||||
// On the other hand, if we're more than a couple standard deviations
|
||||
// off, we should flag that. This still isn't _necessarily_ a problem,
|
||||
// but if you see a repeated failure for a given shift count, that's
|
||||
// almost surely a real bug.
|
||||
XCTAssertLessThanOrEqual(difference, 32,
|
||||
"Accumulated error (\(difference)) was unexpectedly large in \(value).shifted(rightBy: \(count))"
|
||||
)
|
||||
}
|
||||
// Threshold chosen so that this is expected to _usually_ pass, but
|
||||
// it will fail sporadically even with a correct implementation. This is
|
||||
// not a great fit for CI workflows, sorry. Basically ignore one-off
|
||||
// failures, but a repeated failure here is an indication that a bug
|
||||
// exists.
|
||||
XCTAssertLessThanOrEqual(fails, T.bitWidth/2,
|
||||
"Accumulated error was large more often than expected for \(value).shifted(rightBy:)"
|
||||
)
|
||||
}
|
||||
|
||||
func testStochasticShifts() {
|
||||
testStochasticAverage(Int8.random(in: .min ... .max))
|
||||
testStochasticAverage(Int16.random(in: .min ... .max))
|
||||
testStochasticAverage(Int32.random(in: .min ... .max))
|
||||
testStochasticAverage(UInt8.random(in: .min ... .max))
|
||||
testStochasticAverage(UInt16.random(in: .min ... .max))
|
||||
testStochasticAverage(UInt32.random(in: .min ... .max))
|
||||
testStochasticAverage(Int64.random(in: .min ... .max))
|
||||
testStochasticAverage(UInt64.random(in: .min ... .max))
|
||||
testStochasticAverage(DoubleWidth<Int64>.random(in: .min ... .max))
|
||||
testStochasticAverage(DoubleWidth<UInt64>.random(in: .min ... .max))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//===--- LinuxMain.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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
fatalError("Use --enable-test-discovery to run Swift Numerics tests on Linux.")
|
||||
@@ -1,67 +0,0 @@
|
||||
//===--- 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)
|
||||
}
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
//===--- 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)
|
||||
}
|
||||
}
|
||||
@@ -1,236 +0,0 @@
|
||||
//===--- 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)
|
||||
}
|
||||
}
|
||||
@@ -1,379 +0,0 @@
|
||||
//===--- 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
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
//===--- ApproximateEqualityTests.swift -----------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//===--- AugmentedArithmeticTests.swift -----------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
@@ -148,7 +148,7 @@ final class ElementaryFunctionChecks: XCTestCase {
|
||||
|
||||
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
|
||||
func testFloat16() {
|
||||
if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
|
||||
if #available(macOS 11.0, iOS 14.0, watchOS 14.0, tvOS 7.0, *) {
|
||||
Float16.elementaryFunctionChecks()
|
||||
Float16.realFunctionChecks()
|
||||
Float16.powZeroChecks()
|
||||
|
||||
@@ -78,7 +78,7 @@ internal extension Real where Self: FixedWidthFloatingPoint {
|
||||
}
|
||||
|
||||
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
|
||||
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
|
||||
@available(macOS 11.0, iOS 14.0, watchOS 14.0, tvOS 7.0, *)
|
||||
extension Float16 {
|
||||
static func testIntegerExponent() {
|
||||
testIntegerExponentCommon()
|
||||
@@ -157,10 +157,10 @@ extension Double {
|
||||
#endif
|
||||
assertClose( 1.7976931348623151738531864721534215e308, Double.pow(-u, 3196577161300664268), allowedError: tol)
|
||||
assertClose(-1.7976931348623155730212483790972209e308, Double.pow(-u, 3196577161300664269), allowedError: tol)
|
||||
assertClose( 1.7976931348623159721893102860411089e308, Double.pow(-u, 3196577161300664270), allowedError: tol) // warning expected on non-x86
|
||||
assertClose( 1.7976931348623159721893102860411089e308, Double.pow(-u, 3196577161300664270), allowedError: tol)
|
||||
assertClose( 1.7976931348623157075547244136070910e308, Double.pow(-d, -6393154322601327474), allowedError: tol)
|
||||
assertClose(-1.7976931348623159071387553670790721e308, Double.pow(-d, -6393154322601327475), allowedError: tol) // warning expected on non-x86
|
||||
assertClose( 1.7976931348623161067227863205510754e308, Double.pow(-d, -6393154322601327476), allowedError: tol) // warning expected on non-x86
|
||||
assertClose(-1.7976931348623159071387553670790721e308, Double.pow(-d, -6393154322601327475), allowedError: tol)
|
||||
assertClose( 1.7976931348623161067227863205510754e308, Double.pow(-d, -6393154322601327476), allowedError: tol)
|
||||
// Exponents close to underflow boundary.
|
||||
assertClose( 2.4703282292062334560337346683707907e-324, Double.pow(-u, -3355781687888880946))
|
||||
assertClose(-2.4703282292062329075106789791206172e-324, Double.pow(-u, -3355781687888880947))
|
||||
@@ -176,7 +176,7 @@ final class IntegerExponentTests: XCTestCase {
|
||||
|
||||
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
|
||||
func testFloat16() {
|
||||
if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
|
||||
if #available(macOS 11.0, iOS 14.0, watchOS 14.0, tvOS 7.0, *) {
|
||||
Float16.testIntegerExponent()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,7 +102,7 @@ final class RelaxedArithmeticTests: XCTestCase {
|
||||
// Summing all values in an array can be associated however we want, but
|
||||
// has to satisfy the usual error bound of 0.5 * sum.ulp * numberOfElements.
|
||||
// We don't have a golden reference, but we can compare two sums with twice
|
||||
// the bound for a basic check.
|
||||
// the bound for a sanity check.
|
||||
let array = (0 ..< 128).map { _ in T.random(in: 1 ..< 2) }
|
||||
var ref = strictSum(array)
|
||||
var tst = relaxedSum(array)
|
||||
@@ -116,7 +116,7 @@ final class RelaxedArithmeticTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testRelaxedArithmetic() {
|
||||
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
|
||||
#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
|
||||
testRelaxedArithmetic(Float16.self)
|
||||
#endif
|
||||
testRelaxedArithmetic(Float.self)
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
//===--- WindowsMain.swift ------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019-2021 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if os(Windows)
|
||||
import XCTest
|
||||
|
||||
@testable
|
||||
import RealTests
|
||||
|
||||
@testable
|
||||
import ComplexTests
|
||||
|
||||
@testable
|
||||
import IntegerUtilitiesTests
|
||||
|
||||
extension ComplexTests.ApproximateEqualityTests {
|
||||
static var all = testCase([
|
||||
("testFloat", ComplexTests.ApproximateEqualityTests.testFloat),
|
||||
("testDouble", ComplexTests.ApproximateEqualityTests.testDouble),
|
||||
])
|
||||
}
|
||||
|
||||
extension RealTests.ApproximateEqualityTests {
|
||||
static var all = testCase([
|
||||
("testFloat", RealTests.ApproximateEqualityTests.testFloat),
|
||||
("testDouble", RealTests.ApproximateEqualityTests.testDouble),
|
||||
])
|
||||
}
|
||||
|
||||
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
|
||||
extension ElementaryFunctionChecks {
|
||||
static var all = testCase([
|
||||
("testFloat16", ElementaryFunctionChecks.testFloat16),
|
||||
("testFloat", ElementaryFunctionChecks.testFloat),
|
||||
("testDouble", ElementaryFunctionChecks.testDouble),
|
||||
])
|
||||
}
|
||||
|
||||
extension IntegerExponentTests {
|
||||
static var all = testCase([
|
||||
("testFloat16", IntegerExponentTests.testFloat16),
|
||||
("testFloat", IntegerExponentTests.testFloat),
|
||||
("testDouble", IntegerExponentTests.testDouble),
|
||||
])
|
||||
}
|
||||
#else
|
||||
extension ElementaryFunctionChecks {
|
||||
static var all = testCase([
|
||||
("testFloat", ElementaryFunctionChecks.testFloat),
|
||||
("testDouble", ElementaryFunctionChecks.testDouble),
|
||||
])
|
||||
}
|
||||
|
||||
extension IntegerExponentTests {
|
||||
static var all = testCase([
|
||||
("testFloat", IntegerExponentTests.testFloat),
|
||||
("testDouble", IntegerExponentTests.testDouble),
|
||||
])
|
||||
}
|
||||
#endif
|
||||
|
||||
extension RealTests.AugmentedArithmeticTests {
|
||||
static var all = testCase([
|
||||
("testTwoSum", RealTests.AugmentedArithmeticTests.testTwoSum),
|
||||
])
|
||||
}
|
||||
|
||||
extension RealTests.RelaxedArithmeticTests {
|
||||
static var all = testCase([
|
||||
("testRelaxedArithmetic", RealTests.RelaxedArithmeticTests.testRelaxedArithmetic),
|
||||
])
|
||||
}
|
||||
|
||||
extension ArithmeticTests {
|
||||
static var all = testCase([
|
||||
("testPolar", ArithmeticTests.testPolar),
|
||||
("testBaudinSmith", ArithmeticTests.testBaudinSmith),
|
||||
("testDivisionByZero", ArithmeticTests.testDivisionByZero),
|
||||
])
|
||||
}
|
||||
|
||||
extension PropertyTests {
|
||||
static var all = testCase([
|
||||
("testProperties", PropertyTests.testProperties),
|
||||
("testEquatableHashable", PropertyTests.testEquatableHashable),
|
||||
("testCodable", PropertyTests.testCodable),
|
||||
])
|
||||
}
|
||||
|
||||
extension IntegerUtilitiesDivideTests {
|
||||
static var all = testCase([
|
||||
("testDivideInt8", IntegerUtilitiesDivideTests.testDivideInt8),
|
||||
("testDivideInt", IntegerUtilitiesDivideTests.testDivideInt),
|
||||
("testDivideUInt8", IntegerUtilitiesDivideTests.testDivideUInt8),
|
||||
("testDivideStochasticInt8", IntegerUtilitiesDivideTests.testDivideStochasticInt8),
|
||||
("testDivideStochasticUInt32", IntegerUtilitiesDivideTests.testDivideStochasticUInt32),
|
||||
("testRemainderByMinusOne", IntegerUtilitiesDivideTests.testRemainderByMinusOne),
|
||||
])
|
||||
}
|
||||
|
||||
extension IntegerUtilitiesGCDTests {
|
||||
static var all = testCase([
|
||||
("testGCDInt", IntegerUtilitiesGCDTests.testGCDInt),
|
||||
])
|
||||
}
|
||||
|
||||
extension IntegerUtilitiesRotateTests {
|
||||
static var all = testCase([
|
||||
("testRotateUInt8", IntegerUtilitiesRotateTests.testRotateUInt8),
|
||||
("testRotateInt16", IntegerUtilitiesRotateTests.testRotateInt16),
|
||||
])
|
||||
}
|
||||
|
||||
extension IntegerUtilitiesSaturatingTests {
|
||||
static var all = testCase([
|
||||
("testSaturatingAddSigned", IntegerUtilitiesSaturatingTests.testSaturatingAddSigned),
|
||||
("testSaturatingSubSigned", IntegerUtilitiesSaturatingTests.testSaturatingSubSigned),
|
||||
("testSaturatingNegSigned", IntegerUtilitiesSaturatingTests.testSaturatingNegSigned),
|
||||
("testSaturatingMulSigned", IntegerUtilitiesSaturatingTests.testSaturatingMulSigned),
|
||||
("testSaturatingAddUnsigned", IntegerUtilitiesSaturatingTests.testSaturatingAddUnsigned),
|
||||
("testSaturatingSubUnsigned", IntegerUtilitiesSaturatingTests.testSaturatingSubUnsigned),
|
||||
("testSaturatingNegUnsigned", IntegerUtilitiesSaturatingTests.testSaturatingNegUnsigned),
|
||||
("testSaturatingMulUnsigned", IntegerUtilitiesSaturatingTests.testSaturatingMulUnsigned),
|
||||
("testSaturatingShifts", IntegerUtilitiesSaturatingTests.testSaturatingShifts),
|
||||
("testEdgeCaseForNegativeCount", IntegerUtilitiesSaturatingTests.testEdgeCaseForNegativeCount)
|
||||
])
|
||||
}
|
||||
|
||||
extension IntegerUtilitiesShiftTests {
|
||||
static var all = testCase([
|
||||
("testRoundingShifts", IntegerUtilitiesShiftTests.testRoundingShifts),
|
||||
("testStochasticShifts", IntegerUtilitiesShiftTests.testStochasticShifts),
|
||||
])
|
||||
}
|
||||
|
||||
extension IntegerUtilitiesTests.DoubleWidthTests {
|
||||
static var all = testCase([
|
||||
("testArithmetic_Signed", IntegerUtilitiesTests.DoubleWidthTests.testArithmetic_Signed),
|
||||
("testArithmetic_Unsigned", IntegerUtilitiesTests.DoubleWidthTests.testArithmetic_Unsigned),
|
||||
("testBitwise_LeftAndRightShifts", IntegerUtilitiesTests.DoubleWidthTests.testBitwise_LeftAndRightShifts),
|
||||
("testCompileTime_SR_6947", IntegerUtilitiesTests.DoubleWidthTests.testCompileTime_SR_6947),
|
||||
("testConditionalConformance", IntegerUtilitiesTests.DoubleWidthTests.testConditionalConformance),
|
||||
("testConversions", IntegerUtilitiesTests.DoubleWidthTests.testConversions),
|
||||
("testConversions_Exact", IntegerUtilitiesTests.DoubleWidthTests.testConversions_Exact),
|
||||
("testConversions_SignedMax", IntegerUtilitiesTests.DoubleWidthTests.testConversions_SignedMax),
|
||||
("testConversions_SignedMin", IntegerUtilitiesTests.DoubleWidthTests.testConversions_SignedMin),
|
||||
("testConversions_ToAndFromString_Binary", IntegerUtilitiesTests.DoubleWidthTests.testConversions_ToAndFromString_Binary),
|
||||
("testConversions_ToAndFromString_Decimal", IntegerUtilitiesTests.DoubleWidthTests.testConversions_ToAndFromString_Decimal),
|
||||
("testConversions_ToAndFromString_Hexadecimal", IntegerUtilitiesTests.DoubleWidthTests.testConversions_ToAndFromString_Hexadecimal),
|
||||
("testConversions_UnsignedMax", IntegerUtilitiesTests.DoubleWidthTests.testConversions_UnsignedMax),
|
||||
("testConversions_UnsignedMin", IntegerUtilitiesTests.DoubleWidthTests.testConversions_UnsignedMin),
|
||||
("testDivision_ByMinusOne", IntegerUtilitiesTests.DoubleWidthTests.testDivision_ByMinusOne),
|
||||
("testDivision_ByZero", IntegerUtilitiesTests.DoubleWidthTests.testDivision_ByZero),
|
||||
("testInitialization", IntegerUtilitiesTests.DoubleWidthTests.testInitialization),
|
||||
("testInitialization_Overflow", IntegerUtilitiesTests.DoubleWidthTests.testInitialization_Overflow),
|
||||
("testLiterals", IntegerUtilitiesTests.DoubleWidthTests.testLiterals),
|
||||
("testLiterals_Underflow", IntegerUtilitiesTests.DoubleWidthTests.testLiterals_Underflow),
|
||||
("testMagnitude", IntegerUtilitiesTests.DoubleWidthTests.testMagnitude),
|
||||
("testMultipleOf", IntegerUtilitiesTests.DoubleWidthTests.testMultipleOf),
|
||||
("testMultiplication_ByMinusOne", IntegerUtilitiesTests.DoubleWidthTests.testMultiplication_ByMinusOne),
|
||||
("testNested", IntegerUtilitiesTests.DoubleWidthTests.testNested),
|
||||
("testRemainder_ByMinusOne", IntegerUtilitiesTests.DoubleWidthTests.testRemainder_ByMinusOne),
|
||||
("testRemainder_ByZero", IntegerUtilitiesTests.DoubleWidthTests.testRemainder_ByZero),
|
||||
("testTwoWords", IntegerUtilitiesTests.DoubleWidthTests.testTwoWords),
|
||||
("testWords", IntegerUtilitiesTests.DoubleWidthTests.testWords),
|
||||
])
|
||||
}
|
||||
|
||||
var testCases = [
|
||||
ComplexTests.ApproximateEqualityTests.all,
|
||||
RealTests.ApproximateEqualityTests.all,
|
||||
ElementaryFunctionChecks.all,
|
||||
IntegerExponentTests.all,
|
||||
ArithmeticTests.all,
|
||||
PropertyTests.all,
|
||||
IntegerUtilitiesDivideTests.all,
|
||||
IntegerUtilitiesGCDTests.all,
|
||||
IntegerUtilitiesRotateTests.all,
|
||||
IntegerUtilitiesShiftTests.all,
|
||||
IntegerUtilitiesSaturatingTests.all,
|
||||
IntegerUtilitiesTests.DoubleWidthTests.all,
|
||||
]
|
||||
|
||||
XCTMain(testCases)
|
||||
|
||||
#endif
|
||||
@@ -43,8 +43,6 @@ function(get_swift_host_arch result_var_name)
|
||||
set("${result_var_name}" "i686" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "i686")
|
||||
set("${result_var_name}" "i686" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "riscv64")
|
||||
set("${result_var_name}" "riscv64" PARENT_SCOPE)
|
||||
else()
|
||||
message(FATAL_ERROR "Unrecognized architecture on host system: ${CMAKE_SYSTEM_PROCESSOR}")
|
||||
endif()
|
||||
|
||||
Reference in new issue
Block a user