File size: 201,970 Bytes
6503d28 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | {"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Package.swift", "content": "// swift-tools-version:5.9\n//===--- Package.swift ----------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageDescription\n\nlet excludedFilenames = [\"CMakeLists.txt\", \"README.md\"]\n\nlet package = Package(\n \n name: \"swift-numerics\",\n products: [\n .library(name: \"ComplexModule\", targets: [\"ComplexModule\"]),\n .library(name: \"Numerics\", targets: [\"Numerics\"]),\n .library(name: \"RealModule\", targets: [\"RealModule\"]),\n ],\n \n targets: [\n // MARK: - Public API\n .target(\n name: \"ComplexModule\",\n dependencies: [\"RealModule\"],\n exclude: excludedFilenames\n ),\n \n .target(\n name: \"IntegerUtilities\",\n dependencies: [],\n exclude: excludedFilenames\n ),\n \n .target(\n name: \"Numerics\",\n dependencies: [\"ComplexModule\", \"IntegerUtilities\", \"RealModule\"],\n exclude: excludedFilenames\n ),\n \n .target(\n name: \"RealModule\",\n dependencies: [\"_NumericsShims\"],\n exclude: excludedFilenames,\n swiftSettings: [\n .enableExperimentalFeature(\"BuiltinModule\")\n ],\n linkerSettings: [\n .linkedLibrary(\"m\", .when(platforms: [.linux, .android]))\n ]\n ),\n \n // MARK: - Implementation details\n .target(\n name: \"_NumericsShims\",\n exclude: excludedFilenames\n ),\n \n .target(\n name: \"_TestSupport\",\n dependencies: [\"Numerics\"],\n exclude: [\"CMakeLists.txt\"]\n ),\n \n // MARK: - Unit test bundles\n .testTarget(\n name: \"ComplexTests\",\n dependencies: [\"_TestSupport\"],\n exclude: [\"CMakeLists.txt\"]\n ),\n \n .testTarget(\n name: \"IntegerUtilitiesTests\",\n dependencies: [\"IntegerUtilities\", \"_TestSupport\"],\n exclude: [\"CMakeLists.txt\"]\n ),\n \n .testTarget(\n name: \"RealTests\",\n dependencies: [\"_TestSupport\"],\n exclude: [\"CMakeLists.txt\"]\n )\n ]\n)"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "ElementaryFunctionChecks.swift", "content": "//===--- ElementaryFunctionChecks.swift ------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nimport XCTest\nimport RealModule\nimport _TestSupport\n\n#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)\npublic typealias TestLiteralType = Float80\n#else\npublic typealias TestLiteralType = Double\n#endif\n\n@discardableResult\ninternal func assertClose<T>(\n _ expected: TestLiteralType,\n _ observed: T,\n allowedError: T = 16,\n file: StaticString = #file,\n line: UInt = #line\n) -> T where T: BinaryFloatingPoint {\n // Shortcut relative-error check if we got the sign wrong; it's OK to\n // underflow to zero, but we do not want to allow going right through\n // zero and getting the sign wrong.\n guard observed.sign == expected.sign else {\n print(\"Sign was wrong: expected \\(expected) but saw \\(observed).\")\n XCTFail(file: file, line: line)\n return .infinity\n }\n if observed.isNaN && expected.isNaN { return 0 }\n // If T(expected) is zero or infinite, and matches observed, the error\n // is zero.\n let expectedT = T(expected)\n if observed.isZero && expectedT.isZero { return 0 }\n if observed.isInfinite && expectedT.isInfinite { return 0 }\n // Special-case where only one of expectedT or observed is infinity.\n // Artificially knock everything down a binade, treat actual infinity as\n // the base of the next binade up.\n func topBinade(signOf x: T) -> T {\n T(signOf: x, magnitudeOf: T.greatestFiniteMagnitude.binade)\n }\n if observed.isInfinite {\n return assertClose(\n expected/2, topBinade(signOf: observed),\n allowedError: allowedError, file: file, line: line\n )\n }\n if expectedT.isInfinite {\n return assertClose(\n TestLiteralType(topBinade(signOf: expectedT)), observed/2,\n allowedError: allowedError, file: file, line: line\n )\n }\n // Compute error in ulp, compare to tolerance.\n let absoluteError = (TestLiteralType(observed) - expected).magnitude\n let scale = max(expectedT.magnitude, T.leastNormalMagnitude).ulp\n let ulps = T(absoluteError/TestLiteralType(scale))\n if ulps > allowedError {\n print(\"ULP error was unacceptably large: expected \\(expected) but saw \\(observed) (\\(ulps)-ulp error).\")\n XCTFail(file: file, line: line)\n }\n return ulps\n}\n\ninternal func assertClose<T>(\n _ expected: TestLiteralType,\n _ observed: T,\n allowedError: T = 16,\n worstError: inout T,\n file: StaticString = #file,\n line: UInt = #line\n) where T: BinaryFloatingPoint {\n worstError = max(worstError, assertClose(\n expected, observed, allowedError: allowedError, file: file, line: line\n ))\n}\n\ninternal extension ElementaryFunctions where Self: BinaryFloatingPoint {\n static func elementaryFunctionChecks() {\n assertClose(1.1863995522992575361931268186727044683, Self.acos(0.375))\n assertClose(0.3843967744956390830381948729670469737, Self.asin(0.375))\n assertClose(0.3587706702705722203959200639264604997, Self.atan(0.375))\n assertClose(0.9305076219123142911494767922295555080, Self.cos(0.375))\n assertClose(0.3662725290860475613729093517162641571, Self.sin(0.375))\n assertClose(0.3936265759256327582294137871012180981, Self.tan(0.375))\n assertClose(0.4949329230945269058895630995767185785, Self.acosh(1.125))\n assertClose(0.9670596312833237113713762009167286709, Self.asinh(1.125))\n assertClose(0.7331685343967135223291211023213964500, Self.atanh(0.625))\n assertClose(1.0711403467045867672994980155670160493, Self.cosh(0.375))\n assertClose(0.3838510679136145687542956764205024589, Self.sinh(0.375))\n assertClose(0.3583573983507859463193602315531580424, Self.tanh(0.375))\n assertClose(1.4549914146182013360537936919875185083, Self.exp(0.375))\n assertClose(0.4549914146182013360537936919875185083, Self.expMinusOne(0.375))\n assertClose(-0.980829253011726236856451127452003999, Self.log(0.375))\n assertClose(0.3184537311185346158102472135905995955, Self.log(onePlus: 0.375))\n assertClose(-0.7211247851537041911608191553900547941, Self.root(-0.375, 3))\n XCTAssertEqual(-10, Self.root(-1000, 3))\n assertClose(0.6123724356957945245493210186764728479, Self.sqrt(0.375))\n assertClose(0.54171335479545025876069682133938570, Self.pow(0.375, 0.625))\n assertClose(-0.052734375, Self.pow(-0.375, 3))\n }\n}\n\ninternal extension Real where Self: BinaryFloatingPoint {\n static func realFunctionChecks() {\n assertClose(1.2968395546510096659337541177924511598, Self.exp2(0.375))\n assertClose(2.3713737056616552616517527574788898386, Self.exp10(0.375))\n assertClose(-1.415037499278843818546261056052183491, Self.log2(0.375))\n assertClose(-0.425968732272281148346188780918363771, Self.log10(0.375))\n assertClose(0.54041950027058415544357836460859991, Self.atan2(y: 0.375, x: 0.625))\n assertClose(0.72886898685566255885926910969319788, Self.hypot(0.375, 0.625))\n assertClose(0.4041169094348222983238250859191217675, Self.erf(0.375))\n assertClose(0.5958830905651777016761749140808782324, Self.erfc(0.375))\n assertClose(2.3704361844166009086464735041766525098, Self.gamma(0.375))\n#if !os(Windows)\n assertClose( -0.11775527074107877445136203331798850, Self.logGamma(1.375))\n XCTAssertEqual(.plus, Self.signGamma(1.375))\n XCTAssertEqual(.minus, Self.signGamma(-2.375))\n#endif\n }\n}\n\nextension Real {\n static func powZeroChecks() {\n // pow(_:Self,_:Self) is defined by exp(y log(x)) and has edge-cases to\n // match. In particular, if x is zero, log(x) is -infinity, so pow(0,0)\n // is exp(0 * -infinity) = exp(nan) = nan.\n XCTAssertEqual(pow(0, -1 as Self), infinity)\n XCTAssert(pow(0, 0 as Self).isNaN)\n XCTAssertEqual(pow(0, 1 as Self), zero)\n // pow(_:Self,_:Int) is defined by repeated multiplication or division,\n // and hence pow(0, 0) is 1.\n XCTAssertEqual(pow(0, -1), infinity)\n XCTAssertEqual(pow(0, 0), 1)\n XCTAssertEqual(pow(0, 1), zero)\n }\n}\n\nfinal class ElementaryFunctionChecks: XCTestCase {\n \n#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))\n func testFloat16() {\n if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {\n Float16.elementaryFunctionChecks()\n Float16.realFunctionChecks()\n Float16.powZeroChecks()\n }\n }\n#endif\n \n func testFloat() {\n Float.elementaryFunctionChecks()\n Float.realFunctionChecks()\n Float.powZeroChecks()\n }\n \n func testDouble() {\n Double.elementaryFunctionChecks()\n Double.realFunctionChecks()\n Double.powZeroChecks()\n }\n \n#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)\n func testFloat80() {\n Float80.elementaryFunctionChecks()\n Float80.realFunctionChecks()\n Float80.powZeroChecks()\n }\n#endif\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "DoubleWidth.swift", "content": "//===--- DoubleWidth.swift ------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2017-2024 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// A fixed-width integer that has twice the bit width of its base type.\n///\n/// You can use the `DoubleWidth` type to continue calculations with the result\n/// of a full width arithmetic operation. Normally, when you perform a full\n/// width operation, the result is a tuple of the high and low parts of the\n/// result.\n///\n/// let a = 2241543570477705381\n/// let b = 186319822866995413\n/// let c = a.multipliedFullWidth(by: b)\n/// // c == (high: 22640526660490081, low: 7959093232766896457)\n///\n/// The tuple `c` can't be used in any further comparisons or calculations. To\n/// use this value, create a `DoubleWidth` instance from the result. You can\n/// use the `DoubleWidth` instance in the same way that you would use any other\n/// integer type.\n///\n/// let d = DoubleWidth(a.multipliedFullWidth(by: b))\n/// // d == 417644001000058515200174966092417353\n///\n/// // Check the calculation:\n/// print(d / DoubleWidth(a) == b)\n/// // Prints \"true\"\n///\n/// if d > Int.max {\n/// print(\"Too big to be an 'Int'!\")\n/// } else {\n/// print(\"Small enough to fit in an 'Int'\")\n/// }\n/// // Prints \"Too big to be an 'Int'!\"\n///\n/// The `DoubleWidth` type is not intended as a replacement for a variable-width\n/// integer type. Nesting `DoubleWidth` instances, in particular, may result in\n/// undesirable performance.\npublic struct DoubleWidth<Base : FixedWidthInteger> {\n public typealias High = Base\n public typealias Low = Base.Magnitude\n\n internal var _storage: (low: Low, high: High)\n}\n\nextension DoubleWidth {\n /// The \"high word\" of this value.\n ///\n /// Equivalent to `Base(self >> Base.bitWidth)`.\n public var high: High {\n return _storage.high\n }\n\n /// The \"low word\" of the value.\n ///\n /// Equivalent to`Base.Magnitude(truncatingIfNecessary: self)`.\n public var low: Low {\n return _storage.low\n }\n\n /// Creates a new instance from the given tuple of high and low parts.\n ///\n /// Equivalent to\n /// ```\n /// DoubleWidth<Base>(high) << Base.bitWidth + DoubleWidth<Base>(low)\n /// ```\n ///\n /// - Parameter value: The tuple to use as the source of the new instance's\n /// high and low parts.\n public init(_ value: (high: High, low: Low)) {\n self._storage = (low: value.low, high: value.high)\n }\n\n // We expect users to invoke the public initializer above as demonstrated in\n // the documentation (that is, by passing in the result of a full width\n // operation).\n //\n // Internally, we'll need to create new instances by supplying high and low\n // parts directly; ((double parentheses)) greatly impair readability,\n // especially when nested:\n //\n // DoubleWidth<DoubleWidth>((DoubleWidth((0, 0)), DoubleWidth((0, 0))))\n //\n // For that reason, we'll include an internal initializer that takes two\n // separate arguments.\n \n /// Creates a new instance from the given tuple of high and low parts.\n ///\n /// Equivalent to\n /// ```\n /// DoubleWidth<Base>(high) << Base.bitWidth + DoubleWidth<Base>(low)\n /// ```\n internal init(_ _high: High, _ low: Low) {\n self.init((_high, low))\n }\n \n /// Zero.\n public init() {\n self.init(0, 0)\n }\n}\n\nextension DoubleWidth : CustomStringConvertible {\n public var description: String {\n return String(self, radix: 10)\n }\n}\n\nextension DoubleWidth : CustomDebugStringConvertible {\n public var debugDescription: String {\n return \"(\\(_storage.high), \\(_storage.low))\"\n }\n}\n\nextension DoubleWidth : Equatable {\n public static func ==(lhs: DoubleWidth, rhs: DoubleWidth) -> Bool {\n return lhs._storage.low == rhs._storage.low\n && lhs._storage.high == rhs._storage.high\n }\n}\n\nextension DoubleWidth : Comparable {\n public static func <(lhs: DoubleWidth, rhs: DoubleWidth) -> Bool {\n if lhs._storage.high < rhs._storage.high { return true }\n else if lhs._storage.high > rhs._storage.high { return false }\n else { return lhs._storage.low < rhs._storage.low }\n }\n}\n\nextension DoubleWidth : Hashable {\n public func hash(into hasher: inout Hasher) {\n hasher.combine(low)\n hasher.combine(high)\n }\n}\n\nextension DoubleWidth : Numeric {\n public typealias Magnitude = DoubleWidth<Low>\n\n public var magnitude: Magnitude {\n let result = Magnitude(Low(truncatingIfNeeded: _storage.high), _storage.low)\n if Base.isSigned && _storage.high < (0 as High) {\n return ~result &+ 1\n } else {\n return result\n }\n }\n\n internal init(_ _magnitude: Magnitude) {\n self.init(High(_magnitude._storage.high), _magnitude._storage.low)\n }\n\n public init<T : BinaryInteger>(_ source: T) {\n guard let result = DoubleWidth<Base>(exactly: source) else {\n preconditionFailure(\"Value is outside the representable range\")\n }\n self = result\n }\n\n public init?<T : BinaryInteger>(exactly source: T) {\n // Can't represent a negative 'source' if Base is unsigned.\n guard DoubleWidth.isSigned || source >= 0 else { return nil }\n \n // Is 'source' entirely representable in Low?\n if let low = Low(exactly: source.magnitude) {\n self.init(source < (0 as T) ? (~0, ~low &+ 1) : (0, low))\n } else {\n // At this point we know source.bitWidth > Base.bitWidth, or else we\n // would've taken the first branch.\n let lowInT = source & T(~0 as Low)\n let highInT = source >> Low.bitWidth\n \n let low = Low(lowInT)\n guard let high = High(exactly: highInT) else { return nil }\n self.init(high, low)\n }\n }\n}\n\nextension DoubleWidth {\n public struct Words {\n public var _high: High.Words\n public var _low: Low.Words\n\n public init(_ value: DoubleWidth<Base>) {\n // Multiples of word size only.\n guard Base.bitWidth == Base.Magnitude.bitWidth &&\n (UInt.bitWidth % Base.bitWidth == 0 ||\n Base.bitWidth % UInt.bitWidth == 0) else {\n fatalError(\"Access to words is not supported on this type\")\n }\n self._high = value._storage.high.words\n self._low = value._storage.low.words\n assert(!_low.isEmpty)\n }\n }\n}\n\nextension DoubleWidth.Words: RandomAccessCollection {\n public typealias Index = Int\n \n public var startIndex: Index {\n return 0\n }\n\n public var endIndex: Index {\n return count\n }\n \n public var count: Int {\n if Base.bitWidth < UInt.bitWidth { return 1 }\n return _low.count + _high.count\n }\n\n public subscript(_ i: Index) -> UInt {\n if Base.bitWidth < UInt.bitWidth {\n precondition(i == 0, \"Invalid index\")\n assert(2 * Base.bitWidth <= UInt.bitWidth)\n return _low.first! | (_high.first! &<< Base.bitWidth._lowWord) \n }\n if i < _low.count {\n return _low[i + _low.startIndex]\n }\n \n return _high[i - _low.count + _high.startIndex]\n }\n}\n\nextension DoubleWidth : FixedWidthInteger {\n public var words: Words {\n return Words(self)\n }\n\n public static var isSigned: Bool {\n return Base.isSigned\n }\n\n public static var max: DoubleWidth {\n return self.init(High.max, Low.max)\n }\n\n public static var min: DoubleWidth {\n return self.init(High.min, Low.min)\n }\n\n public static var bitWidth: Int {\n return High.bitWidth + Low.bitWidth\n }\n\n public func addingReportingOverflow(_ rhs: DoubleWidth)\n -> (partialValue: DoubleWidth, overflow: Bool) {\n let (low, lowOverflow) =\n _storage.low.addingReportingOverflow(rhs._storage.low)\n let (high, highOverflow) =\n _storage.high.addingReportingOverflow(rhs._storage.high)\n let result = (high &+ (lowOverflow ? 1 : 0), low)\n let overflow = highOverflow ||\n high == Base.max && lowOverflow\n return (partialValue: DoubleWidth(result), overflow: overflow)\n }\n public func subtractingReportingOverflow(_ rhs: DoubleWidth)\n -> (partialValue: DoubleWidth, overflow: Bool) {\n let (low, lowOverflow) =\n _storage.low.subtractingReportingOverflow(rhs._storage.low)\n let (high, highOverflow) =\n _storage.high.subtractingReportingOverflow(rhs._storage.high)\n let result = (high &- (lowOverflow ? 1 : 0), low)\n let overflow = highOverflow ||\n high == Base.min && lowOverflow\n return (partialValue: DoubleWidth(result), overflow: overflow)\n }\n\n public func multipliedReportingOverflow(\n by rhs: DoubleWidth\n ) -> (partialValue: DoubleWidth, overflow: Bool) {\n let (carry, product) = multipliedFullWidth(by: rhs)\n let partialValue = DoubleWidth(truncatingIfNeeded: product)\n // Overflow has occured if carry is not just the sign-extension of\n // partialValue (which is zero when Base is unsigned).\n let overflow = carry != (partialValue >> DoubleWidth.bitWidth)\n return (partialValue, overflow)\n }\n\n public func quotientAndRemainder(\n dividingBy other: DoubleWidth\n ) -> (quotient: DoubleWidth, remainder: DoubleWidth) {\n let (quotient, remainder) =\n Magnitude._divide(self.magnitude, by: other.magnitude)\n guard DoubleWidth.isSigned else {\n return (DoubleWidth(quotient), DoubleWidth(remainder))\n }\n let isNegative = (self.high < (0 as High)) != (other.high < (0 as High))\n let quotient_ = isNegative\n ? quotient == DoubleWidth.min.magnitude\n ? DoubleWidth.min\n : 0 - DoubleWidth(quotient)\n : DoubleWidth(quotient)\n let remainder_ = self.high < (0 as High)\n ? 0 - DoubleWidth(remainder)\n : DoubleWidth(remainder)\n return (quotient_, remainder_)\n }\n\n public func dividedReportingOverflow(\n by other: DoubleWidth\n ) -> (partialValue: DoubleWidth, overflow: Bool) {\n if other == (0 as DoubleWidth) { return (self, true) }\n if DoubleWidth.isSigned && other == -1 && self == .min {\n return (self, true)\n }\n return (quotientAndRemainder(dividingBy: other).quotient, false)\n }\n\n public func remainderReportingOverflow(\n dividingBy other: DoubleWidth\n ) -> (partialValue: DoubleWidth, overflow: Bool) {\n if other == (0 as DoubleWidth) { return (self, true) }\n if DoubleWidth.isSigned && other == -1 && self == .min { return (0, true) }\n return (quotientAndRemainder(dividingBy: other).remainder, false)\n }\n \n // When using a pre-Swift 6.0 runtime, `&*` is not a protocol requirement of\n // FixedWidthInteger, which results in the default implementation of this\n // operation ending up recursively calling itself forever. In order to avoid\n // this, we keep the concrete implementation around.\n public func multipliedFullWidth(\n by other: DoubleWidth\n ) -> (high: DoubleWidth, low: DoubleWidth.Magnitude) {\n let isNegative = DoubleWidth.isSigned &&\n (self < (0 as DoubleWidth)) != (other < (0 as DoubleWidth))\n\n func mul(_ x: Low, _ y: Low) -> (partial: Low, carry: Low) {\n let (high, low) = x.multipliedFullWidth(by: y)\n return (low, high)\n }\n \n func sum(_ x: Low, _ y: Low, _ z: Low) -> (partial: Low, carry: Low) {\n let (sum1, overflow1) = x.addingReportingOverflow(y)\n let (sum2, overflow2) = sum1.addingReportingOverflow(z)\n let carry: Low = (overflow1 ? 1 : 0) + (overflow2 ? 1 : 0)\n return (sum2, carry)\n }\n \n let lhs = self.magnitude\n let rhs = other.magnitude\n \n let a = mul(rhs._storage.low, lhs._storage.low)\n let b = mul(rhs._storage.low, lhs._storage.high)\n let c = mul(rhs._storage.high, lhs._storage.low)\n let d = mul(rhs._storage.high, lhs._storage.high)\n \n let mid1 = sum(a.carry, b.partial, c.partial)\n let mid2 = sum(b.carry, c.carry, d.partial)\n \n let low =\n DoubleWidth<Low>(mid1.partial, a.partial)\n let (sum_, overflow_) =\n mid1.carry.addingReportingOverflow(mid2.partial)\n let high =\n DoubleWidth(High(mid2.carry + d.carry + (overflow_ ? 1 : 0)), sum_)\n \n if isNegative {\n let (lowComplement, overflow) = (~low).addingReportingOverflow(1)\n return (~high + (overflow ? 1 : 0 as DoubleWidth), lowComplement)\n } else {\n return (high, low)\n }\n }\n\n public func dividingFullWidth(\n _ dividend: (high: DoubleWidth, low: DoubleWidth.Magnitude)\n ) -> (quotient: DoubleWidth, remainder: DoubleWidth) {\n let other = DoubleWidth<DoubleWidth>(dividend)\n let (quotient, remainder) =\n Magnitude._divide(other.magnitude, by: self.magnitude)\n guard DoubleWidth.isSigned else {\n return (DoubleWidth(quotient), DoubleWidth(remainder))\n }\n let isNegative =\n (self.high < (0 as High)) != (other.high.high < (0 as High))\n let quotient_ = isNegative\n ? quotient == DoubleWidth.min.magnitude\n ? DoubleWidth.min\n : 0 - DoubleWidth(quotient)\n : DoubleWidth(quotient)\n let remainder_ = other.high.high < (0 as High)\n ? 0 - DoubleWidth(remainder)\n : DoubleWidth(remainder)\n return (quotient_, remainder_)\n }\n\n public static func &=(\n lhs: inout DoubleWidth, rhs: DoubleWidth\n ) {\n lhs._storage.low &= rhs._storage.low\n lhs._storage.high &= rhs._storage.high\n }\n public static func |=(\n lhs: inout DoubleWidth, rhs: DoubleWidth\n ) {\n lhs._storage.low |= rhs._storage.low\n lhs._storage.high |= rhs._storage.high\n }\n public static func ^=(\n lhs: inout DoubleWidth, rhs: DoubleWidth\n ) {\n lhs._storage.low ^= rhs._storage.low\n lhs._storage.high ^= rhs._storage.high\n }\n\n public static func <<=(lhs: inout DoubleWidth, rhs: DoubleWidth) {\n if DoubleWidth.isSigned && rhs < (0 as DoubleWidth) {\n lhs >>= 0 - rhs\n return\n }\n \n // Shift is larger than this type's bit width.\n if rhs._storage.high != (0 as High) ||\n rhs._storage.low >= DoubleWidth.bitWidth\n {\n lhs = 0\n return\n }\n\n lhs &<<= rhs\n }\n \n public static func >>=(lhs: inout DoubleWidth, rhs: DoubleWidth) {\n if DoubleWidth.isSigned && rhs < (0 as DoubleWidth) {\n lhs <<= 0 - rhs\n return\n }\n\n // Shift is larger than this type's bit width.\n if rhs._storage.high != (0 as High) ||\n rhs._storage.low >= DoubleWidth.bitWidth\n {\n lhs = lhs < (0 as DoubleWidth) ? ~0 : 0\n return\n }\n\n lhs &>>= rhs\n }\n\n /// Returns this value \"masked\" by its bit width.\n ///\n /// \"Masking\" notionally involves repeatedly incrementing or decrementing\n /// this value by `self.bitWidth` until the result is contained in the\n /// range `0..<self.bitWidth`.\n internal func _masked() -> DoubleWidth {\n let bits = DoubleWidth(DoubleWidth.bitWidth)\n if DoubleWidth.bitWidth.nonzeroBitCount == 1 {\n return self & (bits &- 1)\n }\n let reduced = self % bits\n // bitWidth is always positive, but the value being reduced might have\n // been negative, in which case reduced will also be negative. We need\n // the representative in [0, bitWidth), so conditionally add the count\n // to get the positive residue.\n if Base.isSigned && reduced < 0 { return reduced &+ bits }\n return reduced\n }\n\n public static func &<<=(lhs: inout DoubleWidth, rhs: DoubleWidth) {\n let rhs = rhs._masked()\n\n guard rhs._storage.low < Base.bitWidth else {\n lhs._storage.high = High(\n truncatingIfNeeded: lhs._storage.low &<<\n (rhs._storage.low &- Low(Base.bitWidth)))\n lhs._storage.low = 0\n return\n }\n\n guard rhs._storage.low != (0 as Low) else { return }\n lhs._storage.high &<<= High(rhs._storage.low)\n lhs._storage.high |= High(\n truncatingIfNeeded: lhs._storage.low &>>\n (Low(Base.bitWidth) &- rhs._storage.low))\n lhs._storage.low &<<= rhs._storage.low\n }\n \n public static func &>>=(lhs: inout DoubleWidth, rhs: DoubleWidth) {\n let rhs = rhs._masked()\n\n guard rhs._storage.low < Base.bitWidth else {\n lhs._storage.low = Low(\n truncatingIfNeeded: lhs._storage.high &>>\n High(rhs._storage.low &- Low(Base.bitWidth)))\n lhs._storage.high = lhs._storage.high < (0 as High) ? ~0 : 0\n return\n }\n\n guard rhs._storage.low != (0 as Low) else { return }\n lhs._storage.low &>>= rhs._storage.low\n lhs._storage.low |= Low(\n truncatingIfNeeded: lhs._storage.high &<<\n High(Low(Base.bitWidth) &- rhs._storage.low))\n lhs._storage.high &>>= High(rhs._storage.low)\n }\n \n\n // FIXME(integers): remove this once the operators are back to Numeric\n public static func + (\n lhs: DoubleWidth, rhs: DoubleWidth\n ) -> DoubleWidth {\n var lhs = lhs\n lhs += rhs\n return lhs\n }\n\n public static func +=(\n lhs: inout DoubleWidth, rhs: DoubleWidth\n ) {\n let (result, overflow) = lhs.addingReportingOverflow(rhs)\n precondition(!overflow, \"Overflow in +=\")\n lhs = result\n }\n\n // FIXME(integers): remove this once the operators are back to Numeric\n public static func - (\n lhs: DoubleWidth, rhs: DoubleWidth\n ) -> DoubleWidth {\n var lhs = lhs\n lhs -= rhs\n return lhs\n }\n\n public static func -=(\n lhs: inout DoubleWidth, rhs: DoubleWidth\n ) {\n let (result, overflow) = lhs.subtractingReportingOverflow(rhs)\n precondition(!overflow, \"Overflow in -=\")\n lhs = result\n }\n\n // FIXME(integers): remove this once the operators are back to Numeric\n public static func * (\n lhs: DoubleWidth, rhs: DoubleWidth\n ) -> DoubleWidth {\n var lhs = lhs\n lhs *= rhs\n return lhs\n }\n\n public static func *=(\n lhs: inout DoubleWidth, rhs: DoubleWidth\n ) {\n let (result, overflow) = lhs.multipliedReportingOverflow(by:rhs)\n precondition(!overflow, \"Overflow in *=\")\n lhs = result\n }\n\n // FIXME(integers): remove this once the operators are back to Numeric\n public static func / (\n lhs: DoubleWidth, rhs: DoubleWidth\n ) -> DoubleWidth {\n var lhs = lhs\n lhs /= rhs\n return lhs\n }\n\n public static func /=(\n lhs: inout DoubleWidth, rhs: DoubleWidth\n ) {\n let (result, overflow) = lhs.dividedReportingOverflow(by:rhs)\n precondition(!overflow, \"Overflow in /=\")\n lhs = result\n }\n\n // FIXME(integers): remove this once the operators are back to Numeric\n public static func % (\n lhs: DoubleWidth, rhs: DoubleWidth\n ) -> DoubleWidth {\n var lhs = lhs\n lhs %= rhs\n return lhs\n }\n\n public static func %=(\n lhs: inout DoubleWidth, rhs: DoubleWidth\n ) {\n let (result, overflow) = lhs.remainderReportingOverflow(dividingBy:rhs)\n precondition(!overflow, \"Overflow in %=\")\n lhs = result\n }\n \n public static func &+(\n lhs: DoubleWidth, rhs: DoubleWidth\n ) -> DoubleWidth {\n let (low, carry) = lhs.low.addingReportingOverflow(rhs.low)\n let high = lhs.high &+ rhs.high &+ (carry ? 1 : 0)\n return DoubleWidth(high, low)\n }\n \n public static func &-(\n lhs: DoubleWidth, rhs: DoubleWidth\n ) -> DoubleWidth {\n let (low, borrow) = lhs.low.subtractingReportingOverflow(rhs.low)\n let high = lhs.high &- rhs.high &- (borrow ? 1 : 0)\n return DoubleWidth(high, low)\n }\n \n public static func &*(\n lhs: DoubleWidth, rhs: DoubleWidth\n ) -> DoubleWidth {\n let p00 = lhs.low.multipliedFullWidth(by: rhs.low)\n let p10 = lhs.high &* Base(truncatingIfNeeded: rhs.low)\n let p01 = Base(truncatingIfNeeded: lhs.low) &* rhs.high\n return DoubleWidth(p10 &+ p01 &+ Base(truncatingIfNeeded: p00.high), p00.low)\n }\n\n public init(_truncatingBits bits: UInt) {\n _storage.low = Low(_truncatingBits: bits)\n _storage.high = High(_truncatingBits: bits >> UInt(Low.bitWidth))\n }\n\n public init(integerLiteral x: Int) {\n self.init(x)\n }\n public var leadingZeroBitCount: Int {\n return high == (0 as High)\n ? High.bitWidth + low.leadingZeroBitCount\n : high.leadingZeroBitCount\n }\n\n public var trailingZeroBitCount: Int {\n return low == (0 as Low)\n ? Low.bitWidth + high.trailingZeroBitCount\n : low.trailingZeroBitCount\n }\n\n public var nonzeroBitCount: Int {\n return high.nonzeroBitCount + low.nonzeroBitCount\n }\n\n public var byteSwapped: DoubleWidth {\n return DoubleWidth(\n High(truncatingIfNeeded: low.byteSwapped),\n Low(truncatingIfNeeded: high.byteSwapped))\n }\n}\n\nextension DoubleWidth : UnsignedInteger where Base : UnsignedInteger {\n /// Returns the quotient and remainder after dividing a triple-width magnitude\n /// `lhs` by a double-width magnitude `rhs`.\n ///\n /// This operation is conceptually that described by Burnikel and Ziegler\n /// (1998).\n internal static func _divide(\n _ lhs: (high: Low, mid: Low, low: Low), by rhs: Magnitude\n ) -> (quotient: Low, remainder: Magnitude) {\n // The following invariants are guaranteed to hold by dividingFullWidth or\n // quotientAndRemainder before this method is invoked:\n assert(rhs.leadingZeroBitCount == 0)\n assert(Magnitude(lhs.high, lhs.mid) < rhs)\n\n guard lhs.high != (0 as Low) else {\n let lhs_ = Magnitude(lhs.mid, lhs.low)\n return lhs_ < rhs ? (0, lhs_) : (1, lhs_ &- rhs)\n }\n\n // Estimate the quotient.\n var quotient = lhs.high == rhs.high\n ? Low.max\n : rhs.high.dividingFullWidth((lhs.high, lhs.mid)).quotient\n // Compute quotient * rhs.\n // TODO: This could be performed more efficiently.\n var product =\n DoubleWidth<Magnitude>(\n 0, Magnitude(quotient.multipliedFullWidth(by: rhs.low)))\n let (x, y) = quotient.multipliedFullWidth(by: rhs.high)\n product += DoubleWidth<Magnitude>(Magnitude(0, x), Magnitude(y, 0))\n // Compute the remainder after decrementing quotient as necessary.\n var remainder =\n DoubleWidth<Magnitude>(\n Magnitude(0, lhs.high), Magnitude(lhs.mid, lhs.low))\n while remainder < product {\n quotient = quotient &- 1\n remainder += DoubleWidth<Magnitude>(0, rhs)\n }\n remainder -= product\n\n return (quotient, remainder.low)\n }\n\n /// Returns the quotient and remainder after dividing a quadruple-width\n /// magnitude `lhs` by a double-width magnitude `rhs`.\n internal static func _divide(\n _ lhs: DoubleWidth<Magnitude>, by rhs: Magnitude\n ) -> (quotient: Magnitude, remainder: Magnitude) {\n guard _fastPath(rhs > (0 as Magnitude)) else {\n fatalError(\"Division by zero\")\n }\n guard _fastPath(rhs >= lhs.high) else {\n fatalError(\"Division results in an overflow\")\n }\n\n if lhs.high == (0 as Magnitude) {\n return lhs.low.quotientAndRemainder(dividingBy: rhs)\n }\n\n if rhs.high == (0 as Low) {\n let a = lhs.high.high % rhs.low\n let b = a == (0 as Low)\n ? lhs.high.low % rhs.low\n : rhs.low.dividingFullWidth((a, lhs.high.low)).remainder\n let (x, c) = b == (0 as Low)\n ? lhs.low.high.quotientAndRemainder(dividingBy: rhs.low)\n : rhs.low.dividingFullWidth((b, lhs.low.high))\n let (y, d) = c == (0 as Low)\n ? lhs.low.low.quotientAndRemainder(dividingBy: rhs.low)\n : rhs.low.dividingFullWidth((c, lhs.low.low))\n return (Magnitude(x, y), Magnitude(0, d))\n }\n\n // Left shift both rhs and lhs, then divide and right shift the remainder.\n let shift = rhs.leadingZeroBitCount\n let rhs = rhs &<< shift\n let lhs = lhs &<< shift\n if lhs.high.high == (0 as Low)\n && Magnitude(lhs.high.low, lhs.low.high) < rhs {\n let (quotient, remainder) =\n Magnitude._divide((lhs.high.low, lhs.low.high, lhs.low.low), by: rhs)\n return (Magnitude(0, quotient), remainder &>> shift)\n }\n let (x, a) =\n Magnitude._divide((lhs.high.high, lhs.high.low, lhs.low.high), by: rhs)\n let (y, b) =\n Magnitude._divide((a.high, a.low, lhs.low.low), by: rhs)\n return (Magnitude(x, y), b &>> shift)\n }\n\n /// Returns the quotient and remainder after dividing a double-width\n /// magnitude `lhs` by a double-width magnitude `rhs`.\n internal static func _divide(\n _ lhs: Magnitude, by rhs: Magnitude\n ) -> (quotient: Magnitude, remainder: Magnitude) {\n guard _fastPath(rhs > (0 as Magnitude)) else {\n fatalError(\"Division by zero\")\n }\n guard rhs < lhs else {\n if _fastPath(rhs > lhs) { return (0, lhs) }\n return (1, 0)\n }\n\n if lhs.high == (0 as Low) {\n let (quotient, remainder) =\n lhs.low.quotientAndRemainder(dividingBy: rhs.low)\n return (Magnitude(quotient), Magnitude(remainder))\n }\n\n if rhs.high == (0 as Low) {\n let (x, a) = lhs.high.quotientAndRemainder(dividingBy: rhs.low)\n let (y, b) = a == (0 as Low)\n ? lhs.low.quotientAndRemainder(dividingBy: rhs.low)\n : rhs.low.dividingFullWidth((a, lhs.low))\n return (Magnitude(x, y), Magnitude(0, b))\n }\n\n // Left shift both rhs and lhs, then divide and right shift the remainder.\n let shift = rhs.leadingZeroBitCount\n // Note the use of `>>` instead of `&>>` below,\n // as `high` should be zero if `shift` is zero.\n let high = (lhs >> (Magnitude.bitWidth &- shift)).low\n let rhs = rhs &<< shift\n let lhs = lhs &<< shift\n let (quotient, remainder) =\n Magnitude._divide((high, lhs.high, lhs.low), by: rhs)\n return (Magnitude(0, quotient), remainder &>> shift)\n }\n}\n\nextension DoubleWidth : SignedNumeric, SignedInteger\n where Base : SignedInteger {}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Error.swift", "content": "//===--- Error.swift ------------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ComplexModule\nimport RealModule\n\npublic func relativeError(_ tst: Float, _ ref: Double) -> Double {\n let scale = max(ref.magnitude, Double(Float.leastNormalMagnitude))\n let error = (Double(tst) - ref).magnitude\n return error / scale\n}\n\npublic func componentwiseError(_ tst: Complex<Float>, _ ref: Complex<Double>) -> Double {\n return max(relativeError(tst.real, ref.real),\n relativeError(tst.imaginary, ref.imaginary))\n}\n\npublic func relativeError(_ tst: Complex<Float>, _ ref: Complex<Double>) -> Double {\n let scale = max(ref.magnitude, Double(Float.leastNormalMagnitude))\n let dtst = Complex(Double(tst.real), Double(tst.imaginary))\n let error = (dtst - ref).magnitude\n return error / scale\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Interval.swift", "content": "//===--- Interval.swift ---------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// A not-particularly-clever floating-point iterval that is iterable for the\n// purposes of testing.\npublic struct Interval<Element>: Sequence where Element: FloatingPoint {\n \n let lower: Element\n \n let upper: Element\n \n public init(from: Element, through: Element) {\n precondition(from <= through)\n lower = from\n upper = through\n }\n \n public init(from: Element, to: Element) {\n self.init(from: from, through: to.nextDown)\n }\n \n public func makeIterator() -> Iterator {\n Iterator(self)\n }\n \n public struct Iterator: IteratorProtocol {\n let interval: Interval\n var nextOutput: Element?\n \n init(_ interval: Interval) {\n self.interval = interval\n self.nextOutput = interval.lower\n }\n \n public mutating func next() -> Element? {\n let result = nextOutput\n if nextOutput == interval.upper { nextOutput = nil }\n else { nextOutput = nextOutput?.nextUp }\n return result\n }\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "BlackHole.swift", "content": "//===--- BlackHole.swift --------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nimport _NumericsShims\n\n@_transparent\npublic func blackHole<T>(_ thing: T) {\n withUnsafePointer(to: thing) {\n _numerics_optimization_barrier($0)\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "AugmentedArithmetic.swift", "content": "//===--- AugmentedArithmetic.swift ----------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2020-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\npublic enum Augmented { }\n\nextension Augmented {\n /// The product `a * b` represented as an implicit sum `head + tail`.\n ///\n /// `head` is the correctly rounded value of `a*b`. If no overflow or\n /// underflow occurs, `tail` represents the rounding error incurred in\n /// computing `head`, such that the exact product is the sum of `head`\n /// and `tail` computed without rounding.\n ///\n /// This operation is sometimes called \"twoProd\" or \"twoProduct\".\n ///\n /// Edge Cases:\n ///\n /// - `head` is always the IEEE 754 product `a * b`.\n /// - If `head` is not finite, `tail` is unspecified and should not be\n /// interpreted as having any meaning (it may be `NaN` or `infinity`).\n /// - When `head` is close to the underflow boundary, the rounding error\n /// may not be representable due to underflow, and `tail` will be rounded.\n /// If `head` is very small, `tail` may even be zero, even though the\n /// product is not exact.\n /// - If `head` is zero, `tail` is also a zero with unspecified sign.\n ///\n /// Postconditions:\n ///\n /// - If `head` is normal, then `abs(tail) < head.ulp`.\n /// Assuming IEEE 754 default rounding, `abs(tail) <= head.ulp/2`.\n /// - If both `head` and `tail` are normal, then `a * b` is exactly\n /// equal to `head + tail` when computed as real numbers.\n @_transparent\n public static func product<T:FloatingPoint>(\n _ a: T, _ b: T\n ) -> (head: T, tail: T) {\n let head = a*b\n // TODO: consider providing an FMA-less implementation for use when\n // targeting platforms without hardware FMA support. This works everywhere,\n // falling back on the C math.h fma funcions, but may be slow on older x86.\n let tail = (-head).addingProduct(a, b)\n return (head, tail)\n }\n \n /// The sum `a + b` represented as an implicit sum `head + tail`.\n ///\n /// - Parameters:\n /// - a: The summand with larger magnitude.\n /// - b: The summand with smaller magnitude.\n ///\n /// `head` is the correctly rounded value of `a + b`. `tail` is the\n /// error from that computation rounded to the closest representable\n /// value.\n ///\n /// > Note:\n /// > `tail` is guaranteed to be the best approximation to the error of\n /// the sum only if `large.magnitude` >= `small.magnitude`. If this is\n /// not the case, then `head` is the correctly rounded sum, but `tail`\n /// is not guaranteed to be the exact error. If you do not know a priori\n /// how the magnitudes of `a` and `b` compare, you likely want to use\n /// ``sum(_:_:)`` instead.\n ///\n /// Unlike ``product(_:_:)``, the rounding error of `sum` never underflows.\n ///\n /// This operation is sometimes called [\"fastTwoSum\"].\n ///\n /// > Note:\n /// > Classical fastTwoSum does not work when `radix` is 10. This function\n /// will fall back on another algorithm for decimal floating-point types\n /// to ensure correct results.\n ///\n /// Edge Cases:\n ///\n /// - `head` is always the IEEE 754 sum `a + b`.\n /// - If `head` is not finite, `tail` is unspecified and should not be\n /// interpreted as having any meaning (it may be `NaN` or `infinity`).\n ///\n /// Postconditions:\n ///\n /// - If `head` is normal, then `abs(tail) < head.ulp`.\n /// Assuming IEEE 754 default rounding, `abs(tail) <= head.ulp/2`.\n ///\n /// [\"fastTwoSum\"]: https://en.wikipedia.org/wiki/2Sum\n @_transparent\n public static func sum<T: FloatingPoint>(\n large a: T, small b: T\n ) -> (head: T, tail: T) {\n // Fall back on 2Sum if radix != 2. Future implementations might use an\n // cheaper algorithm specialized for decimal FP, but must deliver a\n // correct result if the preconditions are satisfied.\n guard T.radix == 2 else { return sum(a, b) }\n // Fast2Sum:\n let head = a + b\n let tail = a - head + b\n return (head, tail)\n }\n \n /// The sum `a + b` represented as an implicit sum `head + tail`.\n ///\n /// `head` is the correctly rounded value of `a + b`. `tail` is the\n /// error from that computation rounded to the closest representable\n /// value.\n ///\n /// The magnitude of the summands does not change the result of this\n /// operation. If you know statically that `a.magnitude >= b.magnitude`,\n /// you may want to consider using ``sum(large:small:)`` to get the same\n /// result somewhat more efficiently. If you do not have such a static\n /// bound, you usually want to use this function instead.\n ///\n /// Unlike ``product(_:_:)``, the rounding error of `sum` never underflows.\n ///\n /// This operation is sometimes called [\"twoSum\"].\n ///\n /// - Parameters:\n /// - a: One of the summands\n /// - b: The other summand\n ///\n /// Edge Cases:\n ///\n /// - `head` is always the IEEE 754 sum `a + b`.\n /// - If `head` is not finite, `tail` is unspecified and should not be\n /// interpreted as having any meaning (it may be `NaN` or `infinity`).\n ///\n /// Postconditions:\n ///\n /// - If `head` is normal, then `abs(tail) < head.ulp`.\n /// Assuming IEEE 754 default rounding, `abs(tail) <= head.ulp/2`.\n ///\n /// [\"twoSum\"]: https://en.wikipedia.org/wiki/2Sum\n @_transparent\n public static func sum<T: FloatingPoint>(\n _ a: T, _ b: T\n ) -> (head: T, tail: T) {\n let head = a + b\n let x = head - b\n let y = head - x\n let tail = (a - x) + (b - y)\n return (head, tail)\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "AlgebraicField.swift", "content": "//===--- AlgebraicField.swift ---------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// A type modeling an algebraic [field]. Refines the `SignedNumeric` protocol,\n/// adding division.\n///\n/// A field is a set on which addition, subtraction, multiplication, and\n/// division are defined, and behave basically like those operations on\n/// the real numbers. More precisely, a field is a commutative group under\n/// its addition, the non-zero elements of the field form a commutative\n/// group under its multiplication, and the distributive law holds.\n///\n/// Some common examples of fields include:\n///\n/// - the rational numbers\n/// - the real numbers\n/// - the complex numbers\n/// - the integers modulo a prime\n///\n/// The most familiar example of a thing that is *not* a field is the integers.\n/// This may be surprising, since integers seem to have addition, subtraction,\n/// multiplication and division. Why don't they form a field?\n///\n/// Because integer multiplication does not form a group; it's commutative and\n/// associative, but integers do not have multiplicative inverses.\n/// I.e. if a is any integer other than 1 or -1, there is no integer b such\n/// that `a*b = 1`. The existence of inverses is requried to form a field.\n///\n/// If a type `T` conforms to the ``Real`` protocol, then `T` and `Complex<T>`\n/// both conform to `AlgebraicField`.\n///\n/// See also Swift's `SignedNumeric`, `Numeric` and `AdditiveArithmetic`\n/// protocols.\n///\n/// [field]: https://en.wikipedia.org/wiki/Field_(mathematics)\npublic protocol AlgebraicField: SignedNumeric where Magnitude: AlgebraicField {\n \n /// Replaces a with the (approximate) quotient `a/b`.\n static func /=(a: inout Self, b: Self)\n \n /// The (approximate) quotient `a/b`.\n static func /(a: Self, b: Self) -> Self\n \n /// The (approximate) reciprocal (multiplicative inverse) of this number,\n /// if it is representable.\n ///\n /// If reciprocal is non-nil, you can replace division by self with\n /// multiplication by reciprocal and either get exact the same result\n /// (for finite fields) or approximately the same result up to a typical\n /// rounding error (for floating-point formats).\n ///\n /// If self is zero and the type has no representation for infinity (as\n /// in a typical finite field implementation), or if a reciprocal would\n /// overflow or underflow such that it cannot be accurately represented,\n /// the result is nil.\n ///\n /// Note that `.zero.reciprocal`, somewhat surprisingly, is *not* nil\n /// for `Real` or `Complex` types, because these types have an\n /// `.infinity` value that acts as the reciprocal of `.zero`.\n ///\n /// If `b.reciprocal` is non-nil, you may be able to replace division by `b`\n /// with multiplication by this value. It is not advantageous to do this\n /// for an isolated division unless it is a compile-time constant visible\n /// to the compiler, but if you are dividing many values by a single\n /// denominator, this will often be a significant performance win.\n ///\n /// Note that this will slightly perturb results for fields with approximate\n /// arithmetic, such as real or complex types--using a normal division\n /// is generally more accurate--but no catastrophic loss of accuracy will\n /// result. For fields with exact arithmetic, the results are necessarily\n /// identical.\n ///\n /// A typical use case looks something like this:\n /// ```\n /// func divide<T: AlgebraicField>(data: [T], by divisor: T) -> [T] {\n /// // If divisor is well-scaled, multiply by reciprocal.\n /// if let recip = divisor.reciprocal {\n /// return data.map { $0 * recip }\n /// }\n /// // Fallback on using division.\n /// return data.map { $0 / divisor }\n /// }\n /// ```\n var reciprocal: Self? { get }\n \n /// `a + b`, with the optimizer licensed to reassociate and form FMAs.\n static func _relaxedAdd(_ a: Self, _ b: Self) -> Self\n \n /// `a * b`, with the optimizer licensed to reassociate and form FMAs.\n static func _relaxedMul(_ a: Self, _ b: Self) -> Self\n}\n\nextension AlgebraicField {\n @_transparent\n public static func /(a: Self, b: Self) -> Self {\n var result = a\n result /= b\n return result\n }\n \n // Implementations should be *conservative* with the reciprocal property;\n // it is OK to return `nil` even in cases where a reciprocal could be\n // represented. For this reason, a default implementation that simply\n // always returns `nil` is correct, but conforming types should provide\n // a better implementation if possible.\n @_transparent\n public var reciprocal: Self? {\n return nil\n }\n \n // It's always OK to simply fall back on normal arithmetic, and for any\n // field with exact arithmetic, this is the correct definition.\n @_transparent\n public static func _relaxedAdd(_ a: Self, _ b: Self) -> Self {\n a + b\n }\n \n // It's always OK to simply fall back on normal arithmetic, and for any\n // field with exact arithmetic, this is the correct definition.\n @_transparent\n public static func _relaxedMul(_ a: Self, _ b: Self) -> Self {\n a * b\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Float16+Real.swift", "content": "//===--- Float16+Real.swift -----------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nimport _NumericsShims\nimport Builtin\n\n// Float16 is only available on macOS when targeting arm64.\n#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))\n\n@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)\nextension Float16: Real {\n @_transparent\n public static func cos(_ x: Float16) -> Float16 {\n Float16(.cos(Float(x)))\n }\n \n @_transparent\n public static func sin(_ x: Float16) -> Float16 {\n Float16(.sin(Float(x)))\n }\n \n @_transparent\n public static func tan(_ x: Float16) -> Float16 {\n Float16(.tan(Float(x)))\n }\n \n @_transparent\n public static func acos(_ x: Float16) -> Float16 {\n Float16(.acos(Float(x)))\n }\n \n @_transparent\n public static func asin(_ x: Float16) -> Float16 {\n Float16(.asin(Float(x)))\n }\n \n @_transparent\n public static func atan(_ x: Float16) -> Float16 {\n Float16(.atan(Float(x)))\n }\n \n @_transparent\n public static func cosh(_ x: Float16) -> Float16 {\n Float16(.cosh(Float(x)))\n }\n \n @_transparent\n public static func sinh(_ x: Float16) -> Float16 {\n Float16(.sinh(Float(x)))\n }\n \n @_transparent\n public static func tanh(_ x: Float16) -> Float16 {\n Float16(.tanh(Float(x)))\n }\n \n @_transparent\n public static func acosh(_ x: Float16) -> Float16 {\n Float16(.acosh(Float(x)))\n }\n \n @_transparent\n public static func asinh(_ x: Float16) -> Float16 {\n Float16(.asinh(Float(x)))\n }\n \n @_transparent\n public static func atanh(_ x: Float16) -> Float16 {\n Float16(.atanh(Float(x)))\n }\n \n @_transparent\n public static func exp(_ x: Float16) -> Float16 {\n Float16(.exp(Float(x)))\n }\n \n @_transparent\n public static func expMinusOne(_ x: Float16) -> Float16 {\n Float16(.expMinusOne(Float(x)))\n }\n \n @_transparent\n public static func log(_ x: Float16) -> Float16 {\n Float16(.log(Float(x)))\n }\n \n @_transparent\n public static func log(onePlus x: Float16) -> Float16 {\n Float16(.log(onePlus: Float(x)))\n }\n \n @_transparent\n public static func erf(_ x: Float16) -> Float16 {\n Float16(.erf(Float(x)))\n }\n \n @_transparent\n public static func erfc(_ x: Float16) -> Float16 {\n Float16(.erfc(Float(x)))\n }\n \n @_transparent\n public static func exp2(_ x: Float16) -> Float16 {\n Float16(.exp2(Float(x)))\n }\n \n @_transparent\n public static func exp10(_ x: Float16) -> Float16 {\n Float16(.exp10(Float(x)))\n }\n \n @_transparent\n public static func hypot(_ x: Float16, _ y: Float16) -> Float16 {\n if x.isInfinite || y.isInfinite { return .infinity }\n let xf = Float(x)\n let yf = Float(y)\n return Float16(.sqrt(xf*xf + yf*yf))\n }\n \n @_transparent\n public static func gamma(_ x: Float16) -> Float16 {\n Float16(.gamma(Float(x)))\n }\n \n @_transparent\n public static func log2(_ x: Float16) -> Float16 {\n Float16(.log2(Float(x)))\n }\n \n @_transparent\n public static func log10(_ x: Float16) -> Float16 {\n Float16(.log10(Float(x)))\n }\n \n @_transparent\n public static func pow(_ x: Float16, _ y: Float16) -> Float16 {\n Float16(.pow(Float(x), Float(y)))\n }\n \n @_transparent\n public static func pow(_ x: Float16, _ n: Int) -> Float16 {\n // Float16 is simpler than Float or Double, because the range of\n // \"interesting\" exponents is pretty small; anything outside of\n // -22707 ... 34061 simply overflows or underflows for every\n // x that isn't zero or one. This whole range is representable\n // as Float, so we can just use powf as long as we're a little\n // bit (get it?) careful to preserve parity.\n let clamped = min(max(n, -0x10000), 0x10000) | (n & 1)\n return Float16(libm_powf(Float(x), Float(clamped)))\n }\n \n @_transparent\n public static func root(_ x: Float16, _ n: Int) -> Float16 {\n Float16(.root(Float(x), n))\n }\n \n @_transparent\n public static func atan2(y: Float16, x: Float16) -> Float16 {\n Float16(.atan2(y: Float(y), x: Float(x)))\n }\n \n #if !os(Windows)\n @_transparent\n public static func logGamma(_ x: Float16) -> Float16 {\n Float16(.logGamma(Float(x)))\n }\n #endif\n \n #if !arch(wasm32) || hasFeature(BuiltinRelaxedFP)\n // WASM doesn't have _Float16 on the C side, so we can't define the C hooks\n // that these use. However, if we have BuiltinRelaxedFP we can use builtins\n // to do this directly without needing the C hooks.\n \n @_transparent\n public static func _relaxedAdd(_ a: Float16, _ b: Float16) -> Float16 {\n #if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later\n Float16(Builtin.fadd_relaxed_FPIEEE16(a._value, b._value))\n #else\n _numerics_relaxed_addf16(a, b)\n #endif\n }\n \n @_transparent\n public static func _relaxedMul(_ a: Float16, _ b: Float16) -> Float16 {\n #if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later\n Float16(Builtin.fmul_relaxed_FPIEEE16(a._value, b._value))\n #else\n _numerics_relaxed_mulf16(a, b)\n #endif\n }\n #endif\n}\n\n#endif"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "ApproximateEquality.swift", "content": "//===--- ApproximateEquality.swift ----------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2020-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nextension Numeric where Magnitude: FloatingPoint {\n /// Test if `self` and `other` are approximately equal.\n ///\n /// `true` if `self` and `other` are equal, or if they are finite and\n /// ```\n /// norm(self - other) <= relativeTolerance * scale\n /// ```\n /// where `scale` is\n /// ```\n /// max(norm(self), norm(other), .leastNormalMagnitude)\n /// ```\n ///\n /// The default value of `relativeTolerance` is `.ulpOfOne.squareRoot()`,\n /// which corresponds to expecting \"about half the digits\" in the computed\n /// results to be good. This is the usual guidance in numerical analysis,\n /// if you don't know anything about the computation being performed, but\n /// is not suitable for all use cases.\n ///\n /// Mathematical Properties:\n ///\n /// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _reflexive_ for\n /// non-exceptional values (such as NaN).\n ///\n /// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _symmetric_.\n ///\n /// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is __not__\n /// _transitive_. Because of this, approximately equality is __not an\n /// equivalence relation__, even when restricted to non-exceptional values.\n ///\n /// This means that you must not use approximate equality to implement\n /// a conformance to Equatable, as it will violate the invariants of\n /// code written against that protocol.\n ///\n /// - For any point `a`, the set of values that compare approximately equal\n /// to `a` is _convex_. (Under the assumption that the `.magnitude`\n /// property implements a valid norm.)\n ///\n /// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _scale invariant_,\n /// so long as no underflow or overflow has occurred, and no exceptional\n /// value is produced by the scaling.\n ///\n /// See also `isApproximatelyEqual(to:absoluteTolerance:[relativeTolerance:norm:])`.\n ///\n /// - Parameters:\n ///\n /// - other: The value to which `self` is compared.\n ///\n /// - relativeTolerance: The tolerance to use for the comparison.\n /// Defaults to `.ulpOfOne.squareRoot()`.\n ///\n /// This value should be non-negative and less than or equal to 1.\n /// This constraint on is only checked in debug builds, because a\n /// mathematically well-defined result exists for any tolerance,\n /// even one out of range.\n ///\n /// - norm: The [norm] to use for the comparison.\n /// Defaults to `\\.magnitude`.\n ///\n /// [norm]: https://en.wikipedia.org/wiki/Norm_(mathematics)\n @inlinable @inline(__always)\n public func isApproximatelyEqual(\n to other: Self,\n relativeTolerance: Magnitude = Magnitude.ulpOfOne.squareRoot(),\n norm: (Self) -> Magnitude = \\.magnitude\n ) -> Bool {\n return isApproximatelyEqual(\n to: other,\n absoluteTolerance: relativeTolerance * Magnitude.leastNormalMagnitude,\n relativeTolerance: relativeTolerance,\n norm: norm\n )\n }\n \n /// Test if `self` and `other` are approximately equal with specified tolerances.\n ///\n /// `true` if `self` and `other` are equal, or if they are finite and either\n /// ```\n /// (self - other).magnitude <= absoluteTolerance\n /// ```\n /// or\n /// ```\n /// (self - other).magnitude <= relativeTolerance * scale\n /// ```\n /// where `scale` is `max(self.magnitude, other.magnitude)`.\n ///\n /// Mathematical Properties:\n ///\n /// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:)`\n /// is _reflexive_ for non-exceptional values (such as NaN).\n ///\n /// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:)`\n /// is _symmetric_.\n ///\n /// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is __not__\n /// _transitive_. Because of this, approximately equality is __not an\n /// equivalence relation__, even when restricted to non-exceptional values.\n ///\n /// This means that you must not use approximate equality to implement\n /// a conformance to Equatable, as it will violate the invariants of\n /// code written against that protocol.\n ///\n /// - For any point `a`, the set of values that compare approximately equal\n /// to `a` is _convex_. (Under the assumption that `norm` implements a\n /// valid norm, which cannot be checked by this function.)\n ///\n /// See also `isApproximatelyEqual(to:[relativeTolerance:])`.\n ///\n /// - Parameters:\n ///\n /// - other: The value to which `self` is compared.\n ///\n /// - absoluteTolerance: The absolute tolerance to use in the comparison.\n ///\n /// This value should be non-negative and finite.\n /// This constraint on is only checked in debug builds, because a\n /// mathematically well-defined result exists for any tolerance,\n /// even one out of range.\n ///\n /// - relativeTolerance: The relative tolerance to use in the comparison.\n /// Defaults to zero.\n ///\n /// This value should be non-negative and less than or equal to 1.\n /// This constraint on is only checked in debug builds, because a\n /// mathematically well-defined result exists for any tolerance,\n /// even one out of range.\n @inlinable @inline(__always)\n public func isApproximatelyEqual(\n to other: Self,\n absoluteTolerance: Magnitude,\n relativeTolerance: Magnitude = 0\n ) -> Bool {\n self.isApproximatelyEqual(\n to: other,\n absoluteTolerance: absoluteTolerance,\n relativeTolerance: relativeTolerance,\n norm: \\.magnitude\n )\n }\n}\n\nextension AdditiveArithmetic {\n /// Test if `self` and `other` are approximately equal with specified\n /// tolerances and norm.\n ///\n /// `true` if `self` and `other` are equal, or if they are finite and either\n /// ```\n /// norm(self - other) <= absoluteTolerance\n /// ```\n /// or\n /// ```\n /// norm(self - other) <= relativeTolerance * scale\n /// ```\n /// where `scale` is `max(norm(self), norm(other))`.\n ///\n /// Mathematical Properties:\n ///\n /// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:norm:)`\n /// is _reflexive_ for non-exceptional values (such as NaN).\n ///\n /// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:norm:)`\n /// is _symmetric_.\n ///\n /// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:norm:)`\n /// is __not__ _transitive_. Because of this, approximately equality is\n /// __not an equivalence relation__, even when restricted to\n /// non-exceptional values.\n ///\n /// This means that you must not use approximate equality to implement\n /// a conformance to Equatable, as it will violate the invariants of\n /// code written against that protocol.\n ///\n /// - For any point `a`, the set of values that compare approximately equal\n /// to `a` is _convex_ (under the assumption that `norm` implements a\n /// valid norm, which cannot be checked by this function or a protocol).\n ///\n /// See also `isApproximatelyEqual(to:[relativeTolerance:norm:])` and\n /// `isApproximatelyEqual(to:absoluteTolerance:[relativeTolerance:])`.\n ///\n /// - Parameters:\n ///\n /// - other: The value to which `self` is compared.\n ///\n /// - absoluteTolerance: The absolute tolerance to use in the comparison.\n ///\n /// This value should be non-negative and finite.\n /// This constraint on is only checked in debug builds, because a\n /// mathematically well-defined result exists for any tolerance, even\n /// one out of range.\n ///\n /// - relativeTolerance: The relative tolerance to use in the comparison.\n /// Defaults to zero.\n ///\n /// This value should be non-negative and less than or equal to 1.\n /// This constraint on is only checked in debug builds, because a\n /// mathematically well-defined result exists for any tolerance,\n /// even one out of range.\n ///\n /// - norm: The norm to use for the comparison.\n /// Defaults to `\\.magnitude`.\n ///\n /// For example, if we wanted to test if a complex value was inside a\n /// circle of radius 0.001 centered at (1 + 0i), we could use:\n /// ```\n /// z.isApproximatelyEqual(\n /// to: 1,\n /// absoluteTolerance: 0.001,\n /// norm: \\.length\n /// )\n /// ```\n /// (if we used the default norm, `\\.magnitude`, we would be testing if\n /// `z` were inside a square region instead.)\n @inlinable\n public func isApproximatelyEqual<Magnitude>(\n to other: Self,\n absoluteTolerance: Magnitude,\n relativeTolerance: Magnitude = 0,\n norm: (Self) -> Magnitude\n ) -> Bool\n where Magnitude: FloatingPoint {\n assert(\n absoluteTolerance >= 0 && absoluteTolerance.isFinite,\n \"absoluteTolerance should be non-negative and finite, \" +\n \"but is \\(absoluteTolerance).\"\n )\n assert(\n relativeTolerance >= 0 && relativeTolerance <= 1,\n \"relativeTolerance should be non-negative and <= 1, \" +\n \"but is \\(relativeTolerance).\"\n )\n if self == other { return true }\n let delta = norm(self - other)\n let scale = max(norm(self), norm(other))\n let bound = max(absoluteTolerance, scale*relativeTolerance)\n return delta.isFinite && delta <= bound\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Real.swift", "content": "//===--- Real.swift -------------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// A type that models the real numbers.\n///\n/// Types conforming to this protocol provide the arithmetic and utility\n/// operations defined by the `FloatingPoint` protocol, and provide all of the\n/// math functions defined by the `ElementaryFunctions` and `RealFunctions`\n/// protocols. This protocol does not add any additional conformances itself,\n/// but is very useful as a protocol against which to write generic code. For\n/// example, we can naturally write a generic implementation of a sigmoid\n/// function:\n/// ```\n/// func sigmoid<T: Real>(_ x: T) -> T {\n/// return 1/(1 + .exp(-x))\n/// }\n/// ```\n/// See also `ElementaryFunctions`, `RealFunctions` and `AlgebraicField`.\npublic protocol Real: FloatingPoint, RealFunctions, AlgebraicField { }\n\n// While `Real` does not provide any additional customization points,\n// it does allow us to default the implementation of a few operations,\n// and also provides `signGamma`.\nextension Real {\n // Most math libraries do not provide exp10, so we need a default\n // implementation. This is not a great one (if the underlying math\n // library does not have a sub-ulp accurate pow, this will not get\n // exact powers of ten right), but suffices in the short term.\n @_transparent\n public static func exp10(_ x: Self) -> Self {\n pow(10, x)\n }\n \n /// cos(x) - 1, computed in such a way as to maintain accuracy for small x.\n ///\n /// See also ``ElementaryFunctions/expMinusOne(_:)``.\n @_transparent\n public static func cosMinusOne(_ x: Self) -> Self {\n let sinxOver2 = sin(x/2)\n return -2*sinxOver2*sinxOver2\n }\n \n #if !os(Windows)\n public static func signGamma(_ x: Self) -> FloatingPointSign {\n // Gamma is strictly positive for x >= 0.\n if x >= 0 { return .plus }\n // For negative x, we arbitrarily choose to assign a sign of .plus to the\n // poles.\n let trunc = x.rounded(.towardZero)\n if x == trunc { return .plus }\n // Otherwise, signGamma is .minus if the integral part of x is even.\n return trunc.isEven ? .minus : .plus\n }\n \n // Determines if this value is even, assuming that it is an integer.\n @inline(__always)\n private var isEven: Bool {\n if Self.radix == 2 {\n // For binary types, we can just check if x/2 is an integer. This works\n // because x/2 is always computed exactly.\n let half = self/2\n return half == half.rounded(.towardZero)\n } else {\n // For decimal types, it's not quite that simple, because x/2 is not\n // necessarily computed exactly. As an example, suppose that we had a\n // decimal type with a one digit significand, and self = 7. Then self/2\n // would round to 4, and we would (wrongly) conclude that it was an\n // integer, and hence that self was even.\n //\n // Instead, for decimal types, we check if 2*trunc(self/2) == self,\n // using an FMA; this is always correct; this approach works for any\n // radix, but the previous method is more efficient for radix == 2.\n let half = self/2\n return self.addingProduct(-2, half.rounded(.towardZero)) == 0\n }\n }\n #endif\n \n @_transparent\n public static func _mulAdd(_ a: Self, _ b: Self, _ c: Self) -> Self {\n a*b + c\n }\n \n @_transparent\n public static func sqrt(_ x: Self) -> Self {\n x.squareRoot()\n }\n \n /// The (approximate) reciprocal (multiplicative inverse) of this number,\n /// if it is representable.\n ///\n /// If `a` if finite and nonzero, and `1/a` overflows or underflows,\n /// then `a.reciprocal` is `nil`. Otherwise, `a.reciprocal` is `1/a`.\n ///\n /// If `b.reciprocal` is non-nil, you may be able to replace division by `b`\n /// with multiplication by this value. It is not advantageous to do this\n /// for an isolated division unless it is a compile-time constant visible\n /// to the compiler, but if you are dividing many values by a single\n /// denominator, this will often be a significant performance win.\n ///\n /// A typical use case looks something like this:\n /// ```\n /// func divide<T: Real>(data: [T], by divisor: T) -> [T] {\n /// // If divisor is well-scaled, multiply by reciprocal.\n /// if let recip = divisor.reciprocal {\n /// return data.map { $0 * recip }\n /// }\n /// // Fallback on using division.\n /// return data.map { $0 / divisor }\n /// }\n /// ```\n ///\n /// Error Bounds:\n ///\n /// Multiplying by the reciprocal instead of dividing will slightly\n /// perturb results. For example `5.0 / 3` is 1.6666666666666667, but\n /// `5.0 * 3.reciprocal!` is 1.6666666666666665.\n ///\n /// The error of a normal division is bounded by half an ulp of the\n /// result; we can derive a quick error bound for multiplication by\n /// the real reciprocal (when it exists) as follows (I will use circle\n /// operators to denote real-number arithmetic, and normal operators\n /// for floating-point arithmetic):\n /// ```\n /// a * b.reciprocal! = a * (1/b)\n /// = a * (1 \u2298 b)(1 + \u03b4\u2081)\n /// = (a \u2298 b)(1 + \u03b4\u2081)(1 + \u03b4\u2082)\n /// = (a \u2298 b)(1 + \u03b4\u2081 + \u03b4\u2082 + \u03b4\u2081\u03b4\u2082)\n /// ```\n /// where `0 < \u03b4\u1d62 <= ulpOfOne/2`. This gives a roughly 1-ulp error,\n /// about twice the error bound we get using division. For most\n /// purposes this is an acceptable error, but if you need to match\n /// results obtained using division, you should not use this.\n @inlinable\n public var reciprocal: Self? {\n let recip = 1/self\n if recip.isNormal || isZero || !isFinite {\n return recip\n }\n return nil\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Double+Real.swift", "content": "//===--- Double+Real.swift ------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nimport _NumericsShims\nimport Builtin\n\nextension Double: Real {\n @_transparent\n public static func cos(_ x: Double) -> Double {\n libm_cos(x)\n }\n \n @_transparent\n public static func sin(_ x: Double) -> Double {\n libm_sin(x)\n }\n \n @_transparent\n public static func tan(_ x: Double) -> Double {\n libm_tan(x)\n }\n \n @_transparent\n public static func acos(_ x: Double) -> Double {\n libm_acos(x)\n }\n \n @_transparent\n public static func asin(_ x: Double) -> Double {\n libm_asin(x)\n }\n \n @_transparent\n public static func atan(_ x: Double) -> Double {\n libm_atan(x)\n }\n \n @_transparent\n public static func cosh(_ x: Double) -> Double {\n libm_cosh(x)\n }\n \n @_transparent\n public static func sinh(_ x: Double) -> Double {\n libm_sinh(x)\n }\n \n @_transparent\n public static func tanh(_ x: Double) -> Double {\n libm_tanh(x)\n }\n \n @_transparent\n public static func acosh(_ x: Double) -> Double {\n libm_acosh(x)\n }\n \n @_transparent\n public static func asinh(_ x: Double) -> Double {\n libm_asinh(x)\n }\n \n @_transparent\n public static func atanh(_ x: Double) -> Double {\n libm_atanh(x)\n }\n \n @_transparent\n public static func exp(_ x: Double) -> Double {\n libm_exp(x)\n }\n \n @_transparent\n public static func expMinusOne(_ x: Double) -> Double {\n libm_expm1(x)\n }\n \n @_transparent\n public static func log(_ x: Double) -> Double {\n libm_log(x)\n }\n \n @_transparent\n public static func log(onePlus x: Double) -> Double {\n libm_log1p(x)\n }\n \n @_transparent\n public static func erf(_ x: Double) -> Double {\n libm_erf(x)\n }\n \n @_transparent\n public static func erfc(_ x: Double) -> Double {\n libm_erfc(x)\n }\n \n @_transparent\n public static func exp2(_ x: Double) -> Double {\n libm_exp2(x)\n }\n \n#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)\n @_transparent\n public static func exp10(_ x: Double) -> Double {\n libm_exp10(x)\n }\n#endif\n \n#if os(macOS) && arch(x86_64)\n // Workaround for macOS bug (<rdar://problem/56844150>) where hypot can\n // overflow for values very close to the overflow boundary of the naive\n // algorithm. Since this is only for macOS, we can just unconditionally\n // use Float80, which makes the implementation trivial.\n public static func hypot(_ x: Double, _ y: Double) -> Double {\n if x.isInfinite || y.isInfinite { return .infinity }\n let x80 = Float80(x)\n let y80 = Float80(y)\n return Double(Float80.sqrt(x80*x80 + y80*y80))\n }\n#else\n @_transparent\n public static func hypot(_ x: Double, _ y: Double) -> Double {\n libm_hypot(x, y)\n }\n#endif\n \n @_transparent\n public static func gamma(_ x: Double) -> Double {\n libm_tgamma(x)\n }\n \n @_transparent\n public static func log2(_ x: Double) -> Double {\n libm_log2(x)\n }\n \n @_transparent\n public static func log10(_ x: Double) -> Double {\n libm_log10(x)\n }\n \n @_transparent\n public static func pow(_ x: Double, _ y: Double) -> Double {\n guard x >= 0 else { return .nan }\n if x == 0 && y == 0 { return .nan }\n return libm_pow(x, y)\n }\n \n @_transparent\n public static func pow(_ x: Double, _ n: Int) -> Double {\n // If n is exactly representable as Double, we can just call pow:\n // Note that all calls on a 32b platform go down this path.\n if let y = Double(exactly: n) { return libm_pow(x, y) }\n // n is not representable in Double, so we will split it into two parts,\n // low and high, such that (high + low) = n, and use the identity:\n //\n // x**(high + low) = x**high * x**low.\n //\n // We put the high-order 32 bits into high, and the remaining 32 bits\n // in low.\n //\n // The exact split isn't important; all we need is that both pieces get\n // less than 53 bits (so that they are exact) and that they both have\n // the same sign as n.\n //\n // This second point is a little bit subtle--why is\n // it necessary? Consider what would happen if we took x = 2 and\n // n = Int.min + Int(UInt32.max), and simply naively split n without\n // taking care with the sign. We would end up computing:\n //\n // 2**n = 2**Int.min * 2**UInt32.max\n //\n // The first exponent is negative, the second positive, so the first term\n // underflows to zero, and the second overflows to infinity, so the final\n // result is NaN, when it should be zero. In order to avoid this\n // situation, we make sure that high contains n rounded *towards zero*,\n // rather than using simple two's-complement truncation (which rounds\n // down).\n let mask = Int(truncatingIfNeeded: UInt32.max)\n let round = n < 0 ? mask : 0\n // The addition and subtraction below cannot actually overflow (proof:\n // round is positive if n is negative, and zero otherwise, so n + round\n // is guaranteed to be representable, and n and high have the same sign,\n // so n - high is also representable), but it's hard to tell the compiler\n // that, so I'm using wrapping operations instead.\n let high = (n &+ round) & ~mask\n let low = n &- high\n return libm_pow(x, Double(low)) * libm_pow(x, Double(high))\n }\n \n @_transparent\n public static func root(_ x: Double, _ n: Int) -> Double {\n guard x >= 0 || n % 2 != 0 else { return .nan }\n // Workaround the issue mentioned below for the specific case of n = 3\n // where we can fallback on cbrt.\n if n == 3 { return libm_cbrt(x) }\n // TODO: this implementation is not quite correct, because either n or\n // 1/n may be not be representable as Double.\n return Double(signOf: x, magnitudeOf: libm_pow(x.magnitude, 1/Double(n)))\n }\n \n @_transparent\n public static func atan2(y: Double, x: Double) -> Double {\n libm_atan2(y, x)\n }\n \n#if !os(Windows)\n @_transparent\n public static func logGamma(_ x: Double) -> Double {\n var dontCare: Int32 = 0\n return libm_lgamma(x, &dontCare)\n }\n#endif\n \n @_transparent\n public static func _relaxedAdd(_ a: Double, _ b: Double) -> Double {\n#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later\n Double(Builtin.fadd_relaxed_FPIEEE64(a._value, b._value))\n#else\n _numerics_relaxed_add(a, b)\n#endif\n }\n \n @_transparent\n public static func _relaxedMul(_ a: Double, _ b: Double) -> Double {\n#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later\n Double(Builtin.fmul_relaxed_FPIEEE64(a._value, b._value))\n#else\n _numerics_relaxed_mul(a, b)\n#endif\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Float80+Real.swift", "content": "//===--- Float80+Real.swift -----------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nimport _NumericsShims\nimport Builtin\n\n// Restrict extension to platforms for which Float80 exists.\n#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)\nextension Float80: Real {\n @_transparent\n public static func cos(_ x: Float80) -> Float80 {\n libm_cosl(x)\n }\n \n @_transparent\n public static func sin(_ x: Float80) -> Float80 {\n libm_sinl(x)\n }\n \n @_transparent\n public static func tan(_ x: Float80) -> Float80 {\n libm_tanl(x)\n }\n \n @_transparent\n public static func acos(_ x: Float80) -> Float80 {\n libm_acosl(x)\n }\n \n @_transparent\n public static func asin(_ x: Float80) -> Float80 {\n libm_asinl(x)\n }\n \n @_transparent\n public static func atan(_ x: Float80) -> Float80 {\n libm_atanl(x)\n }\n \n @_transparent\n public static func cosh(_ x: Float80) -> Float80 {\n libm_coshl(x)\n }\n \n @_transparent\n public static func sinh(_ x: Float80) -> Float80 {\n libm_sinhl(x)\n }\n \n @_transparent\n public static func tanh(_ x: Float80) -> Float80 {\n libm_tanhl(x)\n }\n \n @_transparent\n public static func acosh(_ x: Float80) -> Float80 {\n libm_acoshl(x)\n }\n \n @_transparent\n public static func asinh(_ x: Float80) -> Float80 {\n libm_asinhl(x)\n }\n \n @_transparent\n public static func atanh(_ x: Float80) -> Float80 {\n libm_atanhl(x)\n }\n \n @_transparent\n public static func exp(_ x: Float80) -> Float80 {\n libm_expl(x)\n }\n \n @_transparent\n public static func expMinusOne(_ x: Float80) -> Float80 {\n libm_expm1l(x)\n }\n \n @_transparent\n public static func log(_ x: Float80) -> Float80 {\n libm_logl(x)\n }\n \n @_transparent\n public static func log(onePlus x: Float80) -> Float80 {\n libm_log1pl(x)\n }\n \n @_transparent\n public static func erf(_ x: Float80) -> Float80 {\n libm_erfl(x)\n }\n \n @_transparent\n public static func erfc(_ x: Float80) -> Float80 {\n libm_erfcl(x)\n }\n \n @_transparent\n public static func exp2(_ x: Float80) -> Float80 {\n libm_exp2l(x)\n }\n \n @_transparent\n public static func hypot(_ x: Float80, _ y: Float80) -> Float80 {\n libm_hypotl(x, y)\n }\n \n @_transparent\n public static func gamma(_ x: Float80) -> Float80 {\n libm_tgammal(x)\n }\n \n @_transparent\n public static func log2(_ x: Float80) -> Float80 {\n libm_log2l(x)\n }\n \n @_transparent\n public static func log10(_ x: Float80) -> Float80 {\n libm_log10l(x)\n }\n \n @_transparent\n public static func pow(_ x: Float80, _ y: Float80) -> Float80 {\n guard x >= 0 else { return .nan }\n if x == 0 && y == 0 { return .nan }\n return libm_powl(x, y)\n }\n \n @_transparent\n public static func pow(_ x: Float80, _ n: Int) -> Float80 {\n // Every Int value is exactly representable as Float80, so we don't need\n // to do anything fancy--unlike Float and Double, we can just call the\n // libm pow function.\n libm_powl(x, Float80(n))\n }\n \n @_transparent\n public static func root(_ x: Float80, _ n: Int) -> Float80 {\n guard x >= 0 || n % 2 != 0 else { return .nan }\n // Workaround the issue mentioned below for the specific case of n = 3\n // where we can fallback on cbrt.\n if n == 3 { return libm_cbrtl(x) }\n // TODO: this implementation is not quite correct, because either n or\n // 1/n may be not be representable as Float80.\n return Float80(signOf: x, magnitudeOf: libm_powl(x.magnitude, 1/Float80(n)))\n }\n \n @_transparent\n public static func atan2(y: Float80, x: Float80) -> Float80 {\n libm_atan2l(y, x)\n }\n \n @_transparent\n public static func logGamma(_ x: Float80) -> Float80 {\n var dontCare: Int32 = 0\n return libm_lgammal(x, &dontCare)\n }\n \n @_transparent\n public static func _relaxedAdd(_ a: Float80, _ b: Float80) -> Float80 {\n#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later\n Float80(Builtin.fadd_relaxed_FPIEEE80(a._value, b._value))\n#else\n _numerics_relaxed_addl(a, b)\n#endif\n }\n \n @_transparent\n public static func _relaxedMul(_ a: Float80, _ b: Float80) -> Float80 {\n#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later\n Float80(Builtin.fmul_relaxed_FPIEEE80(a._value, b._value))\n#else\n _numerics_relaxed_mull(a, b)\n#endif\n }\n}\n#endif"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Float+Real.swift", "content": "//===--- Float+Real.swift -------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nimport _NumericsShims\nimport Builtin\n\nextension Float: Real {\n @_transparent\n public static func cos(_ x: Float) -> Float {\n libm_cosf(x)\n }\n \n @_transparent\n public static func sin(_ x: Float) -> Float {\n libm_sinf(x)\n }\n \n @_transparent\n public static func tan(_ x: Float) -> Float {\n libm_tanf(x)\n }\n \n @_transparent\n public static func acos(_ x: Float) -> Float {\n libm_acosf(x)\n }\n \n @_transparent\n public static func asin(_ x: Float) -> Float {\n libm_asinf(x)\n }\n \n @_transparent\n public static func atan(_ x: Float) -> Float {\n libm_atanf(x)\n }\n \n @_transparent\n public static func cosh(_ x: Float) -> Float {\n libm_coshf(x)\n }\n \n @_transparent\n public static func sinh(_ x: Float) -> Float {\n libm_sinhf(x)\n }\n \n @_transparent\n public static func tanh(_ x: Float) -> Float {\n libm_tanhf(x)\n }\n \n @_transparent\n public static func acosh(_ x: Float) -> Float {\n libm_acoshf(x)\n }\n \n @_transparent\n public static func asinh(_ x: Float) -> Float {\n libm_asinhf(x)\n }\n \n @_transparent\n public static func atanh(_ x: Float) -> Float {\n libm_atanhf(x)\n }\n \n @_transparent\n public static func exp(_ x: Float) -> Float {\n libm_expf(x)\n }\n \n @_transparent\n public static func expMinusOne(_ x: Float) -> Float {\n libm_expm1f(x)\n }\n \n @_transparent\n public static func log(_ x: Float) -> Float {\n libm_logf(x)\n }\n \n @_transparent\n public static func log(onePlus x: Float) -> Float {\n libm_log1pf(x)\n }\n \n @_transparent\n public static func erf(_ x: Float) -> Float {\n libm_erff(x)\n }\n \n @_transparent\n public static func erfc(_ x: Float) -> Float {\n libm_erfcf(x)\n }\n \n @_transparent\n public static func exp2(_ x: Float) -> Float {\n libm_exp2f(x)\n }\n \n #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)\n @_transparent\n public static func exp10(_ x: Float) -> Float {\n libm_exp10f(x)\n }\n #endif\n \n @_transparent\n public static func hypot(_ x: Float, _ y: Float) -> Float {\n libm_hypotf(x, y)\n }\n \n @_transparent\n public static func gamma(_ x: Float) -> Float {\n libm_tgammaf(x)\n }\n \n @_transparent\n public static func log2(_ x: Float) -> Float {\n libm_log2f(x)\n }\n \n @_transparent\n public static func log10(_ x: Float) -> Float {\n libm_log10f(x)\n }\n \n @_transparent\n public static func pow(_ x: Float, _ y: Float) -> Float {\n guard x >= 0 else { return .nan }\n if x == 0 && y == 0 { return .nan }\n return libm_powf(x, y)\n }\n \n @_transparent\n public static func pow(_ x: Float, _ n: Int) -> Float {\n // If n is exactly representable as Float, we can just call powf:\n if let y = Float(exactly: n) {\n return libm_powf(x, y)\n }\n // Otherwise, n is too large to losslessly represent as Float.\n // The range of \"interesting\" n is -1488522191 ... 1744361944; outside\n // of this range, all x != 1 overflow or underflow, so only the parity\n // of x matters. We don't really care about the specific range at all,\n // only that the bounds fit exactly into two Floats.\n //\n // We do, however, need to be careful that high and low both have the\n // same sign as n (consult the Double implementation for details of why\n // this matters), so we need to be a little bit careful constructing\n // them.\n //\n // Unlike the Double implementation, when n is very large, high will\n // get rounded here; that's OK because it does not change the sign or\n // parity, which are the only two bits that matter for such large\n // exponents in Float.\n let mask = Int(truncatingIfNeeded: 0xffffff)\n let round = n < 0 ? mask : 0\n let high = (n &+ round) & ~mask\n let low = n &- high\n return libm_powf(x, Float(low)) * libm_powf(x, Float(high))\n }\n \n @_transparent\n public static func root(_ x: Float, _ n: Int) -> Float {\n guard x >= 0 || n % 2 != 0 else { return .nan }\n // Workaround the issue mentioned below for the specific case of n = 3\n // where we can fallback on cbrt.\n if n == 3 { return libm_cbrtf(x) }\n // TODO: this implementation is not quite correct, because either n or\n // 1/n may be not be representable as Float.\n return Float(signOf: x, magnitudeOf: libm_powf(x.magnitude, 1/Float(n)))\n }\n \n @_transparent\n public static func atan2(y: Float, x: Float) -> Float {\n libm_atan2f(y, x)\n }\n \n #if !os(Windows)\n @_transparent\n public static func logGamma(_ x: Float) -> Float {\n var dontCare: Int32 = 0\n return libm_lgammaf(x, &dontCare)\n }\n #endif\n \n @_transparent\n public static func _relaxedAdd(_ a: Float, _ b: Float) -> Float {\n#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later\n Float(Builtin.fadd_relaxed_FPIEEE32(a._value, b._value))\n#else\n _numerics_relaxed_addf(a, b)\n#endif\n }\n \n @_transparent\n public static func _relaxedMul(_ a: Float, _ b: Float) -> Float {\n#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later\n Float(Builtin.fmul_relaxed_FPIEEE32(a._value, b._value))\n#else\n _numerics_relaxed_mulf(a, b)\n#endif\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "RelaxedArithmetic.swift", "content": "//===--- RelaxedArithmetic.swift ------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2021-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nimport _NumericsShims\n\npublic enum Relaxed { }\n\nextension Relaxed {\n /// a+b, but grants the optimizer permission to reassociate expressions\n /// and form FMAs.\n ///\n /// Floating-point addition is not an associative operation, so the Swift\n /// compiler does not have any flexibility in how it evaluates an expression\n /// like:\n /// ```\n /// func sum(array: [Float]) -> Float {\n /// array.reduce(0, +)\n /// }\n /// ```\n /// Using `Relaxed.sum` instead of `+` permits the compiler to reorder the\n /// terms in the summation, which unlocks loop unrolling and vectorization.\n /// In a benchmark, simply using `Relaxed.sum` provides about an 8x speedup\n /// for release builds, without any unsafe flags or other optimizations.\n /// Further improvement should be possible by improving LLVM optimizations\n /// or adding attributes to license more aggressive unrolling and taking\n /// advantage of vector ISA extensions for swift.\n ///\n /// If you want to compute `a-b` with relaxed semantics, use\n /// `Relaxed.sum(a, -b)`.\n ///\n /// If a type or toolchain does not support reassociation for optimization\n /// purposes, this operation decays to a normal addition; it is a license\n /// for the compiler to optimize, not a guarantee that any change occurs.\n @_transparent\n public static func sum<T: AlgebraicField>(_ a: T, _ b: T) -> T {\n T._relaxedAdd(a, b)\n }\n \n /// a*b, but grants the optimizer permission to reassociate expressions\n /// and form FMAs.\n ///\n /// Floating-point addition and multiplication are not associative operations,\n /// so the Swift compiler does not have any flexibility in how it evaluates\n /// an expression like:\n /// ```\n /// func sumOfSquares(array: [Float]) -> Float {\n /// array.reduce(0) { $0 + $1*$1 }\n /// }\n /// ```\n /// Using `Relaxed.sum` and `Relaxed.product` instead of `+` and `*` permits\n /// the compiler to reorder the terms in the summation, which unlocks loop\n /// unrolling and vectorization, and form fused multiply-adds, which allows\n /// us to achieve twice the throughput on some hardware.\n ///\n /// If a type or toolchain does not support reassociation for optimization\n /// purposes, this operation decays to a normal multiplication; it is a\n /// license for the compiler to optimize, not a guarantee that any change\n /// occurs.\n @_transparent\n public static func product<T: AlgebraicField>(_ a: T, _ b: T) -> T {\n T._relaxedMul(a, b)\n }\n}\n\nextension Relaxed {\n /// a*b + c, computed _either_ with an FMA or with separate multiply and add,\n /// whichever is fastest according to the optimizer's heuristics.\n @_transparent\n public static func multiplyAdd<T: AlgebraicField>(\n _ a: T, _ b: T, _ c: T\n ) -> T {\n T._relaxedAdd(c, T._relaxedMul(a, b))\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "ElementaryFunctions.swift", "content": "//===--- ElementaryFunctions.swift ----------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\npublic protocol ElementaryFunctions: AdditiveArithmetic {\n /// The [exponential function][wiki] e^x whose base `e` is the base of the\n /// natural logarithm.\n ///\n /// For types that conform to ``RealFunctions`` see\n /// ``RealFunctions/exp2(_:)`` and ``RealFunctions/exp10(_:)``.\n ///\n /// [wiki]: https://en.wikipedia.org/wiki/Exponential_function\n static func exp(_ x: Self) -> Self\n \n /// exp(x) - 1, computed in such a way as to maintain accuracy for small x.\n ///\n /// When `x` is close to zero, the expression `.exp(x) - 1` suffers from\n /// catastrophic cancellation and the result will not have full accuracy.\n /// The `.expMinusOne(x)` function gives you a means to address this problem.\n ///\n /// As an example, consider the expression `(x + 1) * .exp(x) - 1`. When `x`\n /// is smaller than `.ulpOfOne`, this expression evaluates to `0.0`, when it\n /// should actually round to `2*x`. We can get a full-accuracy result by\n /// using the following instead:\n /// ```\n /// let t = .expMinusOne(x)\n /// return x*(t+1) + t // x*exp(x) + (exp(x)-1) = (x+1)*exp(x) - 1\n /// ```\n /// This re-written expression delivers an accurate result for all values\n /// of `x`, not just for small values.\n ///\n /// For types that conform to ``RealFunctions`` see\n /// ``RealFunctions/exp2(_:)`` and ``RealFunctions/exp10(_:)``.\n static func expMinusOne(_ x: Self) -> Self\n \n /// The [hyperbolic cosine][wiki] of `x`.\n /// ```\n /// e^x + e^-x\n /// cosh(x) = ------------\n /// 2\n /// ```\n ///\n /// See also ``acosh(_:)``.\n ///\n /// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function\n static func cosh(_ x: Self) -> Self\n \n /// The [hyperbolic sine][wiki] of `x`.\n /// ```\n /// e^x - e^-x\n /// sinh(x) = ------------\n /// 2\n /// ```\n ///\n /// See also ``asinh(_:)``.\n ///\n /// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function\n static func sinh(_ x: Self) -> Self\n \n /// The [hyperbolic tangent][wiki] of `x`.\n /// ```\n /// sinh(x)\n /// tanh(x) = ---------\n /// cosh(x)\n /// ```\n ///\n /// See also ``atanh(_:)``.\n ///\n /// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function\n static func tanh(_ x: Self) -> Self\n \n /// The [cosine][wiki] of `x`.\n ///\n /// For real types, `x` may be interpreted as an angle measured in radians.\n ///\n /// See also ``acos(_:)``.\n ///\n /// [wiki]: https://en.wikipedia.org/wiki/Cosine\n static func cos(_ x: Self) -> Self\n \n \n /// The [sine][wiki] of `x`.\n ///\n /// For real types, `x` may be interpreted as an angle measured in radians.\n ///\n /// See also ``asin(_:)``.\n ///\n /// [wiki]: https://en.wikipedia.org/wiki/Sine\n static func sin(_ x: Self) -> Self\n \n /// The [tangent][wiki] of `x`.\n ///\n /// For real types, `x` may be interpreted as an angle measured in radians.\n ///\n /// See also ``atan(_:)``.\n ///\n /// [wiki]: https://en.wikipedia.org/wiki/Tangent\n static func tan(_ x: Self) -> Self\n \n /// The [natural logarithm][wiki] of `x`.\n ///\n /// For types that conform to ``RealFunctions`` see also\n /// ``RealFunctions/log2(_:)`` and ``RealFunctions/log10(_:)``.\n ///\n /// [wiki]: https://en.wikipedia.org/wiki/Logarithm\n static func log(_ x: Self) -> Self\n \n /// log(1 + x), computed in such a way as to maintain accuracy for small x.\n ///\n /// For types that conform to ``RealFunctions`` see also\n /// ``RealFunctions/log2(_:)`` and ``RealFunctions/log10(_:)``.\n static func log(onePlus x: Self) -> Self\n \n /// The [inverse hyperbolic cosine][wiki] of `x`.\n ///\n /// ```\n /// cosh(acosh(x)) \u2245 x\n /// ```\n ///\n /// See also ``cosh(_:)``.\n ///\n /// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function\n static func acosh(_ x: Self) -> Self\n \n /// The [inverse hyperbolic sine][wiki] of `x`.\n ///\n /// ```\n /// sinh(asinh(x)) \u2245 x\n /// ```\n ///\n /// See also ``sinh(_:)``.\n ///\n /// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function\n static func asinh(_ x: Self) -> Self\n \n /// The [inverse hyperbolic tangent][wiki] of `x`.\n ///\n /// ```\n /// tanh(atanh(x)) \u2245 x\n /// ```\n ///\n /// See also ``tanh(_:)``.\n ///\n /// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function\n static func atanh(_ x: Self) -> Self\n \n /// The [arccosine][wiki] (inverse cosine) of `x`.\n ///\n /// For real types, the result may be interpreted as an angle measured in\n /// radians.\n ///\n /// ```\n /// cos(acos(x)) \u2245 x\n /// ```\n ///\n /// See also ``cos(_:)``.\n ///\n /// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions\n static func acos(_ x: Self) -> Self\n \n /// The [arcsine][wiki] (inverse sine) of `x`.\n ///\n /// For real types, the result may be interpreted as an angle measured in\n /// radians.\n ///\n /// ```\n /// sin(asin(x)) \u2245 x\n /// ```\n ///\n /// See also ``sin(_:)``.\n ///\n /// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions\n static func asin(_ x: Self) -> Self\n \n /// The [arctangent][wiki] (inverse tangent) of `x`.\n ///\n /// For real types, the result may be interpreted as an angle measured in\n /// radians.\n ///\n /// ```\n /// tan(atan(x)) \u2245 x\n /// ```\n ///\n /// See also ``tan(_:)``.\n /// For types that conform to ``RealFunctions``, you will sometimes want\n /// to use ``RealFunctions/atan2(y:x:)`` instead.\n ///\n /// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions\n static func atan(_ x: Self) -> Self\n \n /// exp(y * log(x)) computed with additional internal precision.\n ///\n /// The edge-cases of this function are defined based on the behavior of the\n /// expression `exp(y log x)`, matching IEEE 754's `powr` operation.\n /// In particular, this means that if `x` and `y` are both zero, `pow(x,y)`\n /// is `nan` for real types and `infinity` for complex types, rather than 1.\n ///\n /// There is also\n /// <doc:/documentation/RealModule/ElementaryFunctions/pow(_:_:)-9imp6>,\n /// whose behavior is defined in terms of repeated multiplication.\n static func pow(_ x: Self, _ y: Self) -> Self\n \n /// `x` raised to the nth power.\n ///\n /// The edge-cases of this function are defined in terms of repeated\n /// multiplication or division, rather than exp(n log x). In particular,\n /// `Float.pow(0, 0)` is 1.\n static func pow(_ x: Self, _ n: Int) -> Self\n \n /// The [square root][wiki] of `x`.\n ///\n /// [wiki]: https://en.wikipedia.org/wiki/Square_root\n static func sqrt(_ x: Self) -> Self\n \n /// The nth root of `x`.\n static func root(_ x: Self, _ n: Int) -> Self\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "RealFunctions.swift", "content": "//===--- RealFunctions.swift ----------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\npublic protocol RealFunctions: ElementaryFunctions {\n /// The signed angle formed in the plane between the vector `(x,y)` and the\n /// positive real axis, measured in radians.\n ///\n /// The result is in the interval `[-\u03c0, \u03c0]`.\n ///\n /// The argument order to `atan2` may be surprising to new programmers.\n /// The convention of `y` being the first argument goes back at least to\n /// Fortran IV in 1961 and is generally followed in computing with a few\n /// notable exceptions (e.g. Mathematica and Excel). This convention was\n /// originally chosen because of the mathematical definition of the\n /// function:\n ///\n /// ```\n /// atan2(y,x) = atan(y/x) if x > 0\n /// ```\n ///\n /// See also ``ElementaryFunctions/atan(_:)``, as well as the `phase` and\n /// `polar` properties defined on the `Complex` type.\n static func atan2(y: Self, x: Self) -> Self\n \n /// The [error function](https://en.wikipedia.org/wiki/Error_function)\n /// evaluated at `x`.\n static func erf(_ x: Self) -> Self\n \n /// The complimentary [error function](https://en.wikipedia.org/wiki/Error_function)\n /// evaluated at `x`.\n static func erfc(_ x: Self) -> Self\n \n /// 2 raised to the power x.\n ///\n /// See also ``log2(_:)``, ``ElementaryFunctions/exp(_:)``,\n /// ``ElementaryFunctions/expMinusOne(_:)``\n /// and ``ElementaryFunctions/pow(_:_:)-2qmul``.\n static func exp2(_ x: Self) -> Self\n \n /// 10 raised to the power x.\n ///\n /// See also ``log10(_:)``, ``ElementaryFunctions/exp(_:)``,\n /// ``ElementaryFunctions/expMinusOne(_:)``\n /// and ``ElementaryFunctions/pow(_:_:)-2qmul``.\n static func exp10(_ x: Self) -> Self\n \n /// The length of the vector `(x,y)`, computed in a manner that avoids\n /// spurious overflow or underflow.\n ///\n /// See also the `length` and `polar` properties defined on the `Complex`\n /// type.\n static func hypot(_ x: Self, _ y: Self) -> Self\n \n /// The [gamma function](https://en.wikipedia.org/wiki/Gamma_function) \u0393(x).\n static func gamma(_ x: Self) -> Self\n \n /// The base-2 logarithm of `x`.\n ///\n /// See also ``exp2(_:)``, ``ElementaryFunctions/log(_:)``,\n /// and ``ElementaryFunctions/log(onePlus:)``.\n static func log2(_ x: Self) -> Self\n \n /// The base-10 logarithm of `x`.\n ///\n /// See also ``exp10(_:)``, ``ElementaryFunctions/log(_:)``,\n /// and ``ElementaryFunctions/log(onePlus:)``.\n static func log10(_ x: Self) -> Self\n \n#if !os(Windows)\n /// The logarithm of the absolute value of the\n /// [gamma function](https://en.wikipedia.org/wiki/Gamma_function),\n /// log(|\u0393(x)|).\n ///\n /// Not available on Windows targets.\n static func logGamma(_ x: Self) -> Self\n \n /// The sign of the\n /// [gamma function](https://en.wikipedia.org/wiki/Gamma_function), \u0393(x).\n ///\n /// For `x >= 0`, `signGamma(x)` is `.plus`. For negative `x`, `signGamma(x)`\n /// is `.plus` when `x` is an integer, and otherwise it is `.minus` whenever\n /// `trunc(x)` is even, and `.plus` when `trunc(x)` is odd.\n ///\n /// This function is used together with ``logGamma(_:)``, which computes the\n /// logarithm of the absolute value of \u0393(x), to recover the sign information.\n ///\n /// Not available on Windows targets.\n static func signGamma(_ x: Self) -> FloatingPointSign\n#endif\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "GCD.swift", "content": "//===--- GCD.swift --------------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2021-2024 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// The [greatest common divisor][gcd] of `a` and `b`.\n///\n/// If both inputs are zero, the result is zero. If one input is zero, the\n/// result is the absolute value of the other input.\n///\n/// The result must be representable within its type. In particular, the gcd\n/// of a signed, fixed-width integer type's minimum with itself (or zero)\n/// cannot be represented, and results in a trap.\n///\n/// gcd(Int.min, Int.min) // Overflow error\n/// gcd(Int.min, 0) // Overflow error\n///\n/// [gcd]: https://en.wikipedia.org/wiki/Greatest_common_divisor\n@inlinable\npublic func gcd<T: BinaryInteger>(_ a: T, _ b: T) -> T {\n var x = a\n var y = b\n if x.magnitude < y.magnitude { swap(&x, &y) }\n // Avoid overflow when x = signed min, y = -1.\n if y.magnitude == 1 { return 1 }\n // Euclidean algorithm for GCD. It's worth using Lehmer instead for larger\n // integer types, but for now this is good and dead-simple and faster than\n // the other obvious choice, the binary algorithm.\n while y != 0 { (x, y) = (y, x%y) }\n // Try to convert result to T.\n if let result = T(exactly: x.magnitude) { return result }\n // If that fails, produce a diagnostic.\n fatalError(\"GCD (\\(x)) is not representable as \\(T.self).\")\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "SaturatingArithmetic.swift", "content": "//===--- SaturatingArithmetic.swift ---------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nextension FixedWidthInteger {\n /// `~0` (all-ones) if this value is negative, otherwise `0`.\n ///\n /// Note that if `Self` is unsigned, this always returns `0`,\n /// but it is useful for writing algorithms that are generic over\n /// signed and unsigned integers.\n @inline(__always) @usableFromInline\n var signbit: Self {\n return self < .zero ? ~.zero : .zero\n }\n \n /// Saturating integer addition\n ///\n /// `self + other` clamped to the representable range of the type. e.g.:\n /// ```\n /// let a: Int8 = 84\n /// let b: Int8 = 100\n /// // 84 + 100 = 184 is not representable as\n /// // Int8, so `c` is clamped to Int8.max (127).\n /// let c = a.addingWithSaturation(b)\n /// ```\n ///\n /// If the \"normal addition\" `self + other` does not trap,\n /// this method produces the same result.\n @inlinable\n public func addingWithSaturation(_ other: Self) -> Self {\n let (wrapped, overflow) = addingReportingOverflow(other)\n return overflow ? Self.max &- signbit : wrapped\n }\n \n /// Saturating integer subtraction\n ///\n /// `self - other` clamped to the representable range of the type. e.g.:\n /// ```\n /// let a: UInt = 37\n /// let b: UInt = 42\n /// // 37 - 42 = -5, which is not representable as\n /// // UInt, so `c` is clamped to UInt.min (zero).\n /// let c = a.subtractingWithSaturation(b)\n /// ```\n ///\n /// Note that `a.addingWithSaturation(-b)` is not always equivalent to\n /// `a.subtractingWithSaturation(b)`, because `-b` is not representable\n /// if `b` is the minimum value of a signed type.\n ///\n /// If the \"normal subtraction\" `self - other` does not trap,\n /// this method produces the same result.\n @inlinable\n public func subtractingWithSaturation(_ other: Self) -> Self {\n let (wrapped, overflow) = subtractingReportingOverflow(other)\n if !overflow { return wrapped }\n return Self.isSigned ? Self.max &- signbit : 0\n }\n \n /// Saturating integer negation\n ///\n /// For unsigned types, the result is always zero. This is not very\n /// interesting, but may occasionally be useful in generic contexts.\n /// For signed types, the result is `-self` unless `self` is `.min`,\n /// in which case the result is `.max`.\n @inlinable\n public func negatedWithSaturation() -> Self {\n Self.zero.subtractingWithSaturation(self)\n }\n \n /// Saturating integer multiplication\n ///\n /// `self * other` clamped to the representable range of the type. e.g.:\n /// ```\n /// let a: Int8 = -16\n /// let b: Int8 = -8\n /// // -16 * -8 = 128 is not representable as\n /// // Int8, so `c` is clamped to Int8.max (127).\n /// let c = a.multipliedWithSaturation(by: b)\n /// ```\n ///\n /// If the \"normal multiplication\" `self * other` does not trap,\n /// this method produces the same result.\n @inlinable\n public func multipliedWithSaturation(by other: Self) -> Self {\n let (high, low) = multipliedFullWidth(by: other)\n let wrapped = Self(truncatingIfNeeded: low)\n if high == wrapped.signbit { return wrapped }\n return Self.max &- high.signbit\n }\n \n /// Bitwise left shift with rounding and saturation.\n ///\n /// `self` multiplied by the rational number 2^(`count`), saturated to the\n /// range `Self.min ... Self.max`, and rounded according to `rule`.\n ///\n /// See `shifted(rightBy:rounding:)`, defined on `BinaryInteger`, for more\n /// discussion of rounding shifts with examples.\n ///\n /// - Parameters:\n /// - leftBy count: the number of bits to shift by. If positive, this is\n /// a left-shift, and if negative a right shift.\n /// - rounding rule: the direction in which to round if `count` is negative.\n @inlinable\n public func shiftedWithSaturation(\n leftBy count: Int,\n rounding rule: RoundingRule = .down\n ) -> Self {\n if count == 0 { return self }\n // If count is negative, negate it and do a right shift without\n // saturation instead, since we already have that implemented.\n guard count > 0 else {\n return shifted(\n rightBy: count.negatedWithSaturation(),\n rounding: rule\n )\n }\n let clamped = Self.max &- signbit\n guard count < Self.bitWidth else {\n // If count is bitWidth or greater, we always overflow\n // unless self is zero.\n return self == 0 ? 0 : clamped\n }\n // Now we have 0 < count < bitWidth, so we can use a nice\n // straightforward implementation; a shift overflows if\n // the complementary shift doesn't match sign-or-zero\n // extension. E.g.:\n //\n // - signed 0b0010_1111 << 2 overflows, because\n // 0b0010_1111 >> 5 is 0b0000_0001, which does not\n // equal 0b0000_0000\n //\n // - unsigned 0b0010_1111 << 2 does not overflow,\n // because 0b0010_0000 >> 6 is 0b0000_0000, which\n // does equal 0b0000_0000.\n let valueBits = Self.bitWidth &- (Self.isSigned ? 1 : 0)\n let wrapped = self &<< count\n let complement = valueBits &- count\n return self &>> complement == signbit ? wrapped : clamped\n }\n \n /// Bitwise left with rounding and saturation.\n ///\n /// `self` multiplied by the rational number 2^(`count`), saturated to the\n /// range `Self.min ... Self.max`, and rounded according to `rule`.\n ///\n /// See `shifted(rightBy:rounding:)` for more discussion of rounding\n /// shifts with examples.\n ///\n /// - Parameters:\n /// - leftBy count: the number of bits to shift by. If positive, this is a\n /// left-shift, and if negative a right shift.\n /// - rounding rule: the direction in which to round if `count` is negative.\n @_transparent\n public func shiftedWithSaturation<Count: BinaryInteger>(\n leftBy count: Count,\n rounding rule: RoundingRule = .down\n ) -> Self {\n self.shiftedWithSaturation(leftBy: Int(clamping: count), rounding: rule)\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "DivideWithRounding.swift", "content": "//===--- DivideWithRounding.swift -----------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nextension BinaryInteger {\n /// `self` divided by `other`, rounding the result according to `rule`.\n ///\n /// By default, this function uses ``RoundingRule/down``, which **is not\n /// the same** as the rounding of the `/` operator from the Swift standard\n /// library. They agree when the signs of the arguments match, but produce\n /// different results when the quotient is negative. This behavior is\n /// chosen because it generally produces a more useful remainder; in\n /// particular, when the divisor is positive, the remainder is always\n /// positive. To match the behavior of `/`, use ``RoundingRule/towardZero``.\n ///\n /// Note that the remainder of division is not always representable in an\n /// unsigned type if a rounding rule other than ``RoundingRule/down``,\n /// ``RoundingRule/towardZero``, or ``RoundingRule/requireExact`` is\n /// used. For example:\n /// ```swift\n /// let a: UInt = 5\n /// let b: UInt = 3\n /// let q = a.divided(by: b, rounding: .up) // 2\n /// let r = a - b*q // 5 - 3*2 overflows UInt.\n /// ```\n /// For this reason, there is no `remainder(dividingBy:rounding:)`\n /// operation defined on `BinaryInteger`. Signed integers do not have\n /// this problem, so the `SignedInteger` protocol is extended with\n /// ``SignedInteger/divided(by:rounding:)`` returning both quotient\n /// and remainder.\n @inlinable\n public func divided(\n by other: Self,\n rounding rule: RoundingRule = .down\n ) -> Self {\n // \"Normal divsion\" rounds toward zero, so we get self = q*other + r\n // with |r| < |other| and r matching the sign of self.\n let q = self / other\n let r = self - q*other\n // In every rounding mode, the result is the same when the result is\n // exact.\n if r == 0 { return q }\n // From this point forward, we can assume r != 0.\n //\n // To get the quotient and remainder rounded as directed by rule, we\n // will adjust q and r. Note that the quotient is either q-1 or q (if\n // q is negative) or q or q+1 (if q is positive), because q has been\n // rounded toward zero.\n //\n // If we subtract 1 from q, we add other to r to compensate, because:\n // \n // self = q*other + r\n // = (q-1)*other + (r+other)\n //\n // Similarly, if we add 1 to q, we subtract other from r to compensate.\n switch rule {\n case .down:\n // For rounding down, we want to have r match the sign of other\n // rather than self; this means that if the signs of r and other\n // disagree, we have to adjust q downward and r to match.\n if other.signum() != r.signum() { return q-1 }\n return q\n \n case .up:\n // For rounding up, we want to have r have the opposite sign of\n // other; if not, we adjust q upward and r to match.\n if other.signum() == r.signum() { return q+1 }\n return q\n \n case .towardZero:\n // This is exactly what the `/` operator did for us.\n return q\n \n case .awayFromZero:\n break\n \n case .toNearestOrDown:\n if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||\n 2*r.magnitude == other.magnitude && other.signum() != r.signum() {\n break\n }\n return q\n \n case .toNearestOrUp:\n if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||\n 2*r.magnitude == other.magnitude && other.signum() == r.signum() {\n break\n }\n return q\n \n case .toNearestOrZero:\n if r.magnitude <= other.magnitude.shifted(rightBy: 1, rounding: .down) {\n return q\n }\n // Otherwise, round q away from zero.\n \n case .toNearestOrAway:\n if r.magnitude < other.magnitude.shifted(rightBy: 1, rounding: .up) {\n return q\n }\n \n case .toNearestOrEven:\n // First guarantee that |r| <= |other/2|; if not we have to round away\n // instead, so break to do that.\n if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||\n 2*r.magnitude == other.magnitude && !q.isMultiple(of: 2) {\n break\n }\n return q\n \n case .toOdd:\n // If q is already odd, we have the correct result.\n if q._lowWord & 1 == 1 { return q }\n \n case .requireExact:\n preconditionFailure(\"Division was not exact.\")\n }\n \n // We didn't have the right result, so round q away from zero.\n return other.signum() == r.signum() ? q+1 : q-1\n }\n \n // TODO: make this API and make it possible to implement more efficiently.\n // Customization point on new/revised integer protocol? Shouldn't have to\n // go through .words.\n \n /// The index of the most-significant set bit.\n ///\n /// - Precondition: self is assumed to be non-zero (should be changed\n /// if/when this becomes API).\n @usableFromInline\n internal var _msb: Int {\n // a == 0 is never used for division, because this is called\n // on the divisor which cannot be zero as a precondition; if\n // this becomes API, the behavior for this case will have to\n // be defined.\n assert(self != 0)\n // Because self is non-zero, mswIndex is guaranteed to exist,\n // hence force-unwrap is appropriate.\n let mswIndex = words.lastIndex { $0 != 0 }!\n let mswBits = UInt.bitWidth * words.distance(from: words.startIndex, to: mswIndex)\n return mswBits + (UInt.bitWidth - words[mswIndex].leadingZeroBitCount - 1)\n }\n}\n\nextension SignedInteger {\n /// Divides `self` by `other`, rounding the quotient according to `rule`,\n /// and returns the remainder.\n ///\n /// The default rounding rule is ``RoundingRule/down``, which _is not the\n /// same_ as the behavior of the `%` operator from the Swift standard\n /// library, but is chosen because it generally produces a more useful\n /// remainder. To match the behavior of `%`, use ``RoundingRule/towardZero``.\n ///\n /// - Precondition: `other` cannot be zero.\n @inlinable\n public func remainder(\n dividingBy other: Self,\n rounding rule: RoundingRule = .down\n ) -> Self {\n // Produce correct remainder for the .min/-1 case, rather than trapping.\n if other == -1 { return 0 }\n return self.divided(by: other, rounding: rule).remainder\n }\n \n /// Divides `self` by `other`, rounding the quotient according to `rule`,\n /// and returns both the quotient and remainder.\n ///\n /// The default rounding rule is ``RoundingRule/down``, which _is not the\n /// same_ as the behavior of the `%` operator from the Swift standard\n /// library, but is chosen because it generally produces a more useful\n /// remainder. To match the behavior of `/`, use ``RoundingRule/towardZero``.\n ///\n /// Because the default rounding mode does not match Swift's standard\n /// library, this function is a disfavored overload of `divided(by:)`\n /// instead of using the name `quotientAndRemainder(dividingBy:)`, which\n /// would shadow the standard library operation and change the behavior\n /// of any existing use sites. To call this method, you must explicitly\n /// bind the result to a tuple:\n ///\n /// // This calls BinaryInteger's method, which returns only\n /// // the quotient.\n /// let result = 5.divided(by: 3, rounding: .up) // 2\n ///\n /// // This calls SignedInteger's method, which returns both\n /// // the quotient and remainder.\n /// let (q, r) = 5.divided(by: 3, rounding: .up) // (q = 2, r = -1)\n @inlinable @inline(__always) @_disfavoredOverload\n public func divided(\n by other: Self,\n rounding rule: RoundingRule = .down\n ) -> (quotient: Self, remainder: Self) {\n // \"Normal divsion\" rounds toward zero, so we get self = q*other + r\n // with |r| < |other| and r matching the sign of self.\n let q = self / other\n let r = self - q*other\n // In every rounding mode, the result is the same when the result is\n // exact.\n if r == 0 { return (q, r) }\n // From this point forward, we can assume r != 0.\n //\n // To get the quotient and remainder rounded as directed by rule, we\n // will adjust q and r. Note that the quotient is either q-1 or q (if\n // q is negative) or q or q+1 (if q is positive), because q has been\n // rounded toward zero.\n //\n // If we subtract 1 from q, we add other to r to compensate, because:\n //\n // self = q*other + r\n // = (q-1)*other + (r+other)\n //\n // Similarly, if we add 1 to q, we subtract other from r to compensate.\n switch rule {\n case .down:\n // For rounding down, we want to have r match the sign of other\n // rather than self; this means that if the signs of r and other\n // disagree, we have to adjust q downward and r to match.\n return other.signum() == r.signum() ? (q, r) : (q-1, r+other)\n \n case .up:\n // For rounding up, we want to have r have the opposite sign of\n // other; if not, we adjust q upward and r to match.\n return other.signum() == r.signum() ? (q+1, r-other) : (q, r)\n \n case .towardZero:\n // This is exactly what the `/` operator did for us.\n return (q, r)\n \n case .awayFromZero:\n break\n \n case .toNearestOrDown:\n // If |r| < |other/2|, we already rounded q to nearest. If the are\n // equal and q is negative, then we already broke the tie in the right\n // direction. However, we don't have access to the before-rounding q,\n // which may have rounded up to zero, losing the sign information, so\n // we have to look at other and r instead.\n if 2*r.magnitude < other.magnitude ||\n 2*r.magnitude == other.magnitude && other.signum() == r.signum() {\n return (q, r)\n }\n \n case .toNearestOrUp:\n // If |r| < |other/2|, we already rounded q to nearest. If the are\n // equal and q is non-negative, then we already broke the tie in the\n // right direction.\n if 2*r.magnitude < other.magnitude ||\n 2*r.magnitude == other.magnitude && other.signum() != r.signum() {\n return (q, r)\n }\n \n case .toNearestOrZero:\n // Check first if |r| <= |other/2|. If this holds, we have already\n // rounded q correctly. Because we're working with magnitudes, we can\n // safely compute 2r without worrying about overflow, even for fixed-\n // width types, because r cannot be .min (because |r| < |other| by\n // construction).\n if 2*r.magnitude <= other.magnitude {\n return (q, r)\n }\n \n case .toNearestOrAway:\n // Check first if |r| < |other/2|. If this holds, we already rounded\n // q to nearest.\n if 2*r.magnitude < other.magnitude {\n return (q, r)\n }\n \n case .toNearestOrEven:\n // If |r| < |other/2|, we already rounded q to nearest. If the are\n // equal and q is even, then we already broke the tie in the right\n // direction.\n if 2*r.magnitude < other.magnitude ||\n 2*r.magnitude == other.magnitude && q.isMultiple(of: 2) {\n return (q, r)\n }\n \n case .toOdd:\n // If q is already odd, we have the correct result.\n if q._lowWord & 1 == 1 { return (q, r) }\n \n case .requireExact:\n preconditionFailure(\"Division was not exact.\")\n }\n \n // Fallthrough behavior is to round q away from zero and adjust r to\n // match.\n return other.signum() == r.signum() ? (q+1, r-other) : (q-1, r+other)\n }\n}\n\n/// `a = quotient*b + remainder`, with `remainder >= 0`.\n///\n/// When `a` and `b` are both positive, `quotient` is `a/b` and `remainder`\n/// is `a%b`.\n///\n/// Rounding the quotient so that the remainder is non-negative is called\n/// \"Euclidean division\". This is not a _rounding rule_, as `quotient`\n/// cannot be determined from the unrounded value `a/b`; we need to also\n/// know the sign of `a` or `b` or `r` to know which way to round. Because\n/// of this, is not present in the `RoundingRule` enum and uses a separate\n/// API from the other division operations.\n///\n/// - Parameters:\n/// - a: The dividend\n/// - b: The divisor\n///\n/// - Precondition: `b` must be non-zero, and the quotient `a/b` must be\n/// representable. In particular, if `T` is a signed fixed-width integer\n/// type, then `euclideanDivision(T.min, -1)` will trap, because `-T.min`\n/// is not representable.\n///\n/// - Returns: `(quotient, remainder)`, with `0 <= remainder < b.magnitude`.\npublic func euclideanDivision<T>(_ a: T, _ b: T) -> (quotient: T, remainder: T)\nwhere T: SignedInteger\n{\n a.divided(by: b, rounding: a >= 0 ? .towardZero : .awayFromZero)\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "ShiftWithRounding.swift", "content": "//===--- ShiftWithRounding.swift ------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nextension BinaryInteger {\n /// `self` divided by 2^(`count`), rounding the result according to `rule`.\n ///\n /// The default rounding rule is ``RoundingRule/down``, which matches the\n /// behavior of the `>>` operator from the standard library.\n ///\n /// Some examples of different rounding rules:\n ///\n /// // 3/2 is 1.5, which rounds (down by default) to 1.\n /// 3.shifted(rightBy: 1)\n ///\n /// // 1.5 rounds up to 2.\n /// 3.shifted(rightBy: 1, rounding: .up)\n ///\n /// // The two closest values are 1 and 2, 1 is returned because it\n /// // is odd.\n /// 3.shifted(rightBy: 1, rounding: .toOdd)\n ///\n /// // 6/4 = 1.5, so the tie is broken in favor of the even value 2.\n /// 6.shifted(rightBy: 2, rounding: .toNearestOrEven)\n ///\n /// // 4/4 is exactly 1, so this does not trap.\n /// 4.shifted(rightBy: 2, rounding: .requireExact)\n ///\n /// // 5/2 is 2.5, which is not an integer, so this traps.\n /// 5.shifted(rightBy: 1, rounding: .requireExact)\n ///\n /// When `Self(1) << count` is positive, the following are equivalent:\n ///\n /// a.shifted(rightBy: count, rounding: rule)\n /// a.divided(by: 1 << count, rounding: rule)\n @inlinable\n public func shifted(\n rightBy count: Int,\n rounding rule: RoundingRule = .down\n ) -> Self {\n // Easiest case: count is zero or negative, so shift is always exact;\n // delegate to the normal >> operator.\n if count <= 0 { return self >> count }\n if count >= bitWidth {\n // Note: what follows would cause an infinite loop if bitWidth <= 1.\n // This will essentially never happen, but in the highly unlikely event\n // that we encounter such a case, we promote to Int8, do the shift, and\n // then convert back to the appropriate result type.\n if bitWidth <= 1 {\n return Self(Int8(self).shifted(rightBy: count, rounding: rule))\n }\n // That pathological case taken care of, we can now handle over-wide\n // shifts by first shifting all but bitWidth - 1 bits with sticky\n // rounding, and then shifting the remaining bitWidth - 1 bits with\n // the desired rounding mode.\n let count = count - (bitWidth - 1)\n let floor = self >> count\n let lost = self - (floor << count)\n let sticky = floor | (lost == 0 ? 0 : 1)\n return sticky.shifted(rightBy: bitWidth - 1, rounding: rule)\n }\n // Now we are in the happy case: 0 < count < bitWidth, which makes all\n // the math to handle rounding simpler.\n //\n // TODO: If we were really, really careful about overflow, some of these\n // could be made simpler. E.g. mathematically round up is implemented here\n // via:\n //\n // floor = self >> count\n // mask = 1 << count - 1\n // lost = self & mask\n // return floor + (lost == 0 ? 0 : 1)\n //\n // _if_ we didn't have to worry about intermediate overflow (either because\n // self is bounded away from .max or because we don't have a fixed-width\n // type), then we could use the following instead:\n //\n // mask = 1 << count - 1\n // return (self + mask) >> count\n //\n // However, self + mask can overflow, e.g. if we're shifting .max by 1:\n //\n // mask = 1 << 1 - 1 = 1\n // self + mask = .max + 1 // uh-oh\n //\n // This cannot occur for arbitrary-precision numbers, so we could use\n // the simpler expressions for those (but those are precisely the cases\n // where performance of rounding does not matter much, because shifts\n // get swamped by even basic arithmetic). More interesting, we could\n // promote fixed-width numbers to a wider type, preventing this\n // intermediate overflow and allowing us to use the simpler expressions\n // much of the time. We could also explicitly _detect_ the overflow if\n // it happens and patch up the result, though this is a little bit tricky\n // because addingReportingOverflow and friends do not exist on\n // BinaryInteger. Hence, this is a TODO for the future.\n let mask = Magnitude(1) << count - 1\n let lost = Magnitude(truncatingIfNeeded: self) & mask\n let floor = self >> count\n let ceiling = floor + (lost == 0 ? 0 : 1)\n let half: Magnitude = (1 as Magnitude) << (count &- 1)\n switch rule {\n case .down:\n return floor\n case .up:\n return ceiling\n case .towardZero:\n return self > 0 ? floor : ceiling\n case .awayFromZero:\n return self < 0 ? floor : ceiling\n case .toNearestOrDown:\n return floor + Self((lost + (half - 1)) >> count)\n case .toNearestOrUp:\n return floor + Self((lost + half) >> count)\n case .toNearestOrZero:\n let round = half - (self < 0 ? 0 : 1)\n return floor + Self((round + lost) >> count)\n case .toNearestOrAway:\n let round = half - (self > 0 ? 0 : 1)\n return floor + Self((round + lost) >> count)\n case .toNearestOrEven:\n let round = mask >> 1 + Magnitude(floor & 1)\n return floor + Self((round + lost) >> count)\n case .toOdd:\n return floor | (lost == 0 ? 0 : 1)\n case .requireExact:\n precondition(lost == 0, \"shift was not exact.\")\n return floor\n }\n }\n \n /// `self` divided by 2^(`count`), rounding the result according to `rule`.\n ///\n /// The default rounding rule is ``RoundingRule/down``, which matches the\n /// behavior of the `>>` operator from the standard library.\n ///\n /// Some examples of different rounding rules:\n ///\n /// // 3/2 is 1.5, which rounds (down by default) to 1.\n /// 3.shifted(rightBy: 1)\n ///\n /// // 1.5 rounds up to 2.\n /// 3.shifted(rightBy: 1, rounding: .up)\n ///\n /// // The two closest values are 1 and 2, 1 is returned because it\n /// // is odd.\n /// 3.shifted(rightBy: 1, rounding: .toOdd)\n ///\n /// // 6/4 = 1.5, so the tie is broken in favor of the even value 2.\n /// 6.shifted(rightBy: 2, rounding: .toNearestOrEven)\n ///\n /// // 4/4 is exactly 1, so this does not trap.\n /// 4.shifted(rightBy: 2, rounding: .requireExact)\n ///\n /// // 5/2 is 2.5, which is not an integer, so this traps.\n /// 5.shifted(rightBy: 1, rounding: .requireExact)\n ///\n /// When `Self(1) << count` is positive, the following are equivalent:\n ///\n /// a.shifted(rightBy: count, rounding: rule)\n /// a.divided(by: 1 << count, rounding: rule)\n @_transparent\n public func shifted<Count: BinaryInteger>(\n rightBy count: Count,\n rounding rule: RoundingRule = .down\n ) -> Self {\n self.shifted(rightBy: Int(clamping: count), rounding: rule)\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Rotate.swift", "content": "//===--- Rotate.swift -----------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nextension FixedWidthInteger {\n @_transparent @usableFromInline\n internal func rotateImplementation(right count: Int) -> Self {\n // We don't have an unsigned right shift operation for signed values, so\n // we need to convert to an unsigned type. The only unsigned type that's\n // guaranteed to be able to represent the bit pattern of any Self value\n // is Magnitude. It would be possible to have Magnitude be _wider_ than\n // Self, but that's OK as long as we're careful to complement the shift\n // count using Self.bitWidth and not Magnitude.bitWidth or zero.\n let bitPattern = Magnitude(truncatingIfNeeded: self)\n let countComplement = Self.bitWidth &- count\n return Self(truncatingIfNeeded:\n bitPattern &>> count | bitPattern &<< countComplement\n )\n }\n \n /// `self` rotated bitwise right by `count` bits.\n ///\n /// Equivalent to `rotated(left: 0 &- count)`.\n @inlinable\n public func rotated<Count: BinaryInteger>(right count: Count) -> Self {\n rotateImplementation(right: Int(truncatingIfNeeded: count))\n }\n \n /// `self` rotated bitwise left by `count` bits.\n ///\n /// Equivalent to `rotated(right: 0 &- count)`.\n @inlinable\n public func rotated<Count: BinaryInteger>(left count: Count) -> Self {\n rotateImplementation(right: 0 &- Int(truncatingIfNeeded: count))\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "RoundingRule.swift", "content": "//===--- RoundingRule.swift -----------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2021-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// A rule that defines how to select one of the two representable results\n/// closest to a given value.\n///\n/// [Wikipedia](https://en.wikipedia.org/wiki/Rounding#Rounding_to_integer)\n/// provides a good overview of different rounding rules.\n///\n/// Examples using rounding to integer to illustrate the various options:\n/// ```\n/// Directed rounding rules\n/// \n/// value | down | up | towardZero | awayFromZero |\n/// =======+==============+==============+==============+==============+\n/// -1.5 | -2 | -1 | -1 | -2 |\n/// -------+--------------+--------------+--------------+--------------+\n/// -0.5 | -1 | 0 | 0 | -1 |\n/// -------+--------------+--------------+--------------+--------------+\n/// 0.5 | 0 | 1 | 0 | 1 |\n/// -------+--------------+--------------+--------------+--------------+\n/// 0.7 | 0 | 1 | 0 | 1 |\n/// -------+--------------+--------------+--------------+--------------+\n/// 1.2 | 1 | 2 | 1 | 2 |\n/// -------+--------------+--------------+--------------+--------------+\n/// 2.0 | 2 | 2 | 2 | 2 |\n/// -------+--------------+--------------+--------------+--------------+\n///\n/// toNearestOr... rounding rules\n///\n/// value | orDown | orUp | orZero | orAway | orEven |\n/// =======+==========+==========+==========+==========+==========+\n/// -1.5 | -2 | -1 | -1 | -2 | -2 |\n/// -------+----------+----------+----------+----------+----------+\n/// -0.5 | -1 | 0 | 0 | -1 | 0 |\n/// -------+----------+----------+----------+----------+----------+\n/// 0.5 | 0 | 1 | 0 | 1 | 0 |\n/// -------+----------+----------+----------+----------+----------+\n/// 0.7 | 1 | 1 | 1 | 1 | 1 |\n/// -------+----------+----------+----------+----------+----------+\n/// 1.2 | 1 | 1 | 1 | 1 | 1 |\n/// -------+----------+----------+----------+----------+----------+\n/// 2.0 | 2 | 2 | 2 | 2 | 2 |\n/// -------+----------+----------+----------+----------+----------+\n///\n/// Specialized rounding rules\n///\n/// value | toOdd | requireExact |\n/// =======+==============+================+\n/// -1.5 | -1 | trap |\n/// -------+--------------+----------------+\n/// -0.5 | -1 | trap |\n/// -------+--------------+----------------+\n/// 0.5 | 1 | trap |\n/// -------+--------------+----------------+\n/// 0.7 | 1 | trap |\n/// -------+--------------+----------------+\n/// 1.2 | 1 | trap |\n/// -------+--------------+----------------+\n/// 2.0 | 2 | 2 |\n/// -------+--------------+----------------+\n/// ```\npublic enum RoundingRule {\n /// Produces the closest representable value that is less than or equal\n /// to the value being rounded.\n ///\n /// This is the default rounding mode for integer shifts, including the\n /// shift operators defined in the standard library. \n ///\n /// Examples:\n /// - `(-4).divided(by: 3, rounding: .down)` is `-2`, because \u20132 is the\n /// largest integer less than \u20134/3 = \u20131.3\u0305\n /// - `5.shifted(rightBy: 1, rounding: .down)` is `2`, because 2 is the\n /// largest integer less than 5/2 = 2.5.\n case down\n \n /// Produces the closest representable value that is greater than or equal\n /// to the value being rounded.\n ///\n /// Examples:\n /// - `(-4).divided(by: 3, rounding: .up)` is `-1`, because \u20131 is the\n /// smallest integer greater than \u20134/3 = \u20131.3\u0305\n /// - `5.shifted(rightBy: 1, rounding: .up)` is `3`, because 3 is the\n /// smallest integer greater than 5/2 = 2.5.\n case up\n \n /// Produces the closest representable value whose magnitude is less than\n /// or equal to that of the value being rounded.\n ///\n /// Examples:\n /// - `(-4).divided(by: 3, rounding: .towardZero)` is `-1`, because \u20131\n /// is the closest integer to \u20134/3 = \u20131.3\u0305 with smaller magnitude.\n /// - `5.shifted(rightBy: 1, rounding: .towardZero)` is `2`, because 2\n /// is the closest integer to 5/2 = 2.5 with smaller magnitude.\n case towardZero\n \n /// Produces the closest representable value whose magnitude is greater\n /// than or equal to that of the value being rounded.\n ///\n /// Examples:\n /// - `(-4).divided(by: 3, rounding: .awayFromZero)` is `-2`, because \u20132\n /// is the closest integer to \u20134/3 = \u20131.3\u0305 with greater magnitude.\n /// - `5.shifted(rightBy: 1, rounding: .awayFromZero)` is `3`, because 3\n /// is the closest integer to 5/2 = 2.5 with greater magnitude.\n case awayFromZero\n \n /// If the value being rounded is representable, that value is returned.\n /// Otherwise, whichever of the two closest representable values has its\n /// least significant bit set is returned.\n ///\n /// This is also called _sticky rounding_, and it is useful as an\n /// implementation detail because it has the property that if we do\n /// rounding in two steps, first to intermediate precision p\u2081 with .toOdd,\n /// then to the final precision p\u2082 with any other rounding mode, the result\n /// we get is the same as if we rounded directly to p\u2082 in the desired mode\n /// so long as p\u2082 + 1 < p\u2081. Other rounding modes do not have this property,\n /// and admit _double roundings_ when interoperating with some modes.\n ///\n /// Examples:\n /// - `(-4).divided(by: 3, rounding: .toOdd)` is `-1`, because \u20134/3 = \u20131.3\u0305\n /// is not an exact integer, and \u20131 is the closest odd integer.\n /// - `4.shifted(rightBy: 1, rounding: .toOdd)` is `2`,\n /// even though 2 is even, because 4/2 is exactly 2 and no rounding occurs.\n case toOdd\n \n /// Produces the representable value that is closest to the value being\n /// rounded. If two values are equally close, the one that is less than\n /// the value being rounded is chosen.\n ///\n /// Examples:\n /// - `(-4).divided(by: 3, rounding: .toNearestOrDown)`\n /// is `-1`, because \u20134/3 = \u20131.3\u0305 is closer to \u20131 than it is to \u20132.\n ///\n /// - `5.shifted(rightBy: 1, rounding: .toNearestOrDown)` is `2`,\n /// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is less.\n case toNearestOrDown\n \n /// Produces the representable value that is closest to the value being\n /// rounded. If two values are equally close, the one that is greater than\n /// the value being rounded is chosen.\n ///\n /// Examples:\n /// - `(-4).divided(by: 3, rounding: .toNearestOrUp)`\n /// is `-1`, because \u20134/3 = \u20131.3\u0305 is closer to \u20131 than it is to \u20132.\n ///\n /// - `5.shifted(rightBy: 1, rounding: .toNearestOrUp)` is `3`,\n /// because 5/2 = 2.5 is equally close to 2 and 3, and 3 is greater.\n case toNearestOrUp\n \n /// Produces the representable value that is closest to the value being\n /// rounded. If two values are equally close, the one that has smaller\n /// magnitude is returned.\n ///\n /// Examples:\n /// - `(-4).divided(by: 3, rounding: .toNearestOrZero)`\n /// is `-1`, because \u20134/3 = \u20131.3\u0305 is closer to \u20131 than it is to \u20132.\n ///\n /// - `5.shifted(rightBy: 1, rounding: .toNearestOrZero)` is `2`,\n /// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is closer to zero.\n case toNearestOrZero\n \n /// Produces the representable value that is closest to the value being\n /// rounded. If two values are equally close, the one that has greater\n /// magnitude is returned.\n ///\n /// Examples:\n /// - `(-4).divided(by: 3, rounding: .toNearestOrAway)`\n /// is `-1`, because \u20134/3 = \u20131.3\u0305 is closer to \u20131 than it is to \u20132.\n ///\n /// - `5.shifted(rightBy: 1, rounding: .toNearestOrAway)` is `3`,\n /// because 5/2 = 2.5 is equally close to 2 and 3, and 3 is further away\n /// from zero.\n case toNearestOrAway\n \n /// Produces the representable value that is closest to the value being\n /// rounded. If two values are equally close, the one whose least\n /// significant bit is not set is returned.\n ///\n /// Examples:\n /// - `(-4).divided(by: 3, rounding: .toNearestOrEven)`\n /// is `-1`, because \u20134/3 = \u20131.3\u0305 is closer to \u20131 than it is to \u20132.\n ///\n /// - `5.shifted(rightBy: 1, rounding: .toNearestOrEven)` is `2`,\n /// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is even.\n case toNearestOrEven\n \n /// If the value being rounded is representable, that value is returned.\n /// Otherwise, a precondition failure occurs.\n ///\n /// Examples:\n /// - `(-4).divided(by: 3, rounding: .requireExact)` will trap,\n /// because \u20134/3 = \u20131.3\u0305 is not an integer.\n case requireExact\n}\n\nextension RoundingRule {\n /// Produces the representable value that is closest to the value being\n /// rounded. If two values are equally close, the one that has greater\n /// magnitude is returned.\n ///\n /// > Deprecated: Use `.toNearestOrAway` instead.\n @inlinable\n @available(*, deprecated, renamed: \"toNearestOrAway\")\n public static var toNearestOrAwayFromZero: Self { .toNearestOrAway }\n}\n\nextension FloatingPoint {\n /// `self` rounded to integer according to `rule`.\n ///\n /// This mirrors the standard library `rounded` API, providing access to\n /// the expanded set of rounding rules defined in IntegerUtilities. It is\n /// not just a shadow because that would lead to ambiguity errors in\n /// existing code that uses the shortened `rounded(.down)` form.\n @inlinable @inline(__always)\n public func rounding(_ rule: RoundingRule) -> Self {\n switch rule {\n case .down:\n return rounded(.down)\n case .up:\n return rounded(.up)\n case .towardZero:\n return rounded(.towardZero)\n case .awayFromZero:\n return rounded(.awayFromZero)\n case .toNearestOrDown:\n // FP doesn't have toNearestOrDown, so round toNearestOrEven and fixup\n // any exact-halfway cases.\n let nearest = rounded(.toNearestOrEven)\n return nearest - self == 1/2 ? rounded(.down) : nearest\n case .toNearestOrUp:\n // FP doesn't have toNearestOrUp, so round toNearestOrEven and fixup\n // any exact-halfway cases.\n let nearest = rounded(.toNearestOrEven)\n return self - nearest == 1/2 ? rounded(.up) : nearest\n case .toNearestOrZero:\n // FP doesn't have toNearestOrZero, so round toNearestOrEven and fixup\n // any exact-halfway cases.\n let nearest = rounded(.toNearestOrEven)\n return (self - nearest).magnitude == 1/2 ? rounded(.towardZero) : nearest\n case .toNearestOrAway:\n return self.rounded(.toNearestOrAwayFromZero)\n case .toNearestOrEven:\n return self.rounded(.toNearestOrEven)\n case .toOdd:\n let trunc = rounded(.towardZero)\n if trunc == self { return trunc }\n let one = Self(signOf: self, magnitudeOf: 1)\n // We have eliminated all large values at this point; add \u00b10.5, and see\n // which way that rounds, then select the other value.\n let even = (trunc + one/2).rounded(.toNearestOrEven)\n return trunc == even ? trunc + one : trunc\n case .requireExact:\n let trunc = rounded(.towardZero)\n precondition(isInfinite || trunc == self, \"\\(self) is not an exact integer.\")\n return self\n }\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Numerics.swift", "content": "//===--- Numerics.swift ---------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n// A module that re-exports the complete Swift Numerics public API.\n@_exported import ComplexModule\n@_exported import IntegerUtilities\n@_exported import RealModule"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Complex+StringConvertible.swift", "content": "//===--- Complex+StringConvertible.swift ----------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nextension Complex: CustomStringConvertible {\n public var description: String {\n guard isFinite else { return \"inf\" }\n return \"(\\(x), \\(y))\"\n }\n}\n\n#if compiler(>=6.0)\n@_unavailableInEmbedded\n#endif\nextension Complex: CustomDebugStringConvertible {\n public var debugDescription: String {\n \"Complex<\\(RealType.self)>(\\(String(reflecting: x)), \\(String(reflecting: y)))\"\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Complex+IntegerLiteral.swift", "content": "//===--- Complex+IntegerLiteral.swift -------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nextension Complex: ExpressibleByIntegerLiteral {\n public typealias IntegerLiteralType = RealType.IntegerLiteralType\n \n @inlinable\n public init(integerLiteral value: IntegerLiteralType) {\n self.init(RealType(integerLiteral: value))\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Complex+AdditiveArithmetic.swift", "content": "//===--- Complex+AdditiveArithmetic.swift ---------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nimport RealModule\n\nextension Complex: AdditiveArithmetic {\n /// The additive identity, with real and imaginary parts both zero.\n ///\n /// See also: ``one``, ``i``, ``infinity``\n @_transparent\n public static var zero: Complex {\n Complex(0, 0)\n }\n \n @_transparent\n public static func +(z: Complex, w: Complex) -> Complex {\n return Complex(z.x + w.x, z.y + w.y)\n }\n \n @_transparent\n public static func -(z: Complex, w: Complex) -> Complex {\n return Complex(z.x - w.x, z.y - w.y)\n }\n \n @_transparent\n public static func +=(z: inout Complex, w: Complex) {\n z = z + w\n }\n \n @_transparent\n public static func -=(z: inout Complex, w: Complex) {\n z = z - w\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Complex.swift", "content": "//===--- Complex.swift ----------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nimport RealModule\n\n// A [complex number](https://en.wikipedia.org/wiki/Complex_number).\n// See Documentation.docc/Complex.md for more details.\n@frozen\npublic struct Complex<RealType> where RealType: Real {\n // A note on the `x` and `y` properties\n //\n // `x` and `y` are the names we use for the raw storage of the real and\n // imaginary components of our complex number. We also provide public\n // `.real` and `.imaginary` properties, which wrap this storage and\n // fixup the semantics for non-finite values.\n \n /// The storage for the real component of the value.\n @usableFromInline @inline(__always)\n internal var x: RealType\n \n /// The storage for the imaginary part of the value.\n @usableFromInline @inline(__always)\n internal var y: RealType\n \n /// A complex number constructed by specifying the real and imaginary parts.\n @_transparent\n public init(_ real: RealType, _ imaginary: RealType) {\n x = real\n y = imaginary\n }\n}\n\nextension Complex: Sendable where RealType: Sendable { }\n\n// MARK: - Basic properties\nextension Complex {\n /// The real part of this complex value.\n ///\n /// If `z` is not finite, `z.real` is `.nan`.\n public var real: RealType {\n @_transparent\n get { isFinite ? x : .nan }\n\n @_transparent\n set { x = newValue }\n }\n \n /// The imaginary part of this complex value.\n ///\n /// If `z` is not finite, `z.imaginary` is `.nan`.\n public var imaginary: RealType {\n @_transparent\n get { isFinite ? y : .nan }\n\n @_transparent\n set { y = newValue }\n }\n \n /// The raw representation of the value.\n ///\n /// Use this when you need the underlying RealType values,\n /// without fixup for NaN or infinity.\n public var rawStorage: (x: RealType, y: RealType) {\n @_transparent\n get { (x, y) }\n @_transparent\n set { (x, y) = newValue }\n }\n \n /// The raw representation of the real part of this value.\n @available(*, deprecated, message: \"Use rawStorage\")\n @_transparent\n public var _rawX: RealType { x }\n \n /// The raw representation of the imaginary part of this value.\n @available(*, deprecated, message: \"Use rawStorage\")\n @_transparent\n public var _rawY: RealType { y }\n}\n \nextension Complex {\n /// The imaginary unit.\n ///\n /// See also ``zero``, ``one`` and ``infinity``.\n @_transparent\n public static var i: Complex {\n Complex(0, 1)\n }\n \n /// The point at infinity.\n ///\n /// See also ``zero``, ``one`` and ``i``.\n @_transparent\n public static var infinity: Complex {\n Complex(.infinity, 0)\n }\n \n /// True if this value is finite.\n ///\n /// A complex value is finite if neither component is an infinity or nan.\n ///\n /// See also ``isNormal``, ``isSubnormal`` and ``isZero``.\n @_transparent\n public var isFinite: Bool {\n x.isFinite && y.isFinite\n }\n \n /// True if this value is normal.\n ///\n /// A complex number is normal if it is finite and *either* the real or\n /// imaginary component is normal. A floating-point number representing\n /// one of the components is normal if its exponent allows a full-precision\n /// representation.\n ///\n /// See also ``isFinite``, ``isSubnormal`` and ``isZero``.\n @_transparent\n public var isNormal: Bool {\n isFinite && (x.isNormal || y.isNormal)\n }\n \n /// True if this value is subnormal.\n ///\n /// A complex number is subnormal if it is finite, not normal, and not zero.\n /// When the result of a computation is subnormal, underflow has occurred and\n /// the result generally does not have full precision.\n ///\n /// See also ``isFinite``, ``isNormal`` and ``isZero``.\n @_transparent\n public var isSubnormal: Bool {\n isFinite && !isNormal && !isZero\n }\n \n /// True if this value is zero.\n ///\n /// A complex number is zero if *both* the real and imaginary components\n /// are zero.\n ///\n /// See also ``isFinite``, ``isNormal`` and ``isSubnormal``.\n @_transparent\n public var isZero: Bool {\n x == 0 && y == 0\n }\n \n /// A \"canonical\" representation of the value.\n ///\n /// For normal complex numbers with a RealType conforming to\n /// BinaryFloatingPoint (the common case), the result is simply this value\n /// unmodified. For zeros, the result has the representation (+0, +0). For\n /// infinite values, the result has the representation (+inf, +0).\n ///\n /// If the RealType admits non-canonical representations, the x and y\n /// components are canonicalized in the result.\n ///\n /// This is mainly useful for interoperation with other languages, where\n /// you may want to reduce each equivalence class to a single representative\n /// before passing across language boundaries, but it may also be useful\n /// for some serialization tasks. It's also a useful implementation detail\n /// for some primitive operations.\n @_transparent\n public var canonicalized: Self {\n if isZero { return .zero }\n if isFinite { return self.multiplied(by: 1) }\n return .infinity\n }\n}\n\n// MARK: - Additional Initializers\nextension Complex {\n /// The complex number with specified real part and zero imaginary part.\n ///\n /// Equivalent to `Complex(real, 0)`.\n @inlinable\n public init(_ real: RealType) {\n self.init(real, 0)\n }\n \n /// The complex number with zero real part and specified imaginary part.\n ///\n /// Equivalent to `Complex(0, imaginary)`.\n @inlinable\n public init(imaginary: RealType) {\n self.init(0, imaginary)\n }\n}\n\nextension Complex where RealType: BinaryFloatingPoint {\n /// `other` rounded to the nearest representable value of this type.\n @inlinable\n public init<Other: BinaryFloatingPoint>(_ other: Complex<Other>) {\n self.init(RealType(other.x), RealType(other.y))\n }\n \n /// `other`, if it can be represented exactly in this type; otherwise `nil`.\n @inlinable\n public init?<Other: BinaryFloatingPoint>(exactly other: Complex<Other>) {\n guard let x = RealType(exactly: other.x),\n let y = RealType(exactly: other.y) else { return nil }\n self.init(x, y)\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Complex+Codable.swift", "content": "//===--- Complex+Codable.swift --------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nimport RealModule\n\n// FloatingPoint does not refine Codable, so this is a conditional conformance.\n#if compiler(>=6.0)\n@_unavailableInEmbedded\n#endif\nextension Complex: Decodable where RealType: Decodable {\n public init(from decoder: Decoder) throws {\n var unkeyedContainer = try decoder.unkeyedContainer()\n let x = try unkeyedContainer.decode(RealType.self)\n let y = try unkeyedContainer.decode(RealType.self)\n self.init(x, y)\n }\n}\n\n#if compiler(>=6.0)\n@_unavailableInEmbedded\n#endif\nextension Complex: Encodable where RealType: Encodable {\n public func encode(to encoder: Encoder) throws {\n var unkeyedContainer = encoder.unkeyedContainer()\n try unkeyedContainer.encode(x)\n try unkeyedContainer.encode(y)\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Complex+ElementaryFunctions.swift", "content": "//===--- Complex+ElementaryFunctions.swift --------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// Implementation goals, in order of priority:\n//\n// 1. Get the branch cuts right. We should match Kahan's /Much Ado/\n// paper for finite values.\n// 2. Have good relative accuracy in the complex norm.\n// 3. Preserve sign symmetries where possible.\n// 4. Handle the point at infinity consistently with basic operations.\n// This means diverging from what C and C++ do for non-finite inputs.\n// 5. Get good componentwise accuracy /when possible/. I don't know how\n// to do that for all of these functions off the top of my head, and\n// I don't think that other libraries have tried to do so in general,\n// so this is a research project. We should not sacrifice 1-4 for it.\n// Note that multiplication and division don't even provide good\n// componentwise relative accuracy, so it's _totally OK_ to not get\n// it for these functions too. But: it's a dynamite long-term research\n// project.\n// 6. Give the best performance we can. We should care about performance,\n// but with lower precedence than the other considerations.\n//\n// Except where derivations are given, the expressions used here are all\n// adapted from Kahan's 1986 paper \"Branch Cuts for Complex Elementary\n// Functions; or: Much Ado About Nothing's Sign Bit\".\n\nimport RealModule\n\nextension Complex: ElementaryFunctions {\n \n // MARK: - exp-like functions\n \n /// The complex exponential function e^z whose base `e` is the base of the\n /// natural logarithm.\n ///\n /// Mathematically, this operation can be expanded in terms of the `Real`\n /// operations `exp`, `cos` and `sin` as follows:\n /// ```\n /// exp(x + iy) = exp(x) exp(iy)\n /// = exp(x) cos(y) + i exp(x) sin(y)\n /// ```\n /// Note that naive evaluation of this expression in floating-point would be\n /// prone to premature overflow, since `cos` and `sin` both have magnitude\n /// less than 1 for most inputs (i.e. `exp(x)` may be infinity when\n /// `exp(x) cos(y)` would not be).\n @inlinable\n public static func exp(_ z: Complex) -> Complex {\n guard z.isFinite else { return z }\n // If x < log(greatestFiniteMagnitude), then exp(x) does not overflow.\n // To protect ourselves against sketchy log or exp implementations in\n // an unknown host library, or slight rounding disagreements between\n // the two, subtract one from the bound for a little safety margin.\n guard z.x < RealType.log(.greatestFiniteMagnitude) - 1 else {\n let halfScale = RealType.exp(z.x/2)\n let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))\n return phase.multiplied(by: halfScale).multiplied(by: halfScale)\n }\n return Complex(.cos(z.y), .sin(z.y)).multiplied(by: .exp(z.x))\n }\n \n @inlinable\n public static func expMinusOne(_ z: Complex) -> Complex {\n // exp(x + iy) - 1 = (exp(x) cos(y) - 1) + i exp(x) sin(y)\n // -------- u --------\n // Note that the imaginary part is just the usual exp(x) sin(y);\n // the only trick is computing the real part (\"u\"):\n //\n // u = exp(x) cos(y) - 1\n // = exp(x) cos(y) - cos(y) + cos(y) - 1\n // = (exp(x) - 1) cos(y) + (cos(y) - 1)\n // = expMinusOne(x) cos(y) + cosMinusOne(y)\n //\n // Note: most implementations of expm1 for complex (e.g. Julia's)\n // factor the real part as follows instead:\n //\n // exp(x) cosMinuxOne(y) + expMinusOne(x)\n //\n // The other implementation that is sometimes seen is:\n //\n // expMinusOne(z) = 2*exp(z/2)*sinh(z/2)\n //\n // All three of these implementations provide good relative error\n // bounds _in the complex norm_, but the cosineMinusOne-based\n // implementation has the best _componentwise_ error characteristics,\n // which is why we use it here:\n //\n // Implementation | Real | Imaginary |\n // ---------------+--------------------+----------------+\n // Ours | Hybrid bound | Relative bound |\n // Standard | No bound | Relative bound |\n // Half Angle | Hybrid bound | Hybrid bound |\n //\n // FUTURE WORK: devise an algorithm that achieves good _relative_ error\n // in the real component as well. Doing this efficiently is a research\n // project--exp(x) cos(y) - 1 can be very nearly zero along a curve in\n // the complex plane, not only at zero. Evaluating it accurately\n // _without_ depending on arbitrary-precision exp and cos is an\n // interesting challenge.\n guard z.isFinite else { return z }\n // If exp(z) is close to the overflow boundary, we don't need to\n // worry about the \"MinusOne\" part of this function; we're just\n // computing exp(z). (Even when z.y is near a multiple of \u03c0/2,\n // it can't be close enough to overcome the scaling from exp(z.x),\n // so the -1 term is _always_ negligable). So we simply handle\n // these cases exactly the same as exp(z).\n guard z.x < RealType.log(.greatestFiniteMagnitude) - 1 else {\n let halfScale = RealType.exp(z.x/2)\n let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))\n return phase.multiplied(by: halfScale).multiplied(by: halfScale)\n }\n // Special cases out of the way, evaluate as discussed above.\n return Complex(\n Relaxed.multiplyAdd(.cos(z.y), .expMinusOne(z.x), .cosMinusOne(z.y)),\n .exp(z.x) * .sin(z.y)\n )\n }\n \n // cosh(x + iy) = cosh(x) cos(y) + i sinh(x) sin(y).\n //\n // Like exp, cosh is entire, so we do not need to worry about where\n // branch cuts fall. Also like exp, cancellation never occurs in the\n // evaluation of the naive expression, so all we need to be careful\n // about is the behavior near the overflow boundary.\n //\n // Fortunately, if |x| >= -log(ulpOfOne), cosh(x) and sinh(x) are\n // both just exp(|x|)/2, and we already know how to compute that.\n //\n // This function and sinh should stay in sync; if you make a\n // modification here, you should almost surely make a parallel\n // modification to sinh below.\n @inlinable\n public static func cosh(_ z: Complex) -> Complex {\n guard z.isFinite else { return z }\n guard z.x.magnitude < -RealType.log(.ulpOfOne) else {\n let phase = Complex(\n RealType.cos(z.y),\n RealType(signOf: z.x, magnitudeOf: 1) * RealType.sin(z.y)\n )\n let firstScale = RealType.exp(z.x.magnitude/2)\n let secondScale = firstScale/2\n return phase.multiplied(by: firstScale).multiplied(by: secondScale)\n }\n // Future optimization opportunity: expm1 is faster than cosh/sinh\n // on most platforms, and division is now commonly pipelined, so we\n // might replace the check above with a much more conservative one,\n // and then evaluate cosh(x) and sinh(x) as\n //\n // cosh(x) = 1 + 0.5*expm1(x)*expm1(x) / (1 + expm1(x))\n // sinh(x) = expm1(x) + 0.5*expm1(x) / (1 + expm1(x))\n //\n // This won't be a _big_ win except on platforms with a crappy sinh\n // and cosh, and for those we should probably just provide our own\n // implementations of _those_, so for now let's keep it simple and\n // obviously correct.\n return Complex(\n RealType.cosh(z.x) * RealType.cos(z.y),\n RealType.sinh(z.x) * RealType.sin(z.y)\n )\n }\n \n // sinh(x + iy) = sinh(x) cos(y) + i cosh(x) sin(y)\n //\n // See cosh above for algorithm details.\n @inlinable\n public static func sinh(_ z: Complex) -> Complex {\n guard z.isFinite else { return z }\n guard z.x.magnitude < -RealType.log(.ulpOfOne) else {\n let phase = Complex(\n RealType(signOf: z.x, magnitudeOf: RealType.cos(z.y)),\n RealType.sin(z.y)\n )\n let firstScale = RealType.exp(z.x.magnitude/2)\n let secondScale = firstScale/2\n return phase.multiplied(by: firstScale).multiplied(by: secondScale)\n }\n return Complex(\n RealType.sinh(z.x) * RealType.cos(z.y),\n RealType.cosh(z.x) * RealType.sin(z.y)\n )\n }\n \n // tanh(z) = sinh(z) / cosh(z)\n @inlinable\n public static func tanh(_ z: Complex) -> Complex {\n guard z.isFinite else { return z }\n // Note that when |x| is larger than -log(.ulpOfOne),\n // sinh(x + iy) == \u00b1cosh(x + iy), so tanh(x + iy) is just \u00b11.\n guard z.x.magnitude < -RealType.log(.ulpOfOne) else {\n return Complex(\n RealType(signOf: z.x, magnitudeOf: 1),\n RealType(signOf: z.y, magnitudeOf: 0)\n )\n }\n // Now we have z in a vertical strip where exp(x) is reasonable,\n // and y is finite, so we can simply evaluate sinh(z) and cosh(z).\n //\n // TODO: Kahan uses a different expression for evaluation here; it\n // isn't strictly necessary for numerics reasons--it's to avoid\n // doing the complex division, but it probably provides better\n // componentwise error bounds, and is likely more efficient (because\n // it avoids the complex division, which is painful even when well-\n // scaled). This suffices to get us up and running.\n return sinh(z) / cosh(z)\n }\n \n // cos(z) = cosh(iz)\n @inlinable\n public static func cos(_ z: Complex) -> Complex {\n return cosh(Complex(-z.y, z.x))\n }\n \n // sin(z) = -i*sinh(iz)\n @inlinable\n public static func sin(_ z: Complex) -> Complex {\n let w = sinh(Complex(-z.y, z.x))\n return Complex(w.y, -w.x)\n }\n \n // tan(z) = -i*tanh(iz)\n @inlinable\n public static func tan(_ z: Complex) -> Complex {\n let w = tanh(Complex(-z.y, z.x))\n return Complex(w.y, -w.x)\n }\n \n // MARK: - log-like functions\n @inlinable\n public static func log(_ z: Complex) -> Complex {\n // If z is zero or infinite, the phase is undefined, so the result is\n // the single exceptional value.\n guard z.isFinite && !z.isZero else { return .infinity }\n // Having eliminated non-finite values and zero, the imaginary part is\n // easy; it's just the phase, which is always computed with good\n // relative accuracy via atan2.\n let \u03b8 = z.phase\n // The real part of the result is trickier. In exact arithmetic, the\n // real part is just log |z|--many implementations of complex functions\n // simply use this expression as is. However, there are two problems\n // lurking here:\n //\n // - length can overflow even when log(z) is finite.\n //\n // - when length is close to 1, catastrophic cancellation is hidden\n // in this expression. Consider, e.g. z = 1 + \u03b4i for small \u03b4.\n //\n // Because \u03b4 \u226a 1, |z| rounds to 1, and so log |z| produces zero.\n // We can expand using Taylor series to see that the result should\n // be:\n //\n // log |z| = log \u221a(1 + \u03b4\u00b2)\n // = log(1 + \u03b4\u00b2)/2\n // = \u03b4\u00b2/2 + O(\u03b4\u2074)\n //\n // So naively using log |z| results in a total loss of relative\n // accuracy for this case. Note that this is _not_ constrained near\n // a single point; it occurs everywhere close to the circle |z| = 1.\n //\n // Note that this case still _does_ deliver a result with acceptable\n // relative accuracy in the complex norm, because\n //\n // Im(log z) \u2248 \u03b4 \u226b \u03b4\u00b2/2 \u2248 Re(log z).\n //\n // There are a number of ways to try to tackle this problem. I'll begin\n // with a simple one that solves the first issue, and _sometimes_ the\n // second, then analyze when it doesn't work for the second case.\n //\n // To handle very large arguments without overflow, the standard\n // approach is to _rescale_ the problem. We can do this by finding\n // whichever of x and y has greater magnitude, and dividing through\n // by it. You can think of this as changing coordinates by reflections\n // so that we get a new value w = u + iv with |w| = |z| (and hence\n // Re(log w) = Re(log z), and 0 \u2264 u, 0 \u2264 v \u2264 u.\n let u = max(z.x.magnitude, z.y.magnitude)\n let v = min(z.x.magnitude, z.y.magnitude)\n // Now expand out log |w|:\n //\n // log |w| = log(u\u00b2 + v\u00b2)/2\n // = log u + log(onePlus: (v/u)\u00b2)/2\n //\n // This looks promising! It handles overflow well, because log(u) is\n // finite for every finite u, and we have 0 \u2264 v/u \u2264 1, so the second\n // term is bounded by 0 \u2264 log(1 + (v/u)\u00b2)/2 \u2264 (log 2)/2. It also\n // handles the example I gave above well: we have u = 1, v = \u03b4, and\n //\n // log(1) + log(onePlus: \u03b4\u00b2)/2 = 0 + \u03b4\u00b2/2\n //\n // as expected.\n //\n // Unfortunately, it does not handle all points close to the unit\n // circle so well; it's easy to see why if we look at the two terms\n // that contribute to the result. Cancellation occurs when the result\n // is close to zero and the terms have opposing signs. By construction,\n // the second term is always positive, so the easiest observation is\n // that cancellation is only a problem for u < 1 (because otherwise\n // log u is also positive, and there can be no cancellation).\n //\n // We are not trying for sub-ulp accuracy, just a good relative error\n // bound, so for our purposes it suffices to have log u dominate the\n // result:\n if u >= 1 || u >= Relaxed.multiplyAdd(u, u, v*v) {\n let r = v / u\n return Complex(.log(u) + .log(onePlus: r*r)/2, \u03b8)\n }\n // Here we're in the tricky case; cancellation is likely to occur.\n // Instead of the factorization used above, we will want to evaluate\n // log(onePlus: u\u00b2 + v\u00b2 - 1)/2. This all boils down to accurately\n // evaluating u\u00b2 + v\u00b2 - 1. To begin, calculate both squared terms\n // as exact head-tail products (u is guaranteed to be well scaled,\n // v may underflow, but if it does it doesn't matter, the u term is\n // all we need).\n let (a,b) = Augmented.product(u, u)\n let (c,d) = Augmented.product(v, v)\n // It would be nice if we could simply use a - 1, but unfortunately\n // we don't have a tight enough bound to guarantee that that expression\n // is exact; a may be as small as 1/4, so we could lose a single bit\n // to rounding if we did that.\n var (s,e) = Augmented.sum(large: -1, small: a)\n // Now we are ready to assemble the result. If cancellation happens,\n // then |c| > |e| > |b|, |d|, so this assembly order is safe. It's\n // also possible that |c| and |d| are small, but if that happens then\n // there is no significant cancellation, and the exact assembly doesn't\n // matter.\n s = (s + c) + e + b + d\n return Complex(.log(onePlus: s)/2, \u03b8)\n }\n \n @inlinable\n public static func log(onePlus z: Complex) -> Complex {\n // If either |x| or |y| is bounded away from the origin, we don't need\n // any extra precision, and can just literally compute log(1+z). Note\n // that this includes part of the circle |1+z| = 1 where log(onePlus:)\n // vanishes (where x <= -0.5), but on this portion of the circle 1+x\n // is always exact by Sterbenz' lemma, so as long as log( ) produces\n // a good result, log(1+z) will too.\n guard 2*z.x.magnitude < 1 && z.y.magnitude < 1 else { return log(1+z) }\n // z is in (\u00b10.5, \u00b11), so we need to evaluate more carefully.\n // The imaginary part is straightforward:\n let \u03b8 = (1+z).phase\n // For the real part, we _could_ use the same approach that we do for\n // log( ), but we'd need an extra-precise (1+x)\u00b2, which can potentially\n // be quite painful to calculate. Instead, we can use an approach that\n // NevinBR suggested on the Swift forums:\n //\n // Re(log(1+z)) = (log(1+z) + log(1+z\u0305)) / 2\n // = log((1+z)(1+z\u0305)) / 2\n // = log(1 + z + z\u0305 + zz\u0305) / 2\n // = log(1 + 2x + x\u00b2 + y\u00b2) / 2\n // = log(onePlus: (2+x)x + y\u00b2) / 2\n //\n // So now we need to evaluate (2+x)x + y\u00b2 accurately. To do this,\n // we employ augmented arithmetic; the key observation here is that\n // cancellation is only a problem when y\u00b2 \u2248 -(2+x)x\n let xp2 = Augmented.sum(large: 2, small: z.x) // Known that 2 > |x|.\n let a = Augmented.product(z.x, xp2.head)\n let y\u00b2 = Augmented.product(z.y, z.y)\n let s = (a.head + y\u00b2.head + a.tail + y\u00b2.tail).addingProduct(z.x, xp2.tail)\n return Complex(.log(onePlus: s)/2, \u03b8)\n }\n \n @inlinable\n public static func acos(_ z: Complex) -> Complex {\n Complex(\n 2*RealType.atan2(y: sqrt(1-z).real, x: sqrt(1+z).real),\n RealType.asinh((sqrt(1+z).conjugate * sqrt(1-z)).imaginary)\n )\n }\n \n @inlinable\n public static func asin(_ z: Complex) -> Complex {\n Complex(\n RealType.atan2(y: z.x, x: (sqrt(1-z) * sqrt(1+z)).real),\n RealType.asinh((sqrt(1-z).conjugate * sqrt(1+z)).imaginary)\n )\n }\n \n // atan(z) = -i*atanh(iz)\n @inlinable\n public static func atan(_ z: Complex) -> Complex {\n let w = atanh(Complex(-z.y, z.x))\n return Complex(w.y, -w.x)\n }\n \n @inlinable\n public static func acosh(_ z: Complex) -> Complex {\n Complex(\n RealType.asinh((sqrt(z-1).conjugate * sqrt(z+1)).real),\n 2*RealType.atan2(y: sqrt(z-1).imaginary, x: sqrt(z+1).real)\n )\n }\n \n // asinh(z) = -i*asin(iz)\n @inlinable\n public static func asinh(_ z: Complex) -> Complex {\n let w = asin(Complex(-z.y, z.x))\n return Complex(w.y, -w.x)\n }\n \n @inlinable\n public static func atanh(_ z: Complex) -> Complex {\n // TODO: Kahan uses a much more complicated expression here; possibly\n // simply because he didn't have a complex log(1+z) with good\n // characteristics. Investigate tradeoffs further.\n //\n // Further TODO: decide policy for point at infinity / NaN. Unlike most\n // of these functions, atanh doesn't have a pole at infinity; convention\n // in C-family languages is use one value in the upper half plane, and\n // another in the lower. Requires some thought about the most appropriate\n // way to handle this case in Swift.\n (log(onePlus: z) - log(onePlus:-z))/2\n }\n \n // MARK: - pow-like functions\n /// `exp(w*log(z))`\n ///\n /// Edge cases for this function are defined according to the defining\n /// expression exp(w log(z)), except that we define pow(0, w) to be 0\n /// instead of infinity when w is in the (strict) right half-plane, so that\n /// we agree with RealType.pow on the positive real line.\n @inlinable\n public static func pow(_ z: Complex, _ w: Complex) -> Complex {\n if z.isZero { return w.real > 0 ? zero : infinity }\n return exp(w * log(z))\n }\n \n @inlinable\n public static func pow(_ z: Complex, _ n: Int) -> Complex {\n if z.isZero { return n < 0 ? infinity : n == 0 ? one : zero }\n // TODO: this implementation is not quite correct, because n may be\n // rounded in conversion to RealType. This only effects very extreme\n // cases, so we'll leave it alone for now.\n //\n // Note that this does not have the same problems that a similar\n // implementation for a real type would have, because there's no\n // parity/sign interaction in the complex plane.\n return exp(log(z).multiplied(by: RealType(n)))\n }\n \n @inlinable\n public static func sqrt(_ z: Complex) -> Complex {\n let lengthSquared = z.lengthSquared\n if lengthSquared.isNormal {\n // If |z|^2 doesn't overflow, then define u and v by:\n //\n // u = sqrt((|z|+|x|)/2)\n // v = y/2u\n //\n // If x is positive, the result is just w = (u, v). If x is negative,\n // the result is (|v|, copysign(u, y)) instead.\n let norm = RealType.sqrt(lengthSquared)\n let u = RealType.sqrt((norm + abs(z.x))/2)\n let v: RealType = z.y / (2*u)\n if z.x.sign == .plus {\n return Complex(u, v)\n } else {\n return Complex(abs(v), RealType(signOf: z.y, magnitudeOf: u))\n }\n }\n // Handle edge cases:\n if z.isZero { return Complex(0, z.y) }\n if !z.isFinite { return z }\n // z is finite but badly-scaled. Rescale and replay by factoring out\n // the larger of x and y.\n let scale = RealType.maximum(abs(z.x), abs(z.y))\n return Complex.sqrt(z.divided(by: scale)).multiplied(by: .sqrt(scale))\n }\n \n @inlinable\n public static func root(_ z: Complex, _ n: Int) -> Complex {\n if z.isZero { return .zero }\n // TODO: this implementation is not quite correct, because n may be\n // rounded in conversion to RealType. This only effects very extreme\n // cases, so we'll leave it alone for now.\n //\n // Note that this does not have the same problems that a similar\n // implementation for a real type would have, because there's no\n // parity/sign interaction in the complex plane.\n return exp(log(z).divided(by: RealType(n)))\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Complex+Hashable.swift", "content": "//===--- Complex+Hashable.swift -------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nimport RealModule\n\nextension Complex: Hashable {\n @_transparent\n public static func ==(a: Complex, b: Complex) -> Bool {\n // Identify all numbers with either component non-finite as a single\n // \"point at infinity\".\n guard a.isFinite || b.isFinite else { return true }\n // For finite numbers, equality is defined componentwise. Cases where\n // only one of a or b is infinite fall through to here as well, but this\n // expression correctly returns false for them so we don't need to handle\n // them explicitly.\n return a.x == b.x && a.y == b.y\n }\n \n @_transparent\n public func hash(into hasher: inout Hasher) {\n // There are two equivalence classes to which we owe special attention:\n // All zeros should hash to the same value, regardless of sign, and all\n // non-finite numbers should hash to the same value, regardless of\n // representation. The correct behavior for zero falls out for free from\n // the hash behavior of floating-point, but we need to use a\n // representative member for any non-finite values.\n if isFinite {\n hasher.combine(x)\n hasher.combine(y)\n } else {\n hasher.combine(RealType.infinity)\n }\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Complex+Numeric.swift", "content": "//===--- Complex+Numeric.swift --------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nextension Complex: Numeric {\n \n @_transparent\n public static func *(z: Complex, w: Complex) -> Complex {\n return Complex(z.x*w.x - z.y*w.y, z.x*w.y + z.y*w.x)\n }\n \n @_transparent\n public static func *=(z: inout Complex, w: Complex) {\n z = z * w\n }\n \n /// The complex number with specified real part and zero imaginary part.\n ///\n /// Equivalent to `Complex(RealType(real), 0)`.\n @inlinable\n public init<Other: BinaryInteger>(_ real: Other) {\n self.init(RealType(real), 0)\n }\n \n /// The complex number with specified real part and zero imaginary part,\n /// if it can be constructed without rounding.\n @inlinable\n public init?<Other: BinaryInteger>(exactly real: Other) {\n guard let real = RealType(exactly: real) else { return nil }\n self.init(real, 0)\n }\n \n /// The infinity-norm of the value (a.k.a. \"maximum norm\" or \"\u0427\u0435\u0431\u044b\u0448\u0451\u0432\n /// [Chebyshev] norm\").\n ///\n /// Equal to `max(abs(real), abs(imaginary))`.\n ///\n /// If you need to work with the Euclidean norm (a.k.a. 2-norm) instead,\n /// use the ``length`` or ``lengthSquared`` properties. If you just need\n /// to know \"how big\" a number is, use this property.\n ///\n /// **Edge cases:**\n ///\n /// - If `z` is not finite, `z.magnitude` is infinity.\n /// - If `z` is zero, `z.magnitude` is zero.\n /// - Otherwise, `z.magnitude` is finite and non-zero.\n @_transparent\n public var magnitude: RealType {\n guard isFinite else { return .infinity }\n return max(abs(x), abs(y))\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Scale.swift", "content": "//===--- Scale.swift ------------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n// Policy: deliberately not using the * and / operators for these at the\n// moment, because then there's an ambiguity in expressions like 2*z; is\n// that Complex(2) * z or is it RealType(2) * z? This is especially\n// problematic in type inference: suppose we have:\n//\n// let a: RealType = 1\n// let b = 2*a\n//\n// what is the type of b? If we don't have a type context, it's ambiguous.\n// If we have a Complex type context, then b will be inferred to have type\n// Complex! Obviously, that doesn't help anyone.\n\nextension Complex {\n /// The result of multiplying this value by the real number `a`.\n ///\n /// Equivalent to `self * Complex(a)`, but may be computed more efficiently.\n @inlinable @inline(__always)\n public func multiplied(by a: RealType) -> Complex {\n Complex(x*a, y*a)\n }\n \n /// The result of dividing this value by the real number `a`.\n ///\n /// More efficient than `self / Complex(a)`. May not produce exactly the\n /// same result, but will always be more accurate if they differ.\n @inlinable @inline(__always)\n public func divided(by a: RealType) -> Complex {\n Complex(x/a, y/a)\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Polar.swift", "content": "//===--- Polar.swift ------------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nimport RealModule\n\nextension Complex {\n /// The Euclidean norm (a.k.a. 2-norm).\n ///\n /// This property takes care to avoid spurious over- or underflow in\n /// this computation. For example:\n ///\n /// let x: Float = 3.0e+20\n /// let x: Float = 4.0e+20\n /// let naive = sqrt(x*x + y*y) // +Inf\n /// let careful = Complex(x, y).length // 5.0e+20\n ///\n /// Note that it *is* still possible for this property to overflow,\n /// because the length can be as much as sqrt(2) times larger than\n /// either component, and thus may not be representable in the real type.\n ///\n /// For most use cases, you can use the cheaper ``magnitude``\n /// property (which computes the \u221e-norm) instead, which always produces\n /// a representable result. See <doc:Magnitude> for more details.\n ///\n /// Edge cases:\n /// - If a complex value is not finite, its `length` is `infinity`.\n ///\n /// See also ``lengthSquared``, ``phase``, ``polar``\n /// and ``init(length:phase:)``.\n @_transparent\n public var length: RealType {\n let naive = lengthSquared\n guard naive.isNormal else { return carefulLength }\n return .sqrt(naive)\n }\n \n // Internal implementation detail of ``length``, moving slow path off\n // of the inline function. Note that even `carefulLength` can overflow\n // for finite inputs, but only when the result is outside the range\n // of representable values.\n @usableFromInline\n internal var carefulLength: RealType {\n guard isFinite else { return .infinity }\n return .hypot(x, y)\n }\n \n /// The squared length `(real*real + imaginary*imaginary)`.\n ///\n /// This property is more efficient to compute than ``length``, but is\n /// highly prone to overflow or underflow; for finite values that are\n /// not well-scaled, `lengthSquared` is often either zero or\n /// infinity, even when `length` is a finite number. Use this property\n /// only when you are certain that this value is well-scaled.\n ///\n /// For many cases, ``magnitude`` can be used instead, which is similarly\n /// cheap to compute and always returns a representable value.\n ///\n /// Note that because of how `lengthSquared` is used, it is a primary\n /// design goal that it be as fast as possible. Therefore, it does not\n /// normalize infinities, and may return either `.infinity` or `.nan`\n /// for non-finite values.\n @_transparent\n public var lengthSquared: RealType {\n x*x + y*y\n }\n \n /// The phase (angle, or \"argument\").\n ///\n /// - Returns: The angle (measured above the real axis) in radians. If\n /// the complex value is zero or infinity, the phase is not defined,\n /// and `nan` is returned.\n ///\n /// See also ``length``, ``polar`` and ``init(length:phase:)``.\n @inlinable\n public var phase: RealType {\n guard isFinite && !isZero else { return .nan }\n return .atan2(y: y, x: x)\n }\n \n /// The length and phase (or polar coordinates) of this value.\n ///\n /// Edge cases:\n /// - If the complex value is zero or non-finite, phase is `.nan`.\n /// - If the complex value is non-finite, length is `.infinity`.\n ///\n /// See also: ``length``, ``phase`` and ``init(length:phase:)``.\n public var polar: (length: RealType, phase: RealType) {\n (length, phase)\n }\n \n /// Creates a complex value specified with polar coordinates.\n ///\n /// Edge cases:\n /// - Negative lengths are interpreted as reflecting the point through the\n /// origin, i.e.:\n /// ```\n /// Complex(length: -r, phase: \u03b8) == -Complex(length: r, phase: \u03b8)\n /// ```\n /// - For any `\u03b8`, even `.infinity` or `.nan`:\n /// ```\n /// Complex(length: .zero, phase: \u03b8) == .zero\n /// ```\n /// - For any `\u03b8`, even `.infinity` or `.nan`, if `r` is infinite then:\n /// ```\n /// Complex(length: r, phase: \u03b8) == .infinity\n /// ```\n /// - Otherwise, `\u03b8` must be finite, or a precondition failure occurs.\n ///\n /// See also ``length``, ``phase`` and ``polar``.\n @inlinable\n public init(length: RealType, phase: RealType) {\n if phase.isFinite {\n self = Complex(.cos(phase), .sin(phase)).multiplied(by: length)\n } else {\n precondition(\n length.isZero || length.isInfinite,\n \"Either phase must be finite, or length must be zero or infinite.\"\n )\n self = Complex(length)\n }\n }\n}"}
{"repo": "swift-numerics", "lang": "swift", "aspect": "numerics", "file": "Complex+AlgebraicField.swift", "content": "//===--- Complex+AlgebraicField.swift -------------------------*- swift -*-===//\n//\n// This source file is part of the Swift Numerics open source project\n//\n// Copyright (c) 2019-2025 Apple Inc. and the Swift Numerics project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nimport RealModule\n\nextension Complex: AlgebraicField {\n /// The multiplicative identity `1 + 0i`.\n ///\n /// See also: ``zero``, ``i``, ``infinity``\n @_transparent\n public static var one: Complex {\n Complex(1, 0)\n }\n \n /// The [complex conjugate][conj] of this value.\n ///\n /// [conj]: https://en.wikipedia.org/wiki/Complex_conjugate\n @_transparent\n public var conjugate: Complex {\n Complex(x, -y)\n }\n \n @_transparent\n public static func /=(z: inout Complex, w: Complex) {\n z = z / w\n }\n \n @_transparent\n public static func /(z: Complex, w: Complex) -> Complex {\n // Try the naive expression z/w = z * (conj(w) / |w|^2); if we can\n // compute this without over/underflow, everything is fine and the\n // result is correct. If not, we have to rescale and do the\n // computation carefully (see below).\n let lenSq = w.lengthSquared\n guard lenSq.isNormal else { return rescaledDivide(z, w) }\n return z * w.conjugate.divided(by: lenSq)\n }\n \n @usableFromInline @_alwaysEmitIntoClient @inline(never)\n internal static func rescaledDivide(_ z: Complex, _ w: Complex) -> Complex {\n if w.isZero { return .infinity }\n if !w.isFinite { return .zero }\n // Scaling algorithm adapted from Doug Priest's \"Efficient Scaling for\n // Complex Division\":\n if w.magnitude < .leastNormalMagnitude {\n // A difference from Priest's algorithm is that he didn't have to worry\n // about types like Float16, where the significand width is comparable\n // to the exponent range, such that |leastNormalMagnitude|^(-\u00be) isn't\n // representable (e.g. for Float16 it would want to be 2\u00b9\u2078, but the\n // largest allowed exponent is 15). Note that it's critical to use z\u02b9/w\u02b9\n // after rescaling to avoid this, rather than falling through into the\n // normal rescaling, because otherwise we might end up back in the\n // situation where |w| ~ 1.\n let s = 1/(RealType(RealType.radix) * .leastNormalMagnitude)\n let w\u02b9 = w.multiplied(by: s)\n let z\u02b9 = z.multiplied(by: s)\n return z\u02b9 / w\u02b9\n }\n // Having handled that case, we proceed pretty similarly to Priest:\n //\n // 1. Choose real scale s ~ |w|^(-\u00be), an exact power of the radix.\n // 2. w\u02b9 \u2190 sw\n // 3. z\u02b9 \u2190 sz\n // 4. return z\u02b9 * (w\u02b9.conjugate / w\u02b9.lengthSquared) (i.e. z\u02b9/w\u02b9).\n //\n // Why is this safe and accurate? First, observe that w\u02b9 and z\u02b9 are both\n // computed exactly because:\n //\n // - s is an exact power of radix.\n // - w\u02b9 ~ |w|^(\u00bc), and hence cannot overflow or underflow.\n // - z\u02b9 might overflow or underflow, but only if the final result also\n // overflows or underflows. (This is more subtle than I make it\n // sound. In particular, most of the fast ways one might try to\n // compute s give rise to a situation where when |w| is close to\n // one, multiplication by s is a dilation even though the actual\n // division is a contraction or vice-versa, and thus intermediate\n // computations might incorrectly overflow or underflow. Priest\n // had to take some care to avoid this situation, but we do not,\n // because we have already ruled out |w| ~ 1 before we call this\n // function.)\n //\n // Next observe that |w\u02b9.lengthSquared| ~ |w|^(\u00bd), so again this cannot\n // overflow or underflow, and neither can (w\u02b9.conjugate/w\u02b9.lengthSquared),\n // which has magnitude like |w|^(-\u00bc).\n //\n // Note that because the scale factor is always a power of the radix,\n // the rescaling does not affect rounding, and so this algorithm is scale-\n // invariant compared to the mainline `/` implementation, up to the\n // underflow boundary.\n //\n // Note that our final assembly of the result is different from Priest;\n // he applies s to w twice, instead of once to w and once to z, and\n // does the product as (zw\u0305\u02ba)*(1/|w\u02b9|\u00b2), while we do z\u02b9(w\u0305\u02b9/|w\u02b9|\u00b2). We\n // prefer our version for three reasons:\n //\n // 1. it extracts a little more ILP\n // 2. it makes it so that we get exactly the same roundings on the\n // rescaled divide path as on the fast path, so that z/w = tz/tw\n // when tz and tw are computed exactly.\n // 3. it unlocks a future optimization where we hoist s and\n // (w\u0305\u02b9/|w\u02b9|\u00b2) and make divisions all fast-path without perturbing\n // rounding.\n let s = RealType(\n sign: .plus,\n exponent: -3*w.magnitude.exponent/4,\n significand: 1\n )\n let w\u02b9 = w.multiplied(by: s)\n let z\u02b9 = z.multiplied(by: s)\n return z\u02b9 * w\u02b9.conjugate.divided(by: w\u02b9.lengthSquared)\n }\n \n /// A normalized complex number with the same phase as this value.\n ///\n /// If such a value cannot be produced (because the phase of zero and\n /// infinity is undefined), `nil` is returned.\n @inlinable\n public var normalized: Complex? {\n if length.isNormal {\n return self.divided(by: length)\n }\n if isZero || !isFinite {\n return nil\n }\n return self.divided(by: magnitude).normalized\n }\n \n /// The reciprocal of this value, if it can be computed without undue\n /// overflow or underflow.\n ///\n /// If z.reciprocal is non-nil, you can safely replace division by z with\n /// multiplication by this value. It is not advantageous to do this for an\n /// isolated division, but if you are dividing many values by a single\n /// denominator, this will often be a significant performance win.\n ///\n /// A typical use case looks something like this:\n /// ```\n /// func divide<T: Real>(data: [Complex<T>], by divisor: Complex<T>) -> [Complex<T>] {\n /// // If divisor is well-scaled, multiply by reciprocal.\n /// if let recip = divisor.reciprocal {\n /// return data.map { $0 * recip }\n /// }\n /// // Fallback on using division.\n /// return data.map { $0 / divisor }\n /// }\n /// ```\n ///\n /// Error Bounds:\n ///\n /// Unlike real types, with Complex types, _if no underflow occurs in\n /// computing the reciprocal_, replacing division with multiplication by\n /// this value does not perturb the result. Note that this condition is\n /// not the same as `reciprocal` returning a non-nil value. If the `real`\n /// and `imaginary` components are poorly scaled with respect to each other,\n /// one component of `reciprocal` may underflow while the other component\n /// is normal, resulting in a non-nil `reciprocal`.\n ///\n /// We return a non-nil reciprocal in this case because it still\n /// satisfies the accuracy expectations of `reciprocal` in any Complex\n /// norm (but not componentwise).\n @inlinable\n public var reciprocal: Complex? {\n let recip = 1/self\n if recip.isNormal || isZero || !isFinite {\n return recip\n }\n return nil\n }\n \n @_transparent\n public static func _relaxedAdd(_ a: Self, _ b: Self) -> Self {\n Complex(Relaxed.sum(a.x, b.x), Relaxed.sum(a.y, b.y))\n }\n \n @_transparent\n public static func _relaxedMul(_ a: Self, _ b: Self) -> Self {\n Complex(\n Relaxed.sum(Relaxed.product(a.x, b.x), -Relaxed.product(a.y, b.y)),\n Relaxed.sum(Relaxed.product(a.x, b.y), Relaxed.product(a.y, b.x))\n )\n }\n}"}
|