Source file src/runtime/fastlog2.go

     1  // Copyright 2015 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 runtime
     6  
     7  // fastlog2 implements a fast approximation to the base 2 log of a
     8  // float64. This is used to compute a geometric distribution for heap
     9  // sampling, without introducing dependencies into package math. This
    10  // uses a very rough approximation using the float64 exponent and the
    11  // first 25 bits of the mantissa. The top 5 bits of the mantissa are
    12  // used to load limits from a table of constants and the rest are used
    13  // to scale linearly between them.
    14  func fastlog2(x float64) float64 {
    15  	const fastlogScaleBits = 20
    16  	const fastlogScaleRatio = 1.0 / (1 << fastlogScaleBits)
    17  
    18  	xBits := float64bits(x)
    19  	// Extract the exponent from the IEEE float64, and index a constant
    20  	// table with the first 10 bits from the mantissa.
    21  	xExp := int64((xBits>>52)&0x7FF) - 1023
    22  	xManIndex := (xBits >> (52 - fastlogNumBits)) % (1 << fastlogNumBits)
    23  	xManScale := (xBits >> (52 - fastlogNumBits - fastlogScaleBits)) % (1 << fastlogScaleBits)
    24  
    25  	low, high := fastlog2Table[xManIndex], fastlog2Table[xManIndex+1]
    26  	return float64(xExp) + low + (high-low)*float64(xManScale)*fastlogScaleRatio
    27  }
    28  

View as plain text