Charles L. Dorian | c3fa32c | 2010-02-18 23:33:15 -0800 | [diff] [blame] | 1 | // 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 | |
| 5 | package math |
| 6 | |
| 7 | // Ldexp is the inverse of Frexp. |
Charles L. Dorian | 3c3e68b | 2010-04-09 14:37:33 -0700 | [diff] [blame] | 8 | // It returns frac × 2**exp. |
Eoghan Sherry | 13c2e62 | 2011-01-19 14:23:59 -0500 | [diff] [blame] | 9 | // |
| 10 | // Special cases are: |
| 11 | // Ldexp(±0, exp) = ±0 |
| 12 | // Ldexp(±Inf, exp) = ±Inf |
| 13 | // Ldexp(NaN, exp) = NaN |
Russ Cox | dd8dc6f | 2011-12-13 15:20:12 -0500 | [diff] [blame] | 14 | func Ldexp(frac float64, exp int) float64 |
| 15 | |
| 16 | func ldexp(frac float64, exp int) float64 { |
Charles L. Dorian | c3fa32c | 2010-02-18 23:33:15 -0800 | [diff] [blame] | 17 | // special cases |
Charles L. Dorian | 22f84c5 | 2010-04-26 22:44:39 -0700 | [diff] [blame] | 18 | switch { |
| 19 | case frac == 0: |
| 20 | return frac // correctly return -0 |
Luuk van Dijk | 8dd3de4 | 2012-02-01 16:08:31 +0100 | [diff] [blame] | 21 | case IsInf(frac, 0) || IsNaN(frac): |
Eoghan Sherry | 13c2e62 | 2011-01-19 14:23:59 -0500 | [diff] [blame] | 22 | return frac |
Charles L. Dorian | c3fa32c | 2010-02-18 23:33:15 -0800 | [diff] [blame] | 23 | } |
Eoghan Sherry | 13c2e62 | 2011-01-19 14:23:59 -0500 | [diff] [blame] | 24 | frac, e := normalize(frac) |
| 25 | exp += e |
Charles L. Dorian | c3fa32c | 2010-02-18 23:33:15 -0800 | [diff] [blame] | 26 | x := Float64bits(frac) |
Eoghan Sherry | 13c2e62 | 2011-01-19 14:23:59 -0500 | [diff] [blame] | 27 | exp += int(x>>shift)&mask - bias |
| 28 | if exp < -1074 { |
| 29 | return Copysign(0, frac) // underflow |
Charles L. Dorian | c3fa32c | 2010-02-18 23:33:15 -0800 | [diff] [blame] | 30 | } |
Eoghan Sherry | 13c2e62 | 2011-01-19 14:23:59 -0500 | [diff] [blame] | 31 | if exp > 1023 { // overflow |
Charles L. Dorian | c3fa32c | 2010-02-18 23:33:15 -0800 | [diff] [blame] | 32 | if frac < 0 { |
| 33 | return Inf(-1) |
| 34 | } |
| 35 | return Inf(1) |
| 36 | } |
Eoghan Sherry | 13c2e62 | 2011-01-19 14:23:59 -0500 | [diff] [blame] | 37 | var m float64 = 1 |
| 38 | if exp < -1022 { // denormal |
| 39 | exp += 52 |
| 40 | m = 1.0 / (1 << 52) // 2**-52 |
| 41 | } |
Charles L. Dorian | c3fa32c | 2010-02-18 23:33:15 -0800 | [diff] [blame] | 42 | x &^= mask << shift |
Eoghan Sherry | 13c2e62 | 2011-01-19 14:23:59 -0500 | [diff] [blame] | 43 | x |= uint64(exp+bias) << shift |
| 44 | return m * Float64frombits(x) |
Charles L. Dorian | c3fa32c | 2010-02-18 23:33:15 -0800 | [diff] [blame] | 45 | } |