示例工程 02-values-variables-types
02-values-variables-types/Sources/Ch02Kit/FloatingPointTraps.swift
import Foundation
/// 二进制浮点:0.1 不能精确表示,十次相加不等于 1;比较必须给容差。
public enum FloatingPointTraps {
public static let tenth: Double = 0.1
public static let sumOfTenTenths: Double = (0..<10).reduce(0) { partial, _ in
partial + tenth
}
public static let equalsOneExactly: Bool = sumOfTenTenths == 1.0
/// NaN 与任何值都不相等,包括它自己。
public static let nanValue: Double = makeNaN()
public static let nanEqualsItself: Bool = nanValue == nanValue
/// 负零与正零相等,但 `sign` 不同。
public static let zeroValue: Double = 0.0
public static let negativeZeroValue: Double = -0.0
public static let negativeZeroEqualsZero: Bool = negativeZeroValue == zeroValue
/// 固定精度的文本表示,用于快照与正文表格。
public static func fixed(_ value: Double, digits: Int = 3) -> String {
String(format: "%.\(digits)f", value)
}
/// 带容差的相等判断:绝对误差小于 tolerance 即视为相等。
public static func approximatelyEqual(_ lhs: Double, _ rhs: Double, tolerance: Double = 1e-9)
-> Bool
{
abs(lhs - rhs) <= tolerance
}
/// Decimal 走十进制表示,适合金额;0.1 乘以 10 精确等于 1。
public static let decimalTenthTimesTenEqualsOne: Bool = {
guard let tenth = Decimal(string: "0.1") else { return false }
return tenth * 10 == Decimal(1)
}()
private static func makeNaN() -> Double {
Double.nan
}
}