gitee.com/quant1x/num@v0.3.2/math32/ldexp.go (about)

     1  package math32
     2  
     3  // Ldexp is the inverse of Frexp.
     4  // It returns frac × 2**exp.
     5  //
     6  // Special cases are:
     7  //
     8  //	Ldexp(±0, exp) = ±0
     9  //	Ldexp(±Inf, exp) = ±Inf
    10  //	Ldexp(NaN, exp) = NaN
    11  func Ldexp(frac float32, exp int) float32 {
    12  	return ldexp(frac, exp)
    13  }
    14  
    15  func ldexp(frac float32, exp int) float32 {
    16  	// special cases
    17  	switch {
    18  	case frac == 0:
    19  		return frac // correctly return -0
    20  	case IsInf(frac, 0) || IsNaN(frac):
    21  		return frac
    22  	}
    23  	frac, e := normalize(frac)
    24  	exp += e
    25  	x := Float32bits(frac)
    26  	exp += int(x>>shift)&mask - bias
    27  	if exp < -149 {
    28  		return Copysign(0, frac) // underflow
    29  	}
    30  	if exp > 127 { // overflow
    31  		if frac < 0 {
    32  			return Inf(-1)
    33  		}
    34  		return Inf(1)
    35  	}
    36  	var m float32 = 1
    37  	if exp < -(127 - 1) { // denormal
    38  		exp += shift
    39  		m = 1.0 / (1 << 23) // 1/(2**-23)
    40  	}
    41  	x &^= mask << shift
    42  	x |= uint32(exp+bias) << shift
    43  	return m * Float32frombits(x)
    44  }