diff --git a/.spi.yml b/.spi.yml new file mode 100644 index 0000000..4c4e6f7 --- /dev/null +++ b/.spi.yml @@ -0,0 +1,4 @@ +version: 1 +builder: + configs: + - documentation_targets: [Numerics, RealModule, ComplexModule, BigIntModule] diff --git a/Package.swift b/Package.swift index e06c559..1a02f77 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.4 +// swift-tools-version:5.5 //===--- Package.swift ----------------------------------------*- swift -*-===// // // This source file is part of the Swift Numerics open source project @@ -28,7 +28,8 @@ let package = Package( // MARK: - Public API .target( name: "BigIntModule", - dependencies: [] + dependencies: [], + exclude: excludedFilenames ), .target( @@ -45,21 +46,23 @@ let package = Package( .target( name: "Numerics", - dependencies: ["ComplexModule", "IntegerUtilities", "RealModule"], + dependencies: ["ComplexModule", "IntegerUtilities", "RealModule", "BigIntModule"], exclude: excludedFilenames ), .target( name: "RealModule", dependencies: ["_NumericsShims"], - exclude: excludedFilenames + exclude: excludedFilenames, + linkerSettings: [ + .linkedLibrary("m", .when(platforms: [.linux, .android])) + ] ), // MARK: - Implementation details .target( name: "_NumericsShims", - exclude: excludedFilenames, - linkerSettings: [.linkedLibrary("m", .when(platforms: [.linux, .android]))] + exclude: excludedFilenames ), .target( diff --git a/Package@swift-5.4.swift b/Package@swift-5.4.swift new file mode 100644 index 0000000..71ed362 --- /dev/null +++ b/Package@swift-5.4.swift @@ -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" + ) + ] +) diff --git a/README.md b/README.md index fc76b27..3f59e70 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,7 @@ Questions about how to use Swift Numerics modules, or issues that are not clearl 1. [`RealModule`](Sources/RealModule/README.md) 2. [`ComplexModule`](Sources/ComplexModule/README.md) 3. [`IntegerUtilities`](Sources/IntegerUtilities/README.md) (on main only, not yet present in a released tag) +4. [`BigIntModule`](Sources/BigIntModule/README.md) (on branch only) ## Future expansion diff --git a/Sources/BigIntModule/BigUInt.swift b/Sources/BigIntModule/BigUInt.swift new file mode 100644 index 0000000..5016d32 --- /dev/null +++ b/Sources/BigIntModule/BigUInt.swift @@ -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(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?(_ 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?(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?(exactly source: T) where T: BinaryFloatingPoint { + guard source.isFinite, source == source.rounded(.towardZero) else { + return nil + } + self.init(source) + } + + public init(_ 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(_ 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(clamping source: T) where T: BinaryInteger { + self.init(source) + } + + public init(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 <<= (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 >>= (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 + var rhat: Array + 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.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.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 + } + } + } +} diff --git a/Sources/BigIntModule/CMakeLists.txt b/Sources/BigIntModule/CMakeLists.txt new file mode 100644 index 0000000..444f855 --- /dev/null +++ b/Sources/BigIntModule/CMakeLists.txt @@ -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) diff --git a/Sources/BigIntModule/README.md b/Sources/BigIntModule/README.md new file mode 100644 index 0000000..56dd1d8 --- /dev/null +++ b/Sources/BigIntModule/README.md @@ -0,0 +1,3 @@ +# Arbitrary-precision integers + +This module provides a `BigInt` type. \ No newline at end of file diff --git a/Sources/ComplexModule/Complex+AlgebraicField.swift b/Sources/ComplexModule/Complex+AlgebraicField.swift index be8a2aa..4908b57 100644 --- a/Sources/ComplexModule/Complex+AlgebraicField.swift +++ b/Sources/ComplexModule/Complex+AlgebraicField.swift @@ -123,4 +123,17 @@ extension Complex: AlgebraicField { } return nil } + + @_transparent + public static func _relaxedAdd(_ a: Self, _ b: Self) -> Self { + Complex(Relaxed.sum(a.x, b.x), Relaxed.sum(a.y, b.y)) + } + + @_transparent + public static func _relaxedMul(_ a: Self, _ b: Self) -> Self { + Complex( + Relaxed.sum(Relaxed.product(a.x, b.x), -Relaxed.product(a.y, b.y)), + Relaxed.sum(Relaxed.product(a.x, b.y), Relaxed.product(a.y, b.x)) + ) + } } diff --git a/Sources/ComplexModule/Complex+ElementaryFunctions.swift b/Sources/ComplexModule/Complex+ElementaryFunctions.swift index f6ef2f4..6c75e4b 100644 --- a/Sources/ComplexModule/Complex+ElementaryFunctions.swift +++ b/Sources/ComplexModule/Complex+ElementaryFunctions.swift @@ -119,7 +119,7 @@ extension Complex: ElementaryFunctions { } // Special cases out of the way, evaluate as discussed above. return Complex( - RealType._mulAdd(.cos(z.y), .expMinusOne(z.x), .cosMinusOne(z.y)), + Relaxed.multiplyAdd(.cos(z.y), .expMinusOne(z.x), .cosMinusOne(z.y)), .exp(z.x) * .sin(z.y) ) } @@ -300,7 +300,7 @@ extension Complex: ElementaryFunctions { // We are not trying for sub-ulp accuracy, just a good relative error // bound, so for our purposes it suffices to have log u dominate the // result: - if u >= 1 || u >= RealType._mulAdd(u,u,v*v) { + if u >= 1 || u >= Relaxed.multiplyAdd(u, u, v*v) { let r = v / u return Complex(.log(u) + .log(onePlus: r*r)/2, θ) } diff --git a/Sources/IntegerUtilities/CMakeLists.txt b/Sources/IntegerUtilities/CMakeLists.txt index cd141a4..db167c7 100644 --- a/Sources/IntegerUtilities/CMakeLists.txt +++ b/Sources/IntegerUtilities/CMakeLists.txt @@ -12,6 +12,7 @@ add_library(IntegerUtilities GCD.swift Rotate.swift RoundingRule.swift + SaturatingArithmetic.swift ShiftWithRounding.swift) set_target_properties(IntegerUtilities PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) diff --git a/Sources/IntegerUtilities/DivideWithRounding.swift b/Sources/IntegerUtilities/DivideWithRounding.swift index 87fabaa..c0cf0a6 100644 --- a/Sources/IntegerUtilities/DivideWithRounding.swift +++ b/Sources/IntegerUtilities/DivideWithRounding.swift @@ -126,12 +126,13 @@ extension BinaryInteger { } } - // TODO: make this API and make it possible to implement more - // efficiently. Customization point on new/revised integer - // protocol? Shouldn't have to go through .words. + // TODO: make this API and make it possible to implement more efficiently. + // Customization point on new/revised integer protocol? Shouldn't have to + // go through .words. + /// The index of the most-significant set bit. /// - /// - Precondition: self is assumed to be non-zero (to be changed + /// - Precondition: self is assumed to be non-zero (should be changed /// if/when this becomes API). @usableFromInline internal var _msb: Int { diff --git a/Sources/IntegerUtilities/README.md b/Sources/IntegerUtilities/README.md index ee7318c..2af9f79 100644 --- a/Sources/IntegerUtilities/README.md +++ b/Sources/IntegerUtilities/README.md @@ -4,7 +4,7 @@ _Note: This module is only present on `main`, and has not yet been stabilized an ## Utilities defined for `BinaryInteger` -The following API are defined for all integer types conforming to `BinaryInteger`: +The following API are defined for all integer types: - The `gcd(_:_:)` free function implements the _Greatest Common Divisor_ operation. @@ -36,7 +36,33 @@ The following API are defined for signed integer types: - The `rotated(right:)` and `rotated(left:)` methods implement _bitwise rotation_ for signed and unsigned integer types. The count parameter may be any `BinaryInteger` type. + +### [Saturating Arithmetic][saturating] + +The following saturating operations are defined as methods on `FixedWidthInteger`: + +- `addingWithSaturation(_:)` +- `subtractingWithSaturation(_:)` +- `negatedWithSaturation(_:)` +- `multipliedWithSaturation(by:)` +- `shiftedWithSaturation(leftBy:rounding:)` + +These implement _saturating arithmetic_. +They are an alternative to the usual `+`, `-`, and `*` operators, which trap if the result cannot be represented in the argument type, and `&+`, `&-`, `&*`, and `<<`, which wrap out-of-range results modulo 2ⁿ for some n. +Instead these methods clamp the result to the representable range of the type: +``` +let x: Int8 = 84 +let y: Int8 = 100 +let a = x + y // traps due to overflow +let b = x &+ y // wraps to -72 +let c = x.addingWithSaturation(y) // saturates to 127 +``` + +If you are using saturating arithmetic, you may also want to perform saturating conversions between integer types; this functionality is provided by the standard library via the [`init(clamping:)` API][clamping]. ## Types The `RoundingRule` enum is used with shift, division, and round operations to specify how to round their results to a representable value. + +[saturating]: https://en.wikipedia.org/wiki/Saturation_arithmetic +[clamping]: https://developer.apple.com/documentation/swift/binaryinteger/init(clamping:) diff --git a/Sources/IntegerUtilities/RoundingRule.swift b/Sources/IntegerUtilities/RoundingRule.swift index 47d13c9..687ce14 100644 --- a/Sources/IntegerUtilities/RoundingRule.swift +++ b/Sources/IntegerUtilities/RoundingRule.swift @@ -14,24 +14,84 @@ /// /// [Wikipedia](https://en.wikipedia.org/wiki/Rounding#Rounding_to_integer) /// provides a good overview of different rounding rules. +/// +/// Examples using rounding to integer to illustrate the various options: +/// ``` +/// value | down | up | towardZero | awayFromZero | +/// =======+==============+==============+==============+==============+ +/// 1.5 | 1 | 2 | 1 | 2 | +/// -------+--------------+--------------+--------------+--------------+ +/// -0.5 | -1 | 0 | 0 | -1 | +/// -------+--------------+--------------+--------------+--------------+ +/// 0.3 | 0 | 1 | 0 | 1 | +/// -------+--------------+--------------+--------------+--------------+ +/// 2 | 2 | 2 | 2 | 2 | +/// -------+--------------+--------------+--------------+--------------+ +/// +/// value | toOdd | toNearestOrAwayFromZero | toNearestOrEven | +/// =======+==============+=========================+==================+ +/// 1.5 | 1 | 2 | 2 | +/// -------+--------------+-------------------------+------------------+ +/// -0.5 | -1 | -1 | 0 | +/// -------+--------------+-------------------------+------------------+ +/// 0.3 | 1 | 0 | 0 | +/// -------+--------------+-------------------------+------------------+ +/// 2 | 2 | 2 | 2 | +/// -------+--------------+-------------------------+------------------+ +/// +/// value | stochastically | requireExact | +/// =======+=======================+================+ +/// 1.5 | 50% 1, 50% 2 | trap | +/// -------+-----------------------+----------------+ +/// -0.5 | 50% -1, 50% 0 | trap | +/// -------+-----------------------+----------------+ +/// 0.3 | 70% 0, 30% 1 | trap | +/// -------+-----------------------+----------------+ +/// 2 | 2 | 2 | +/// -------+-----------------------+----------------+ +/// ``` public enum RoundingRule { /// Produces the closest representable value that is less than or equal /// to the value being rounded. /// /// This is the default rounding mode for integer shifts, including the - /// shift operators defined in the standard library. + /// shift operators defined in the standard library. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .down)` is `-2`, because –2 is the + /// largest integer less than –4/3 = –1.3̅ + /// - `5.shifted(rightBy: 1, rounding: .down)` is `2`, because 2 is the + /// largest integer less than 5/2 = 2.5. case down /// Produces the closest representable value that is greater than or equal /// to the value being rounded. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .up)` is `-1`, because –1 is the + /// smallest integer greater than –4/3 = –1.3̅ + /// - `5.shifted(rightBy: 1, rounding: .up)` is `3`, because 3 is the + /// smallest integer greater than 5/2 = 2.5. case up /// Produces the closest representable value whose magnitude is less than /// or equal to that of the value being rounded. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .towardZero)` is `-1`, because –1 + /// is the closest integer to –4/3 = –1.3̅ with smaller magnitude. + /// - `5.shifted(rightBy: 1, rounding: .towardZero)` is `2`, because 2 + /// is the closest integer to 5/2 = 2.5 with smaller magnitude. case towardZero - /// Produces the closest representable value whose magnitude is greater than - /// or equal to that of the value being rounded. + /// Produces the closest representable value whose magnitude is greater + /// than or equal to that of the value being rounded. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .awayFromZero)` is `-2`, because –2 + /// is the closest integer to –4/3 = –1.3̅ with greater magnitude. + /// - `5.shifted(rightBy: 1, rounding: .awayFromZero)` is `3`, because 3 + /// is the closest integer to 5/2 = 2.5 with greater magnitude. case awayFromZero /// If the value being rounded is representable, that value is returned. @@ -45,24 +105,83 @@ public enum RoundingRule { /// we get is the same as if we rounded directly to p₂ in the desired mode /// so long as p₂ + 1 < p₁. Other rounding modes do not have this property, /// and admit _double roundings_ when interoperating with some modes. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .toOdd)` is `-1`, because –4/3 = –1.3̅ + /// is not an exact integer, and –1 is the closest odd integer. + /// - `4.shifted(rightBy: 1, rounding: .toOdd)` is `2`, + /// even though 2 is even, because 4/2 is exactly 2 and no rounding occurs. case toOdd /// Produces the representable value that is closest to the value being /// rounded. If two values are equally close, the one that has greater /// magnitude is returned. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .toNearestOrAwayFromZero)` + /// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2. + /// + /// - `5.shifted(rightBy: 1, rounding: .toNearestOrAwayFromZero)` is `3`, + /// because 5/2 = 2.5 is equally close to 2 and 3, and 3 is further away + /// from zero. case toNearestOrAwayFromZero /// Produces the representable value that is closest to the value being /// rounded. If two values are equally close, the one whose least /// significant bit is not set is returned. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .toNearestOrEven)` + /// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2. + /// + /// - `5.shifted(rightBy: 1, rounding: .toNearestOrEven)` is `2`, + /// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is even. case toNearestOrEven /// Adds a uniform random value from [0, d) to the value being rounded, /// where d is the distance between the two closest representable values, /// then rounds the sum downwards. + /// + /// Unlike all the other rounding modes, this mode is _not deterministic_; + /// repeated calls to rounding operations with this mode will generally + /// produce different results. There is a tradeoff implicit in using this + /// mode: you can sacrifice _reproducible_ results to get _more accurate_ + /// results in aggregate. For a contrived but illustrative example, consider + /// the following: + /// ``` + /// let data = Array(repeating: 1, count: 100) + /// let result = data.reduce(0) { + /// $0 + $1.divided(by: 3, rounding: rule) + /// } + /// ``` + /// because 1/3 is always the same value between 0 and 1, any + /// deterministic rounding rule must produce either 0 or 100 for + /// this computation. But rounding `stochastically` will + /// produce a value close to 33. The _error_ of the computation + /// is smaller, but the result will now change between runs of the + /// program. + /// + /// For this simple case a better solution would be to add the + /// values first, and then divide. This gives a result that is both + /// reproducible _and_ accurate: + /// ``` + /// let result = data.reduce(0, +)/3 + /// ``` + /// but this isn't always possible in more sophisticated scenarios, + /// and in those cases this rounding rule may be useful. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .stochastically)` + /// will be –1 with probability 2/3 and –2 with probability 1/3. + /// - `5.shifted(rightBy: 1, rounding: .stochastically)` + /// will be 2 with probability 1/2 and 3 with probability 1/2. case stochastically /// If the value being rounded is representable, that value is returned. /// Otherwise, a precondition failure occurs. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .requireExact)` will trap, + /// because –4/3 = –1.3̅ is not an integer. case requireExact } diff --git a/Sources/IntegerUtilities/SaturatingArithmetic.swift b/Sources/IntegerUtilities/SaturatingArithmetic.swift new file mode 100644 index 0000000..2d933f8 --- /dev/null +++ b/Sources/IntegerUtilities/SaturatingArithmetic.swift @@ -0,0 +1,167 @@ +//===--- SaturatingArithmetic.swift ---------------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2023 Apple Inc. and the Swift Numerics project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension FixedWidthInteger { + /// `~0` (all-ones) if this value is negative, otherwise `0`. + /// + /// Note that if `Self` is unsigned, this always returns `0`, + /// but it is useful for writing algorithms that are generic over + /// signed and unsigned integers. + @inline(__always) @usableFromInline + var signbit: Self { + return self < .zero ? ~.zero : .zero + } + + /// Saturating integer addition + /// + /// `self + other` clamped to the representable range of the type. e.g.: + /// ``` + /// let a: Int8 = 84 + /// let b: Int8 = 100 + /// // 84 + 100 = 184 is not representable as + /// // Int8, so `c` is clamped to Int8.max (127). + /// let c = a.addingWithSaturation(b) + /// ``` + /// + /// Anytime the "normal addition" `self + other` does not trap, + /// `addingWithSaturation` produces the same result. + @inlinable + public func addingWithSaturation(_ other: Self) -> Self { + let (wrapped, overflow) = addingReportingOverflow(other) + return overflow ? Self.max &- signbit : wrapped + } + + /// Saturating integer subtraction + /// + /// `self - other` clamped to the representable range of the type. e.g.: + /// ``` + /// let a: UInt = 37 + /// let b: UInt = 42 + /// // 37 - 42 = -5, which is not representable as + /// // UInt, so `c` is clamped to UInt.min (zero). + /// let c = a.subtractingWithSaturation(b) + /// ``` + /// + /// Note that `a.addingWithSaturation(-b)` is not always equivalent to + /// `a.subtractingWithSaturation(b)`, because `-b` is not representable + /// if `b` is the minimum value of a signed type. + /// + /// Anytime the "normal subtraction" `self - other` does not trap, + /// `subtractingWithSaturation` produces the same result. + @inlinable + public func subtractingWithSaturation(_ other: Self) -> Self { + let (wrapped, overflow) = subtractingReportingOverflow(other) + if !overflow { return wrapped } + return Self.isSigned ? Self.max &- signbit : 0 + } + + /// Saturating integer negation + /// + /// For unsigned types, the result is always zero. This is not very + /// interesting, but may occasionally be useful in generic contexts. + /// For signed types, the result is `-self` unless `self` is `.min`, + /// in which case the result is `.max`. + @inlinable + public func negatedWithSaturation() -> Self { + Self.zero.subtractingWithSaturation(self) + } + + /// Saturating integer multiplication + /// + /// `self * other` clamped to the representable range of the type. e.g.: + /// ``` + /// let a: Int8 = -16 + /// let b: Int8 = -8 + /// // -16 * -8 = 128 is not representable as + /// // Int8, so `c` is clamped to Int8.max (127). + /// let c = a.multipliedWithSaturation(by: b) + /// ``` + /// + /// Anytime the "normal multiplication" `self * other` does not trap, + /// `multipliedWithSaturation` produces the same result. + @inlinable + public func multipliedWithSaturation(by other: Self) -> Self { + let (high, low) = multipliedFullWidth(by: other) + let wrapped = Self(truncatingIfNeeded: low) + if high == wrapped.signbit { return wrapped } + return Self.max &- high.signbit + } + + /// Bitwise left with rounding and saturation. + /// + /// `self` multiplied by the rational number 2^(`count`), saturated to the + /// range `Self.min ... Self.max`, and rounded according to `rule`. + /// + /// See `shifted(rightBy:rounding:)` for more discussion of rounding + /// shifts with examples. + /// + /// - Parameters: + /// - leftBy count: the number of bits to shift by. If positive, this is a left-shift, + /// and if negative a right shift. + /// - rounding rule: the direction in which to round if `count` is negative. + @inlinable + public func shiftedWithSaturation( + leftBy count: Int, + rounding rule: RoundingRule = .down + ) -> Self { + if count == 0 { return self } + // If count is negative, negate it and do a right shift without + // saturation instead, since we already have that implemented. + guard count > 0 else { + return shifted( + rightBy: count.negatedWithSaturation(), + rounding: rule + ) + } + let clamped = Self.max &- signbit + guard count < Self.bitWidth else { + // If count is bitWidth or greater, we always overflow + // unless self is zero. + return self == 0 ? 0 : clamped + } + // Now we have 0 < count < bitWidth, so we can use a nice + // straightforward implementation; a shift overflows if + // the complementary shift doesn't match sign-or-zero + // extension. E.g.: + // + // - signed 0b0010_1111 << 2 overflows, because + // 0b0010_1111 >> 5 is 0b0000_0001, which does not + // equal 0b0000_0000 + // + // - unsigned 0b0010_1111 << 2 does not overflow, + // because 0b0010_0000 >> 6 is 0b0000_0000, which + // does equal 0b0000_0000. + let valueBits = Self.bitWidth &- (Self.isSigned ? 1 : 0) + let wrapped = self &<< count + let complement = valueBits &- count + return self &>> complement == signbit ? wrapped : clamped + } + + /// Bitwise left with rounding and saturation. + /// + /// `self` multiplied by the rational number 2^(`count`), saturated to the + /// range `Self.min ... Self.max`, and rounded according to `rule`. + /// + /// See `shifted(rightBy:rounding:)` for more discussion of rounding + /// shifts with examples. + /// + /// - Parameters: + /// - leftBy count: the number of bits to shift by. If positive, this is a left-shift, + /// and if negative a right shift. + /// - rounding rule: the direction in which to round if `count` is negative. + @_transparent + public func shiftedWithSaturation( + leftBy count: Count, + rounding rule: RoundingRule = .down + ) -> Self { + self.shiftedWithSaturation(leftBy: Int(clamping: count), rounding: rule) + } +} diff --git a/Sources/IntegerUtilities/ShiftWithRounding.swift b/Sources/IntegerUtilities/ShiftWithRounding.swift index baaa8f4..d03bbae 100644 --- a/Sources/IntegerUtilities/ShiftWithRounding.swift +++ b/Sources/IntegerUtilities/ShiftWithRounding.swift @@ -27,14 +27,14 @@ extension BinaryInteger { /// // is odd. /// 3.shifted(rightBy: 1, rounding: .toOdd) /// - /// // 7/2^2 = 1.75, so the result is 1 with probability 1/4, and 2 + /// // 7/4 = 1.75, so the result is 1 with probability 1/4, or 2 /// // with probability 3/4. /// 7.shifted(rightBy: 2, rounding: .stochastically) /// - /// // 4/2^2 = 4/4 = 1, exactly. - /// 4.shifted(rightBy: 2, rounding: .trap) + /// // 4/4 is exactly 1, so this does not trap. + /// 4.shifted(rightBy: 2, rounding: .requireExact) /// - /// // 5/2 is 2.5, which is not exact, so this traps. + /// // 5/2 is 2.5, which is not an integer, so this traps. /// 5.shifted(rightBy: 1, rounding: .requireExact) /// /// When `Self(1) << count` is positive, the following are equivalent: @@ -42,8 +42,8 @@ extension BinaryInteger { /// a.shifted(rightBy: count, rounding: rule) /// a.divided(by: 1 << count, rounding: rule) @inlinable - public func shifted( - rightBy count: Count, + public func shifted( + rightBy count: Int, rounding rule: RoundingRule = .down ) -> Self { // Easiest case: count is zero or negative, so shift is always exact; @@ -61,11 +61,11 @@ extension BinaryInteger { // shifts by first shifting all but bitWidth - 1 bits with sticky // rounding, and then shifting the remaining bitWidth - 1 bits with // the desired rounding mode. - let count = count - Count(bitWidth - 1) - var floor = self >> count + let count = count - (bitWidth - 1) + let floor = self >> count let lost = self - (floor << count) - if lost != 0 { floor |= 1 } // insert sticky bit - return floor.shifted(rightBy: bitWidth - 1, rounding: rule) + let sticky = floor | (lost == 0 ? 0 : 1) + return sticky.shifted(rightBy: bitWidth - 1, rounding: rule) } // Now we are in the happy case: 0 < count < bitWidth, which makes all // the math to handle rounding simpler. @@ -124,18 +124,18 @@ extension BinaryInteger { return floor + Self((round + lost) >> count) case .stochastically: // TODO: it's unfortunate that we can't specify a custom random source - // for the stochastically rounding rule, but I don't see a nice way to have - // that share the API with the other rounding rules, because we'd then - // have to take the RNG in-out. The same problem applies to rounding - // with dithering. We should consider adding a stateful rounding API - // down the road to support those use cases. + // 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 stochastically - // rounding for bigints; 32b suffices for most purposes, and 64b is - // more than enough. + // 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 { @@ -155,4 +155,43 @@ extension BinaryInteger { return floor } } + + /// `self` divided by 2^(`count`), rounding the result according to `rule`. + /// + /// The default rounding rule is `.down`, which matches the behavior of + /// the `>>` operator from the standard library. + /// + /// Some examples of different rounding rules: + /// + /// // 3/2 is 1.5, which rounds (down by default) to 1. + /// 3.shifted(rightBy: 1) + /// + /// // 1.5 rounds up to 2. + /// 3.shifted(rightBy: 1, rounding: .up) + /// + /// // The two closest values are 1 and 2, 1 is returned because it + /// // is odd. + /// 3.shifted(rightBy: 1, rounding: .toOdd) + /// + /// // 7/4 = 1.75, so the result is 1 with probability 1/4, or 2 + /// // with probability 3/4. + /// 7.shifted(rightBy: 2, rounding: .stochastically) + /// + /// // 4/4 is exactly 1, so this does not trap. + /// 4.shifted(rightBy: 2, rounding: .requireExact) + /// + /// // 5/2 is 2.5, which is not an integer, so this traps. + /// 5.shifted(rightBy: 1, rounding: .requireExact) + /// + /// When `Self(1) << count` is positive, the following are equivalent: + /// + /// a.shifted(rightBy: count, rounding: rule) + /// a.divided(by: 1 << count, rounding: rule) + @_transparent + public func shifted( + rightBy count: Count, + rounding rule: RoundingRule = .down + ) -> Self { + self.shifted(rightBy: Int(clamping: count), rounding: rule) + } } diff --git a/Sources/Numerics/CMakeLists.txt b/Sources/Numerics/CMakeLists.txt index 8104049..3e5f747 100644 --- a/Sources/Numerics/CMakeLists.txt +++ b/Sources/Numerics/CMakeLists.txt @@ -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) diff --git a/Sources/Numerics/Numerics.swift b/Sources/Numerics/Numerics.swift index 2aa9903..0faa23d 100644 --- a/Sources/Numerics/Numerics.swift +++ b/Sources/Numerics/Numerics.swift @@ -10,6 +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 diff --git a/Sources/RealModule/AlgebraicField.swift b/Sources/RealModule/AlgebraicField.swift index 7a231e8..4c8070d 100644 --- a/Sources/RealModule/AlgebraicField.swift +++ b/Sources/RealModule/AlgebraicField.swift @@ -89,6 +89,12 @@ public protocol AlgebraicField: SignedNumeric { /// } /// ``` var reciprocal: Self? { get } + + /// a + b, with the optimizer licensed to reassociate and form FMAs. + static func _relaxedAdd(_ a: Self, _ b: Self) -> Self + + /// a * b, with the optimizer licensed to reassociate and form FMAs. + static func _relaxedMul(_ a: Self, _ b: Self) -> Self } extension AlgebraicField { @@ -99,12 +105,27 @@ extension AlgebraicField { return result } - /// Implementations should be *conservative* with the reciprocal property; - /// it is OK to return `nil` even in cases where a reciprocal could be - /// represented. For this reason, a default implementation that simply - /// always returns `nil` is correct, but conforming types should provide - /// a better implementation if possible. + // Implementations should be *conservative* with the reciprocal property; + // it is OK to return `nil` even in cases where a reciprocal could be + // represented. For this reason, a default implementation that simply + // always returns `nil` is correct, but conforming types should provide + // a better implementation if possible. + @_transparent public var reciprocal: Self? { return nil } + + // It's always OK to simply fall back on normal arithmetic, and for any + // field with exact arithmetic, this is the correct definition. + @_transparent + public static func _relaxedAdd(_ a: Self, _ b: Self) -> Self { + a + b + } + + // It's always OK to simply fall back on normal arithmetic, and for any + // field with exact arithmetic, this is the correct definition. + @_transparent + public static func _relaxedMul(_ a: Self, _ b: Self) -> Self { + a * b + } } diff --git a/Sources/RealModule/CMakeLists.txt b/Sources/RealModule/CMakeLists.txt index c074dcf..acc78da 100644 --- a/Sources/RealModule/CMakeLists.txt +++ b/Sources/RealModule/CMakeLists.txt @@ -17,7 +17,8 @@ add_library(RealModule Float16+Real.swift Float80+Real.swift Real.swift - RealFunctions.swift) + RealFunctions.swift + RelaxedArithmetic.swift) set_target_properties(RealModule PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) target_link_libraries(RealModule PUBLIC diff --git a/Sources/RealModule/Double+Real.swift b/Sources/RealModule/Double+Real.swift index 469e114..4c6b341 100644 --- a/Sources/RealModule/Double+Real.swift +++ b/Sources/RealModule/Double+Real.swift @@ -221,7 +221,12 @@ extension Double: Real { #endif @_transparent - public static func _mulAdd(_ a: Double, _ b: Double, _ c: Double) -> Double { - _numerics_muladd(a, b, c) + public static func _relaxedAdd(_ a: Double, _ b: Double) -> Double { + _numerics_relaxed_add(a, b) + } + + @_transparent + public static func _relaxedMul(_ a: Double, _ b: Double) -> Double { + _numerics_relaxed_mul(a, b) } } diff --git a/Sources/RealModule/Float+Real.swift b/Sources/RealModule/Float+Real.swift index fe7849f..ab459bb 100644 --- a/Sources/RealModule/Float+Real.swift +++ b/Sources/RealModule/Float+Real.swift @@ -194,7 +194,12 @@ extension Float: Real { #endif @_transparent - public static func _mulAdd(_ a: Float, _ b: Float, _ c: Float) -> Float { - _numerics_muladdf(a, b, c) + public static func _relaxedAdd(_ a: Float, _ b: Float) -> Float { + _numerics_relaxed_addf(a, b) + } + + @_transparent + public static func _relaxedMul(_ a: Float, _ b: Float) -> Float { + _numerics_relaxed_mulf(a, b) } } diff --git a/Sources/RealModule/Float16+Real.swift b/Sources/RealModule/Float16+Real.swift index 6a99102..9613ebc 100644 --- a/Sources/RealModule/Float16+Real.swift +++ b/Sources/RealModule/Float16+Real.swift @@ -172,6 +172,20 @@ extension Float16: Real { Float16(.logGamma(Float(x))) } #endif + + // TODO: once clang stabilizes the calling conventions for _Float16 on Intel, + // we can re-enable these; presently the type is disabled on the target. + #if !(arch(i386) || arch(x86_64)) + @_transparent + public static func _relaxedAdd(_ a: Float16, _ b: Float16) -> Float16 { + _numerics_relaxed_addf16(a, b) + } + + @_transparent + public static func _relaxedMul(_ a: Float16, _ b: Float16) -> Float16 { + _numerics_relaxed_mulf16(a, b) + } + #endif } #endif diff --git a/Sources/RealModule/Float80+Real.swift b/Sources/RealModule/Float80+Real.swift index 9a85d5d..b4ca39b 100644 --- a/Sources/RealModule/Float80+Real.swift +++ b/Sources/RealModule/Float80+Real.swift @@ -165,5 +165,15 @@ extension Float80: Real { var dontCare: Int32 = 0 return libm_lgammal(x, &dontCare) } + + @_transparent + public static func _relaxedAdd(_ a: Float80, _ b: Float80) -> Float80 { + _numerics_relaxed_addl(a, b) + } + + @_transparent + public static func _relaxedMul(_ a: Float80, _ b: Float80) -> Float80 { + _numerics_relaxed_mull(a, b) + } } #endif diff --git a/Sources/RealModule/RealFunctions.swift b/Sources/RealModule/RealFunctions.swift index b88074c..31e6d16 100644 --- a/Sources/RealModule/RealFunctions.swift +++ b/Sources/RealModule/RealFunctions.swift @@ -76,9 +76,4 @@ public protocol RealFunctions: ElementaryFunctions { /// See also `gamma()` and `logGamma()`. static func signGamma(_ x: Self) -> FloatingPointSign #endif - - /// a*b + c, computed _either_ with an FMA or with separate multiply and add. - /// - /// Whichever is faster should be chosen by the compiler statically. - static func _mulAdd(_ a: Self, _ b: Self, _ c: Self) -> Self } diff --git a/Sources/RealModule/RelaxedArithmetic.swift b/Sources/RealModule/RelaxedArithmetic.swift new file mode 100644 index 0000000..e3a5865 --- /dev/null +++ b/Sources/RealModule/RelaxedArithmetic.swift @@ -0,0 +1,82 @@ +//===--- RelaxedArithmetic.swift ------------------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import _NumericsShims + +/// A namespace for "relaxed arithmetic" operations for types conforming to +/// `AlgebraicField`. +public enum Relaxed { } + +extension Relaxed { + /// a+b with the optimizer licensed to reassociate expressions and form FMAs. + /// + /// Floating-point addition is not an associative operation, so the Swift + /// compiler does not have any flexibility in how it evaluates an expression + /// like: + /// ``` + /// func sum(array: [Float]) -> Float { + /// array.reduce(0, +) + /// } + /// ``` + /// Using `Relaxed.sum` instead of `+` permits the compiler to reorder the + /// terms in the summation, which unlocks loop unrolling and vectorization. + /// In a benchmark, simply using `Relaxed.sum` provides about an 8x speedup + /// for release builds, without any unsafe flags or other optimizations. + /// Further improvement should be possible by improving LLVM optimizations + /// or adding attributes to license more aggressive unrolling and taking + /// advantage of vector ISA extensions for swift. + /// + /// If you want to compute `a-b` with relaxed semantics, use + /// `Relaxed.sum(a, -b)`. + /// + /// If a type or toolchain does not support reassociation for optimization + /// purposes, this operation decays to a normal addition; it is a license + /// for the compiler to optimize, not a guarantee that any change occurs. + @_transparent + public static func sum(_ a: T, _ b: T) -> T { + T._relaxedAdd(a, b) + } + + /// a*b with the optimizer licensed to reassociate expressions and form FMAs. + /// + /// Floating-point addition and multiplication are not associative operations, + /// so the Swift compiler does not have any flexibility in how it evaluates + /// an expression like: + /// ``` + /// func sumOfSquares(array: [Float]) -> Float { + /// array.reduce(0) { $0 + $1*$1 } + /// } + /// ``` + /// Using `Relaxed.sum` and `Relaxed.product` instead of `+` and `*` permits + /// the compiler to reorder the terms in the summation, which unlocks loop + /// unrolling and vectorization, and form fused multiply-adds, which allows + /// us to achieve twice the throughput on some hardware. + /// + /// If a type or toolchain does not support reassociation for optimization + /// purposes, this operation decays to a normal multiplication; it is a + /// license for the compiler to optimize, not a guarantee that any change + /// occurs. + @_transparent + public static func product(_ a: T, _ b: T) -> T { + T._relaxedMul(a, b) + } +} + +extension Relaxed { + /// a*b + c, computed _either_ with an FMA or with separate multiply and add, + /// whichever is fastest according to the optimizer's heuristics. + @_transparent + public static func multiplyAdd( + _ a: T, _ b: T, _ c: T + ) -> T { + T._relaxedAdd(c, T._relaxedMul(a, b)) + } +} diff --git a/Sources/_NumericsShims/include/_NumericsShims.h b/Sources/_NumericsShims/include/_NumericsShims.h index 7e25eab..016c235 100644 --- a/Sources/_NumericsShims/include/_NumericsShims.h +++ b/Sources/_NumericsShims/include/_NumericsShims.h @@ -382,18 +382,71 @@ HEADER_SHIM long double libm_lgammal(long double x, int *signp) { } #endif -// MARK: - fast mul-add inlines -/// a*b + c evaluated _either_ as two operations or fma, whichever is faster. -HEADER_SHIM float _numerics_muladdf(float a, float b, float c) { -#pragma STDC FP_CONTRACT ON - return a*b + c; +// MARK: - math inlines with relaxed semantics to support optimization. +#define CLANG_RELAX_FP _Pragma("clang fp reassociate(on) contract(fast)") + +#if !(__i386__ || __x86_64__) +/// a + b with the "allow reassociation" and "allow FMA formation" flags +/// set in the IR. +HEADER_SHIM _Float16 _numerics_relaxed_addf16(_Float16 a, _Float16 b) { + CLANG_RELAX_FP + return a + b; } -/// a*b + c evaluated _either_ as two operations or fma, whichever is faster. -HEADER_SHIM double _numerics_muladd(double a, double b, double c) { -#pragma STDC FP_CONTRACT ON - return a*b + c; +/// a * b with the "allow reassociation" and "allow FMA formation" flags +/// set in the IR. +HEADER_SHIM _Float16 _numerics_relaxed_mulf16(_Float16 a, _Float16 b) { + CLANG_RELAX_FP + return a * b; +} +#endif + +/// a + b with the "allow reassociation" and "allow FMA formation" flags +/// set in the IR. +HEADER_SHIM float _numerics_relaxed_addf(float a, float b) { + CLANG_RELAX_FP + return a + b; } -// No long-double muladd operation, because no one has built an FMA for it -// (except for Itanium, which Swift doesn't support). +/// a * b with the "allow reassociation" and "allow FMA formation" flags +/// set in the IR. +HEADER_SHIM float _numerics_relaxed_mulf(float a, float b) { + CLANG_RELAX_FP + return a * b; +} + +/// a + b with the "allow reassociation" and "allow FMA formation" flags +/// set in the IR. +HEADER_SHIM double _numerics_relaxed_add(double a, double b) { + CLANG_RELAX_FP + return a + b; +} + +/// a * b with the "allow reassociation" and "allow FMA formation" flags +/// set in the IR. +HEADER_SHIM double _numerics_relaxed_mul(double a, double b) { + CLANG_RELAX_FP + return a * b; +} + +#if !defined _WIN32 && (defined __i386__ || defined __x86_64__) +/// a + b with the "allow reassociation" and "allow FMA formation" flags +/// set in the IR. +HEADER_SHIM long double _numerics_relaxed_addl(long double a, long double b) { + CLANG_RELAX_FP + return a + b; +} + +/// a * b with the "allow reassociation" and "allow FMA formation" flags +/// set in the IR. +HEADER_SHIM long double _numerics_relaxed_mull(long double a, long double b) { + CLANG_RELAX_FP + return a * b; +} +#endif + +HEADER_SHIM void _numerics_optimization_barrier(const void *pointer) { + __asm("": :"r" (pointer)); +} + +#undef CLANG_RELAX_FP diff --git a/Sources/_TestSupport/BlackHole.swift b/Sources/_TestSupport/BlackHole.swift new file mode 100644 index 0000000..c614028 --- /dev/null +++ b/Sources/_TestSupport/BlackHole.swift @@ -0,0 +1,19 @@ +//===--- BlackHole.swift --------------------------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import _NumericsShims + +@_transparent +public func blackHole(_ thing: T) { + withUnsafePointer(to: thing) { + _numerics_optimization_barrier($0) + } +} diff --git a/Sources/_TestSupport/CMakeLists.txt b/Sources/_TestSupport/CMakeLists.txt index 48b85d1..96c3079 100644 --- a/Sources/_TestSupport/CMakeLists.txt +++ b/Sources/_TestSupport/CMakeLists.txt @@ -8,6 +8,7 @@ See https://swift.org/LICENSE.txt for license information #]] add_library(_TestSupport + BlackHole.swift DoubleWidth.swift Error.swift Interval.swift diff --git a/Sources/_TestSupport/DoubleWidth.swift b/Sources/_TestSupport/DoubleWidth.swift index b26a337..78fd8d3 100644 --- a/Sources/_TestSupport/DoubleWidth.swift +++ b/Sources/_TestSupport/DoubleWidth.swift @@ -363,8 +363,10 @@ extension DoubleWidth : FixedWidthInteger { let low = DoubleWidth(mid1.partial, a.partial) + let (sum_, overflow_) = + mid1.carry.addingReportingOverflow(mid2.partial) let high = - DoubleWidth(High(mid2.carry + d.carry), mid1.carry + mid2.partial) + DoubleWidth(High(mid2.carry + d.carry + (overflow_ ? 1 : 0)), sum_) if isNegative { let (lowComplement, overflow) = (~low).addingReportingOverflow(1) @@ -631,10 +633,14 @@ extension DoubleWidth : UnsignedInteger where Base : UnsignedInteger { ) -> (quotient: Low, remainder: Magnitude) { // The following invariants are guaranteed to hold by dividingFullWidth or // quotientAndRemainder before this method is invoked: - assert(lhs.high != (0 as Low)) assert(rhs.leadingZeroBitCount == 0) assert(Magnitude(lhs.high, lhs.mid) < rhs) + guard lhs.high != (0 as Low) else { + let lhs_ = Magnitude(lhs.mid, lhs.low) + return lhs_ < rhs ? (0, lhs_) : (1, lhs_ &- rhs) + } + // Estimate the quotient. var quotient = lhs.high == rhs.high ? Low.max @@ -735,8 +741,10 @@ extension DoubleWidth : UnsignedInteger where Base : UnsignedInteger { // Left shift both rhs and lhs, then divide and right shift the remainder. let shift = rhs.leadingZeroBitCount + // Note the use of `>>` instead of `&>>` below, + // as `high` should be zero if `shift` is zero. + let high = (lhs >> (Magnitude.bitWidth &- shift)).low let rhs = rhs &<< shift - let high = (lhs &>> (Magnitude.bitWidth &- shift)).low let lhs = lhs &<< shift let (quotient, remainder) = Magnitude._divide((high, lhs.high, lhs.low), by: rhs) diff --git a/Sources/_TestSupport/RealTestSupport.swift b/Sources/_TestSupport/RealTestSupport.swift index ad90efe..6189336 100644 --- a/Sources/_TestSupport/RealTestSupport.swift +++ b/Sources/_TestSupport/RealTestSupport.swift @@ -16,7 +16,7 @@ where Exponent: FixedWidthInteger, RawSignificand: FixedWidthInteger { } #if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64)) -@available(macOS 11.0, iOS 14.0, watchOS 14.0, tvOS 7.0, *) +@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) extension Float16: FixedWidthFloatingPoint { } #endif diff --git a/Tests/BigIntTests/BigUIntTests.swift b/Tests/BigIntTests/BigUIntTests.swift new file mode 100644 index 0000000..74ad609 --- /dev/null +++ b/Tests/BigIntTests/BigUIntTests.swift @@ -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 = lowerBound ..< upperBound + + let encoder = JSONEncoder() + let decoder = JSONDecoder() + let data = try encoder.encode(expectedRange) + let actualRange = try decoder.decode(Range.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(_ 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 + } +} diff --git a/Tests/IntegerUtilitiesTests/CMakeLists.txt b/Tests/IntegerUtilitiesTests/CMakeLists.txt index a6522d2..1537662 100644 --- a/Tests/IntegerUtilitiesTests/CMakeLists.txt +++ b/Tests/IntegerUtilitiesTests/CMakeLists.txt @@ -12,6 +12,7 @@ add_library(IntegerUtilitiesTests DoubleWidthTests.swift GCDTests.swift RotateTests.swift + SaturatingArithmeticTests.swift ShiftTests.swift) target_compile_options(IntegerUtilitiesTests PRIVATE -enable-testing) diff --git a/Tests/IntegerUtilitiesTests/DoubleWidthTests.swift b/Tests/IntegerUtilitiesTests/DoubleWidthTests.swift index 8e685b2..6b297f7 100644 --- a/Tests/IntegerUtilitiesTests/DoubleWidthTests.swift +++ b/Tests/IntegerUtilitiesTests/DoubleWidthTests.swift @@ -129,6 +129,34 @@ final class DoubleWidthTests: XCTestCase { XCTAssertEqual(x % 3, 1) XCTAssertEqual(x % y, x) + + do { + let lhs = _UInt16((high: 0b0011_0000, low: 0)) + let rhs = _UInt16((high: 0b0010_0000, low: 0)) + XCTAssertEqual(lhs % rhs, 4096) + } + do { + let lhs = _UInt128((high: 0xa0c7d7165cf01386, low: 0xbf3f66a93056143f)) + let rhs = _UInt128((high: 0x9ac3a19b1e7d6b83, low: 0x513929792d588736)) + XCTAssertEqual(String(lhs % rhs), "7997221894243298914179865336050715913") + } + do { + let lhs = _UInt128((high: 0xea8a9116b7af33b7, low: 0x3d9d6779ddd22ca3)) + let rhs = _UInt128((high: 0xc3673efc7f1f37cc, low: 0x312f661057d0ba94)) + XCTAssertEqual(String(lhs % rhs), "52023287460685389410162512181093036559") + } + do { + let lhs = _UInt256("2369676578372158364766242369061213561181961479062237766620")! + let rhs = _UInt256("102797312405202436815976773795958969482")! + XCTAssertEqual(String(lhs / rhs), "23051931251193218442") + } + do { + let lhs = _UInt256("96467201117289166187766181030232879447148862859323917044548749804018359008044")! + let rhs = _UInt256("4646260627574879223760172113656436161581617773435991717024")! + XCTAssertEqual(String(lhs / rhs), "20762331011904583253") + } + + XCTAssertTrue((0xff01 as _UInt16).multipliedFullWidth(by: 0x101) == (high: 256, low: 1)) } func testArithmetic_Signed() { diff --git a/Tests/IntegerUtilitiesTests/SaturatingArithmeticTests.swift b/Tests/IntegerUtilitiesTests/SaturatingArithmeticTests.swift new file mode 100644 index 0000000..d6a9190 --- /dev/null +++ b/Tests/IntegerUtilitiesTests/SaturatingArithmeticTests.swift @@ -0,0 +1,192 @@ +//===--- SaturatingArithmeticTests.swift ----------------------*- swift -*-===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +import IntegerUtilities +import XCTest +import _TestSupport + +final class IntegerUtilitiesSaturatingTests: XCTestCase { + + func testSaturatingAddSigned() { + for a in Int8.min ... Int8.max { + for b in Int8.min ... Int8.max { + let expected = Int8(clamping: Int16(a) + Int16(b)) + let observed = a.addingWithSaturation(b) + if expected != observed { + print("Error found in (\(a)).addingWithSaturation(\(b)).") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + } + } + + func testSaturatingSubSigned() { + for a in Int8.min ... Int8.max { + for b in Int8.min ... Int8.max { + let expected = Int8(clamping: Int16(a) - Int16(b)) + let observed = a.subtractingWithSaturation(b) + if expected != observed { + print("Error found in (\(a)).subtractingWithSaturation(\(b)).") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + } + } + + func testSaturatingNegSigned() { + for a in Int8.min ... Int8.max { + let expected = Int8(clamping: 0 - Int16(a)) + let observed = a.negatedWithSaturation() + if expected != observed { + print("Error found in (\(a)).negatedWithSaturation().") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + } + + func testSaturatingMulSigned() { + for a in Int8.min ... Int8.max { + for b in Int8.min ... Int8.max { + let expected = Int8(clamping: Int16(a) * Int16(b)) + let observed = a.multipliedWithSaturation(by: b) + if expected != observed { + print("Error found in (\(a)).multipliedWithSaturation(by: \(b)).") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + } + } + + func testSaturatingAddUnsigned() { + for a in UInt8.min ... UInt8.max { + for b in UInt8.min ... UInt8.max { + let expected = UInt8(clamping: UInt16(a) + UInt16(b)) + let observed = a.addingWithSaturation(b) + if expected != observed { + print("Error found in (\(a)).addingWithSaturation(\(b)).") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + } + } + + func testSaturatingSubUnsigned() { + for a in UInt8.min ... UInt8.max { + for b in UInt8.min ... UInt8.max { + let expected = UInt8(clamping: Int16(a) - Int16(b)) + let observed = a.subtractingWithSaturation(b) + if expected != observed { + print("Error found in (\(a)).subtractingWithSaturation(\(b)).") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + } + } + + func testSaturatingNegUnsigned() { + for a in UInt8.min ... UInt8.max { + let observed = a.negatedWithSaturation() + if 0 != observed { + print("Error found in (\(a)).negatedWithSaturation().") + print("Expected: zero") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + } + + func testSaturatingMulUnsigned() { + for a in UInt8.min ... UInt8.max { + for b in UInt8.min ... UInt8.max { + let expected = UInt8(clamping: UInt16(a) * UInt16(b)) + let observed = a.multipliedWithSaturation(by: b) + if expected != observed { + print("Error found in (\(a)).multipliedWithSaturation(by: \(b)).") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + } + } + } + } + + func testSaturatingShift( + _ value: T, _ count: C, rounding rule: RoundingRule + ) where T: FixedWidthInteger, C: FixedWidthInteger { + let observed = value.shiftedWithSaturation(leftBy: count, rounding: rule) + var expected: T = 0 + if count <= 0 { + expected = value.shifted(rightBy: -Int64(count), rounding: rule) + } else { + let multiplier: T = 1 << count + if multiplier <= 0 { + expected = value == 0 ? 0 : + value < 0 ? .min : .max + } else { + expected = value.multipliedWithSaturation(by: multiplier) + } + } + if observed != expected { + print("Error found in \(T.self).shiftedWithSaturation(leftBy: \(count), rounding: \(rule)).") + print(" Value: \(String(value, radix: 16))") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + + func testSaturatingShift( + _ type: T.Type, rounding rule: RoundingRule + ) { + for count in Int8.min ... .max { + testSaturatingShift(0, count, rounding: rule) + for bits in 0 ..< T.bitWidth { + let msb: T.Magnitude = 1 << bits + let value = T(truncatingIfNeeded: msb) | .random(in: 0 ... T(msb-1)) + testSaturatingShift(value, count, rounding: rule) + testSaturatingShift(0 &- value, count, rounding: rule) + } + } + } + + func testSaturatingShifts() { + testSaturatingShift(Int8.self, rounding: .toOdd) + testSaturatingShift(UInt8.self, rounding: .toOdd) + testSaturatingShift(Int.self, rounding: .toOdd) + testSaturatingShift(UInt.self, rounding: .toOdd) + } + + func testEdgeCaseForNegativeCount() { + XCTAssertEqual(1.shiftedWithSaturation(leftBy: Int.min), 0) + } + +} diff --git a/Tests/IntegerUtilitiesTests/ShiftTests.swift b/Tests/IntegerUtilitiesTests/ShiftTests.swift index 2fb609c..36b8185 100644 --- a/Tests/IntegerUtilitiesTests/ShiftTests.swift +++ b/Tests/IntegerUtilitiesTests/ShiftTests.swift @@ -16,9 +16,9 @@ import _TestSupport final class IntegerUtilitiesShiftTests: XCTestCase { - func testRoundingShift( - _ value: T, _ count: Int, rounding rule: RoundingRule - ) { + func testRoundingShift( + _ value: T, _ count: C, rounding rule: RoundingRule + ) where T: FixedWidthInteger, C: BinaryInteger { let floor = value >> count let lost = value &- floor << count let exact = count <= 0 || lost == 0 @@ -95,6 +95,10 @@ final class IntegerUtilitiesShiftTests: XCTestCase { testRoundingShift(T.random(in: .min ... .max), count, rounding: rule) } } + + for count in Int8.min ... .max { + testRoundingShift(T.random(in: .min ... .max), count, rounding: rule) + } } func testRoundingShifts() { diff --git a/Tests/RealTests/CMakeLists.txt b/Tests/RealTests/CMakeLists.txt index e7ea4ff..a46c475 100644 --- a/Tests/RealTests/CMakeLists.txt +++ b/Tests/RealTests/CMakeLists.txt @@ -9,8 +9,10 @@ See https://swift.org/LICENSE.txt for license information add_library(RealTests ApproximateEqualityTests.swift + AugmentedArithmeticTests.swift ElementaryFunctionChecks.swift - IntegerExponentTests.swift) + IntegerExponentTests.swift + RelaxedArithmeticTests.swift) target_compile_options(RealTests PRIVATE -enable-testing) target_link_libraries(RealTests PUBLIC diff --git a/Tests/RealTests/RelaxedArithmeticTests.swift b/Tests/RealTests/RelaxedArithmeticTests.swift new file mode 100644 index 0000000..5140c9b --- /dev/null +++ b/Tests/RealTests/RelaxedArithmeticTests.swift @@ -0,0 +1,129 @@ +//===--- RelaxedArithmeticTests.swift -------------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import RealModule +import _TestSupport +#if canImport(Accelerate) +import Accelerate +#endif + +#if !DEBUG +func strictSum(_ array: [T]) -> T { + array.reduce(0, +) +} + +func relaxedSum(_ array: [T]) -> T { + array.reduce(0, Relaxed.sum) +} + +func strictSumOfSquares(_ array: [T]) -> T { + array.reduce(0) { $0 + $1*$1 } +} + +func relaxedSumOfSquares(_ array: [T]) -> T { + array.reduce(0) { Relaxed.multiplyAdd($1, $1, $0) } +} + +// TODO: not a great harness, but making it better bumps up against the +// limitations of what XCT measure { } lets us do easily. Good enough for now. +func benchmarkReduction(_ data: [Float], _ reduction: ([Float]) -> Float) { + var accum: Float = 0 + let iters = 100_000 + for _ in 0 ..< iters { + accum += reduction(data) + } + blackHole(accum) +} + +final class RelaxedArithmeticTests: XCTestCase { + + var floatData: [Float] = [] + + override func setUp() { + super.setUp() + floatData = (0 ..< 1024).map { _ in .random(in: .sqrt(1/2) ..< .sqrt(2)) } + } + + func testStrictSumPerformance() { + measure { benchmarkReduction(floatData, strictSum) } + } + + func testRelaxedSumPerformance() { + // Performance of this should be closer to vDSP.sum than to + // strict sum + measure { benchmarkReduction(floatData, relaxedSum) } + } + +#if canImport(Accelerate) + func testvDSPSumPerformance() { + measure { benchmarkReduction(floatData, vDSP.sum) } + } +#endif + + func testStrictDotPerformance() { + measure { benchmarkReduction(floatData, strictSumOfSquares) } + } + + func testRelaxedDotPerformance() { + // Performance of this should be closer to vDSP.sumOfSquares than to + // strict sumOfSquares + measure { benchmarkReduction(floatData, relaxedSumOfSquares) } + } + +#if canImport(Accelerate) + func testvDSPDotPerformance() { + measure { benchmarkReduction(floatData, vDSP.sumOfSquares) } + } +#endif + + func testRelaxedArithmetic(_ type: T.Type) { + // Relaxed add is still an add; it's just permitted to reorder relative + // to other adds or form FMAs. So if we do one in isolation, it has to + // produce the same result as a normal addition. + let a = T.random(in: -1 ... 1) + let b = T.random(in: -1 ... 1) + XCTAssertEqual(a + b, Relaxed.sum(a, b)) + // Same is true for mul. + XCTAssertEqual(a * b, Relaxed.product(a, b)) + // add + mul must be either two operations or an FMA: + let unfused = a + 1.5 * b + let fused = a.addingProduct(1.5, b) + let relaxed = Relaxed.multiplyAdd(1.5, b, a) + XCTAssert(relaxed == unfused || relaxed == fused) + // Summing all values in an array can be associated however we want, but + // has to satisfy the usual error bound of 0.5 * sum.ulp * numberOfElements. + // We don't have a golden reference, but we can compare two sums with twice + // the bound for a sanity check. + let array = (0 ..< 128).map { _ in T.random(in: 1 ..< 2) } + var ref = strictSum(array) + var tst = relaxedSum(array) + var bound = max(ref, tst).ulp * T(array.count) + XCTAssertLessThanOrEqual(abs(ref - tst), bound) + // Similarly for sum of squares ... + ref = strictSumOfSquares(array) + tst = relaxedSumOfSquares(array) + bound = 2 * max(ref, tst).ulp * T(array.count) + XCTAssertLessThanOrEqual(abs(ref - tst), bound) + } + + func testRelaxedArithmetic() { +#if swift(>=5.4) && !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64)) + testRelaxedArithmetic(Float16.self) +#endif + testRelaxedArithmetic(Float.self) + testRelaxedArithmetic(Double.self) +#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android) + testRelaxedArithmetic(Float80.self) +#endif + } +} +#endif diff --git a/Tests/WindowsMain.swift b/Tests/WindowsMain.swift index 5ce400a..4c3c65b 100644 --- a/Tests/WindowsMain.swift +++ b/Tests/WindowsMain.swift @@ -67,6 +67,18 @@ extension IntegerExponentTests { } #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), @@ -107,6 +119,21 @@ extension IntegerUtilitiesRotateTests { ]) } +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), @@ -158,6 +185,7 @@ var testCases = [ IntegerUtilitiesGCDTests.all, IntegerUtilitiesRotateTests.all, IntegerUtilitiesShiftTests.all, + IntegerUtilitiesSaturatingTests.all, IntegerUtilitiesTests.DoubleWidthTests.all, ]