I've added this extension to Double below to decompose a Double into integer mantissa and exponent in Swift. I've tested it for a number of values, including DBL_MAX and -DBL_MAX. My questions are: (1) Is there a built in method or function somewhere that already does this? (2) Is this correct, for all environments, with all Doubles? Is there any way it could fail? (3) Is there a way to make it more efficient but still portable?
Thanks for your advice.
extension Double {
func decomp () -> (mantissa:Int64,exponent:Int64) {
var (a,b) = frexp(self)
var exponent = Int64(b)
while floor(a) != a {
a *= 2
exponent--
}
let mantissa = Int64(floor(a))
return (mantissa, exponent)
}
}
As far as I can tell this should be easy but it doesn't work,
The FloatingPoint protocol, as defined https://github.com/apple/swift/blob/master/stdlib/public/core/FloatingPoint.swift.gyb , to which the Double struct complies already defines an exponent and a significand variable (on line 207 and 231 respectively).
And the Double struct https://github.com/apple/swift/blob/master/stdlib/public/core/FloatingPointTypes.swift.gyb , defines the exponent on line 389 and the significand on line 398.