blob: b5d2a5e7e83b4431470c7fac10dac9a56202c916 [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
Russ Coxdd8dc6f2011-12-13 15:20:12 -050014func Ldexp(frac float64, exp int) float64
15
16func ldexp(frac float64, exp int) float64 {
Charles L. Dorianc3fa32c2010-02-18 23:33:15 -080017 // special cases
Charles L. Dorian22f84c52010-04-26 22:44:39 -070018 switch {
19 case frac == 0:
20 return frac // correctly return -0
Luuk van Dijk8dd3de42012-02-01 16:08:31 +010021 case IsInf(frac, 0) || IsNaN(frac):
Eoghan Sherry13c2e622011-01-19 14:23:59 -050022 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}