Swift 5 MIT LiCENSE CI via GitHub Actions

swift-bignum

Swift 中用于 Swift 的任意精度算术运算

概要

import BigNum
BigRat.sqrt(2, precision:128)  // 240615969168004511545033772477625056927/170141183460469231731687303715884105728
BigFloat.exp(1, precision:128) // 2.718281828459045235360287471352662497759

描述

此模块提供两种符合 FloatingPoint 协议的任意精度类型。

除了 FloatingPoint 支持的所有算术运算之外,<math.h> 中的大多数函数都作为静态函数提供。 如您在上面的概要中看到的,所有有损的算术函数和运算符都可以将 precision:Int 作为可选参数。 如果省略,则使用 BigRat.precisionBigFloat.precision 的值(默认值:64)。

BigFloat.sqrt(2) // 1.41421356237309504876
BigFloat.precision = 128
BigFloat.sqrt(2) // 1.414213562373095048801688724209698078569

BigInt 是一种任意精度整数类型,在内部使用并重新导出,因此您不必仅仅为了它而 import BigIntBigInt 也扩展了 .over() 方法,因此您可以不用直接构造 BigRat,而是使用 .over() 方法。

BigInt(3260954456333195553).over(BigInt(2305843009213693952)) // == BigRat.sqrt(2)

用法

构建

$ git clone https://github.com/dankogai/swift-bignum.git
$ cd swift-bignum # the following assumes your $PWD is here
$ swift build

REPL

简单地

$ scripts/run-repl.sh

$ swift run --repl

在您的 REPL 中,

[0/0] Build complete!
Launching Swift REPL with arguments: -I/Users/dankogai/github/swift-bignum/.build/x86_64-apple-macosx/release -L/Users/dankogai/github/swift-bignum/.build/x86_64-apple-macosx/release -lBigNum__REPL -I/Users/dankogai/github/swift-bignum/.build/checkouts/swift-numerics/Sources/_NumericsShims/include
Welcome to Swift version 5.5.2-dev.
Type :help for assistance.
  1> import BigNum 
  2> var bf = BigFloat.sqrt(2, precision:128)
bf: BigNum.BigFloat = {
  scale = -127
  mantissa = {
    magnitude = {
      kind = array
      storage = 2 values {
        [0] = 6448461645324402335
        [1] = 13043817825332782212
      }
    }
    sign = plus
  }
}
  3> print(bf)
1.414213562373095048801688724209698078569

从您的 Xcode 项目中。

只需从项目的 Package Dependencies 选项卡中添加软件包。 在搜索字段中输入 https://github.com/dankogai/swift-bignum 并单击 [Add Package]

现在您可以 import BigNum 了。

现在您要做的就是构建并享受它!

如果您遇到类似 Missing required module '_NumericShims' 的错误,请尝试清理您的 ~/Library/Developer/Xcode/DerivedData

从您的 SwiftPM 管理的项目中

将以下内容添加到 dependencies 部分

.package(
  url: "https://github.com/dankogai/swift-bignum.git", .branch("main")
)

并将以下内容添加到 .target 参数

.target(
  name: "YourSwiftyPackage",
  dependencies: ["BigNum"])

现在您要做的就是

import BigNum

在您的代码中。 尽情享用!

先决条件

Swift 5 或更高版本,OS X 或 Linux 用于构建。