blob: 96c95cad4ae11fc2ff3c573aa9730bc9992a276b [file] [log] [blame]
Charles L. Dorianc3fa32c2010-02-18 23:33:15 -08001// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package math
6
7// Ldexp is the inverse of Frexp.
Charles L. Dorian3c3e68b2010-04-09 14:37:33 -07008// It returns frac × 2**exp.
Eoghan Sherry13c2e622011-01-19 14:23:59 -05009//
10// Special cases are:
11// Ldexp(±0, exp) = ±0
12// Ldexp(±Inf, exp) = ±Inf
13// Ldexp(NaN, exp) = NaN
Charles L. Dorianc3fa32c2010-02-18 23:33:15 -080014func Ldexp(frac float64, exp int) float64 {
15 // TODO(rsc): Remove manual inlining of IsNaN, IsInf
16 // when compiler does it for us
17 // special cases
Charles L. Dorian22f84c52010-04-26 22:44:39 -070018 switch {
19 case frac == 0:
20 return frac // correctly return -0
Eoghan Sherry13c2e622011-01-19 14:23:59 -050021 case frac < -MaxFloat64 || frac > MaxFloat64 || frac != frac: // IsInf(frac, 0) || IsNaN(frac):
22 return frac
Charles L. Dorianc3fa32c2010-02-18 23:33:15 -080023 }
Eoghan Sherry13c2e622011-01-19 14:23:59 -050024 frac, e := normalize(frac)
25 exp += e
Charles L. Dorianc3fa32c2010-02-18 23:33:15 -080026 x := Float64bits(frac)
Eoghan Sherry13c2e622011-01-19 14:23:59 -050027 exp += int(x>>shift)&mask - bias
28 if exp < -1074 {
29 return Copysign(0, frac) // underflow
Charles L. Dorianc3fa32c2010-02-18 23:33:15 -080030 }
Eoghan Sherry13c2e622011-01-19 14:23:59 -050031 if exp > 1023 { // overflow
Charles L. Dorianc3fa32c2010-02-18 23:33:15 -080032 if frac < 0 {
33 return Inf(-1)
34 }
35 return Inf(1)
36 }
Eoghan Sherry13c2e622011-01-19 14:23:59 -050037 var m float64 = 1
38 if exp < -1022 { // denormal
39 exp += 52
40 m = 1.0 / (1 << 52) // 2**-52
41 }
Charles L. Dorianc3fa32c2010-02-18 23:33:15 -080042 x &^= mask << shift
Eoghan Sherry13c2e622011-01-19 14:23:59 -050043 x |= uint64(exp+bias) << shift
44 return m * Float64frombits(x)
Charles L. Dorianc3fa32c2010-02-18 23:33:15 -080045}