Swift 4.2 MIT LiCENSE build status

已过时,请使用 Swift Numerics

现在我们已经有了 apple/swift-numerics 官方版本,你应该切换到 NumericsRealModuleElementaryFunctions 协议。

swift-floatingpointmath

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 时,DoubleFloat 将成为 FloatingPointMath

Foundation (或 GlibcDarwin) 不同,此模块

遵循 FloatingPointMath

快速简便的方法

如果该类型已经遵循 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 相当。 对于更精确的浮点类型(例如,Float128BigFloat),您应该实现自己的版本。

用法

将以下内容添加到您的项目的 Package.swift 文件中。