Source file src/math/ldexp.go

     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.
     8  // It returns frac × 2**exp.
     9  //
    10  // Special cases are:
    11  //	Ldexp(±0, exp) = ±0
    12  //	Ldexp(±Inf, exp) = ±Inf
    13  //	Ldexp(NaN, exp) = NaN
    14  func Ldexp(frac float64, exp int) float64 {
    15  	if haveArchLdexp {
    16  		return archLdexp(frac, exp)
    17  	}
    18  	return ldexp(frac, exp)
    19  }
    20  
    21  func ldexp(frac float64, exp int) float64 {
    22  	// special cases
    23  	switch {
    24  	case frac == 0:
    25  		return frac // correctly return -0
    26  	case IsInf(frac, 0) || IsNaN(frac):
    27  		return frac
    28  	}
    29  	frac, e := normalize(frac)
    30  	exp += e
    31  	x := Float64bits(frac)
    32  	exp += int(x>>shift)&mask - bias
    33  	if exp < -1075 {
    34  		return Copysign(0, frac) // underflow
    35  	}
    36  	if exp > 1023 { // overflow
    37  		if frac < 0 {
    38  			return Inf(-1)
    39  		}
    40  		return Inf(1)
    41  	}
    42  	var m float64 = 1
    43  	if exp < -1022 { // denormal
    44  		exp += 53
    45  		m = 1.0 / (1 << 53) // 2**-53
    46  	}
    47  	x &^= mask << shift
    48  	x |= uint64(exp+bias) << shift
    49  	return m * Float64frombits(x)
    50  }
    51  

View as plain text