Swift 编程语言的近似浮点相等比较
近似
Swift 编程语言的近似浮点相等比较。
介绍
Approxed 是一个 Swift 包,它提供了浮点比较的实现 对于 Swift 生态系统。比较两个浮动通常不正确的行为 使用精确相等比较的相等或不相等的点数,由于 浮点运算的不精确性。取而代之的是使用近似值 而是比较。浮点数是违反直觉的生物,所以需要 以不同于整数的方式处理它们。
用法
若要在项目中使用“近似值”,请将以下行添加到依赖项 在 Swift 包清单中列出
dependencies: [
.package(url: "https://github.com/lambdaxymox/Approximate", .branch("master")),
]
以及以下行到您期望的每个目标
.product(name: "Approximate", package: "Approximate")
例如,您的 Swift 包清单可能如下所示
// swift-tools-version:5.6
import PackageDescription
let package = Package(
name: "my-app",
dependencies: [
.package(url: "https://github.com/lambdaxymox/Approximate", from: "1.0.1"),
],
targets: [
.target(name: "my-app", dependencies: [
.product(name: "Approximate", package: "Approximate"),
]),
]
)
最后导入库
import Approximate
并在您的项目中使用它。
Features
This library provides the three standard forms of approximate equality comparisons for floating point numbers in Swift. These are absolute difference equality, units in last place (ULPS) equality, and relative equality.
References
Some references going in depth about comparing floating point numbers and their tricky subtleties.
- Comparing Floating Point Numbers, 2012 Edition
- The Floating-Point Guide
- What Every Computer Scientist Should Know About Floating-Point Arithmetic