现在我们已经有了 apple/swift-numerics 官方版本,你应该切换到 Numerics
的 RealModule
的 ElementaryFunctions
协议。
Swift 的面向协议的数学函数
此模块提供了一个协议 FloatingPointMath
。遵循该协议的类型**必须**实现:
public protocol FloatingPointMath {
init (_:Double) // BinaryFloatingPoint already has one
var asDouble:Double { get } // you have to add it yourself
}
并且**应该**实现(虽然提供了默认实现):
static func acos (_ x:Self)->Self
static func acosh(_ x:Self)->Self
static func asin (_ x:Self)->Self
static func asinh(_ x:Self)->Self
static func atan (_ x:Self)->Self
static func atanh(_ x:Self)->Self
static func cbrt (_ x:Self)->Self
static func cos (_ x:Self)->Self
static func cosh (_ x:Self)->Self
static func exp (_ x:Self)->Self
static func exp2 (_ x:Self)->Self
static func expm1(_ x:Self)->Self
static func log (_ x:Self)->Self
static func log2 (_ x:Self)->Self
static func log10(_ x:Self)->Self
static func log1p(_ x:Self)->Self
static func sin (_ x:Self)->Self
static func sinh (_ x:Self)->Self
static func sqrt (_ x:Self)->Self
static func tan (_ x:Self)->Self
static func tanh (_ x:Self)->Self
static func atan2(_ y:Self, _ x:Self)->Self
static func hypot(_ x:Self, _ y:Self)->Self
static func pow (_ x:Self, _ y:Self)->Self
static func erf (_ x:Self)->Self
static func erfc (_ x:Self)->Self
static func lgamma(_ x:Self)->Self
static func tgamma(_ x:Self)->Self
简而言之,遵循该协议的类型保证拥有数学函数作为 (static|class) 方法。 为了方便起见,当您 import
时,Double
和 Float
将成为 FloatingPointMath
。
与 Foundation
(或 Glibc
或 Darwin
) 不同,此模块
libm
中的数学函数。import Foundation
atan2(0.0, -1.0) == M_PI // imported in the global namespace with lots of other symbols
import FloatingPointMath
Double.atan2(0.0, -1.0) == Double.pi // explicitly under `Double`.
如果该类型已经遵循 BinaryFloatingPoint
,您只需添加 .asDouble
,如下所示:
extension CGFloat : FloatingPointMath {
public var asDouble:Double { return Double(self) }
}
默认实现只是转换为 Double,进行计算,然后将结果转换回来,如下所示。
public static func acos (_ x:Self)->Self {
return Self(Darwin.acos (x.asDouble))
}
所以结果的精度仅与 Double
相当。 对于更精确的浮点类型(例如,Float128
或 BigFloat
),您应该实现自己的版本。
将以下内容添加到您的项目的 Package.swift
文件中。
dependencies
.package(url: "https://github.com/dankogai/swift-floatingpointmath.git", from: "0.0.7")
.target
在 targets:
中
dependencies:["FloatingPointMath"]