2018-23-01 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / libgo / go / runtime / fastlog2.go
blob1f251bfaab2d59057bd0abd557c76c9b87777c9e
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.
5 package runtime
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)
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)
25 low, high := fastlog2Table[xManIndex], fastlog2Table[xManIndex+1]
26 return float64(xExp) + low + (high-low)*float64(xManScale)*fastlogScaleRatio