Now that we have apple/swift-numericsofficially, you should switch to ElementaryFunctions protocol of RealModule of Numerics.
swift-floatingpointmath
Protocol-Oriented Math Functions for Swift
Description
This module provides a protocol FloatingPointMath. Conforming protocols MUST implemnt:
public protocol FloatingPointMath {
init (_:Double) // BinaryFloatingPoint already has one
var asDouble:Double { get } // you have to add it yourself
}
And SHOULD implement (though default implementations are provided):
In short, conforming types are guaranteed to have math functions as (static|class) methods. For convenience, Double and Float are made FloatingPointMath when you import.
Unlike Foundation (or Glibc or Darwin), this module:
does nothing further. Just math functions found in libm.
imports these functions as (static|class) methods to avoid namespace collision.
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`.
Conforming to FloatingPointMath
Quick and Dirty Way
If the type already conform to BinaryFloatingPoint, all you have to do is add .asDouble as follows:
extension CGFloat : FloatingPointMath {
public var asDouble:Double { return Double(self) }
}
Hard but Right Way
Default implementations just convert to Double, do the calculation and convert the result back like the following.
OBSOLETED by Swift Numerics
Now that we have apple/swift-numerics officially, you should switch to
ElementaryFunctionsprotocol ofRealModuleofNumerics.swift-floatingpointmath
Protocol-Oriented Math Functions for Swift
Description
This module provides a protocol
FloatingPointMath. Conforming protocols MUST implemnt:And SHOULD implement (though default implementations are provided):
In short, conforming types are guaranteed to have math functions as (static|class) methods. For convenience,
DoubleandFloatare madeFloatingPointMathwhen youimport.Unlike
Foundation(orGlibcorDarwin), this module:libm.Conforming to
FloatingPointMathQuick and Dirty Way
If the type already conform to
BinaryFloatingPoint, all you have to do is add.asDoubleas follows:Hard but Right Way
Default implementations just convert to Double, do the calculation and convert the result back like the following.
So the result is only as accurate as
Double. For more accurate floating-point types (say,Float128orBigFloat), you should implement your own.Usage
Add the following to the
Package.swiftfile of your project.dependencies:.targetintargets: