✨ Swift 中的算术魔法大修。
Package | Swift | iOS | Mac Catalyst | macOS | tvOS | watchOS |
---|---|---|---|---|---|---|
0.17.0 | 5.7 | 14.0 | 14.0 | 11.0 | 14.0 | 7.0 |
Important
此项目的开发已转移至 Ultimathnum。
事实证明,我需要 ~(~(x)) 等于所有 x 的 x。
目前,这对于任意无符号整数是不可能的。
因此,我正在研究一种允许这样做的新的抽象概念。
它统一了所有大小,并为通用代码带来了恢复机制。
此外,我正在寻找工作机会。
一个新的协议层级结构,用于改进 Swift 的标准库。
一个可组合的、大型的、固定宽度的、二补码二进制整数。
NBKDoubleWidth
是一个通用的软件模型,用于处理大于一个机器字的固定宽度整数。它的位宽是其 High
组件位宽的两倍。通过这种方式,您可以构建新的整数类型
typealias Int256 = NBKDoubleWidth< Int128>
typealias UInt256 = NBKDoubleWidth<UInt128>
与其他二进制整数一样,NBKDoubleWidth
具有二补码语义。
The two's complement representation of 0 is an infinite sequence of 0s.
The two's complement representation of -1 is an infinite sequence of 1s.
每个 NBKDoubleWidth
都有固定的位宽,其一半也是如此。这种设计带有一套溢出和位铸造操作。均匀分割也适用于分而治之的策略。
NBKDoubleWidth
模拟了一个简单的 UInt
集合,其中 UInt
是一个无符号机器字。它至少包含两个字,但确切的计数取决于平台的架构。因此,您应该使用诸如 startIndex
和 endIndex
之类的属性,而不是硬编码的索引。
// Int256 and UInt256, as constructed on a 64-bit platform:
┌───────────────────────────┐ ┌───────────────────────────┐
│ Int256 │ │ UInt256 │
├─────────────┬─────────────┤ ├─────────────┬─────────────┤
│ Int128 │ UInt128 │ │ UInt128 │ UInt128 │
├──────┬──────┼──────┬──────┤ ├──────┬──────┼──────┬──────┤
│ Int │ UInt │ UInt │ UInt │ │ UInt │ UInt │ UInt │ UInt │
└──────┴──────┴──────┴──────┘ └──────┴──────┴──────┴──────┘
Swift 的类型系统强制执行正确的布局,因为 Int
和 UInt
是标准库中唯一满足其类型要求的类型。具体来说,只有 Int
和 UInt
具有 NBKCoreInteger<UInt>
Digit
类型。
除了其普通的算术魔法运算外,NBKDoubleWidth
还提供单位数运算,其中数字是无/有符号机器字。这些操作对于小型计算更有效。以下是一些示例
Int256(1) + Int(1), UInt256(1) + UInt(1)
Int256(2) - Int(2), UInt256(2) - UInt(2)
Int256(3) * Int(3), UInt256(3) * UInt(3)
Int256(4) / Int(4), UInt256(4) / UInt(4)
Int256(5) % Int(5), UInt256(5) % UInt(5)
Important
它正在开发中。我可能会随时修改它。
NBKFibonacciXL(0) // (index: 0, element: 0, next: 1)
NBKFibonacciXL(1) // (index: 1, element: 1, next: 1)
NBKFibonacciXL(2) // (index: 2, element: 1, next: 2)
NBKFibonacciXL(3) // (index: 3, element: 2, next: 3)
NBKFibonacciXL(4) // (index: 4, element: 3, next: 5)
NBKFibonacciXL(5) // (index: 5, element: 5, next: 8)
它使用快速的倍增和加法算法
NBKFibonacciXL(10_000_000) // 2.3s on MacBook Pro, 13-inch, M1, 2020
但是您也可以手动逐步执行它
mutating func increment() { ... } // index + 1
mutating func decrement() { ... } // index - 1
mutating func double() { ... } // index * 2
Numberick 包含多个模块。导入部分或全部模块。
主版本零 (0.y.z) 用于初始开发。
任何内容都可能随时更改。
公共 API 不应被视为稳定。
将此软件包添加到您的软件包依赖项列表中。
.package(url: "https://github.com/oscbyspro/Numberick.git", .upToNextMinor(from: "0.17.0")),
从 Package.swift 中的产品中选择目标依赖项。
.product(name: "Numberick", package: "Numberick"),
.product(name: "NBKCoreKit", package: "Numberick"),
.product(name: "NBKDoubleWidthKit", package: "Numberick"),
.product(name: "NBKFlexibleWidthKit", package: "Numberick"),
从根目录中列出的 pods 中选择目标依赖项。
pod "Numberick", "~> 0.17.0"
pod "Numberick-NBKCoreKit", "~> 0.17.0"
pod "Numberick-NBKDoubleWidthKit", "~> 0.17.0"
此项目灵感来源于 Apple 的 Int128 和 DoubleWidth。