Debian Codegraph @

samplers/probability/consistent/base2.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package consistent // import "go.opentelemetry.io/contrib/samplers/probability/consistent"
5
6 import "math"
7
8 // These are IEEE 754 double-width floating point constants used with
9 // math.Float64bits.
10 const (
11 offsetExponentMask = 0x7ff0000000000000
12 offsetExponentBias = 1023
13 significandBits = 52
14 )
15
16 // expFromFloat64 returns floor(log2(x)).
17 func expFromFloat64(x float64) int {
18 biased := (math.Float64bits(x) & offsetExponentMask) >> significandBits
19 // The biased exponent can only be expressed with 11 bits (size (i.e. 64) -
20 // significant (i.e 52) - sign (i.e. 1)). Meaning the int conversion below
21 // is guaranteed to be lossless.
22 return int(biased) - offsetExponentBias
23 }
24
25 // expToFloat64 returns 2^x.
26 func expToFloat64(x int) float64 {
27 // The exponent field is an 11-bit unsigned integer from 0 to 2047, in
28 // biased form: an exponent value of 1023 represents the actual zero.
29 // Exponents range from -1022 to +1023 because exponents of -1023 (all 0s)
30 // and +1024 (all 1s) are reserved for special numbers.
31 // Therefore, the uint64 conversion below is guaranteed to be lossless.
32 const low, high = -1022, 1023
33 if x < low {
34 x = low
35 }
36 if x > high {
37 x = high
38 }
39 biased := uint64(offsetExponentBias + x)
40 return math.Float64frombits(biased << significandBits)
41 }
42
43 // splitProb returns the two values of log-adjusted-count nearest to p
44 // Example:
45 //
46 // splitProb(0.375) => (2, 1, 0.5)
47 //
48 // indicates to sample with probability (2^-2) 50% of the time
49 // and (2^-1) 50% of the time.
50 func splitProb(p float64) (uint8, uint8, float64) {
51 if p < 2e-62 {
52 // Note: spec.
53 return pZeroValue, pZeroValue, 1
54 }
55 // Take the exponent and drop the significand to locate the
56 // smaller of two powers of two.
57 exp := expFromFloat64(p)
58
59 // Low is the smaller of two log-adjusted counts, the negative
60 // of the exponent computed above.
61 low := -exp
62 // High is the greater of two log-adjusted counts (i.e., one
63 // less than low, a smaller adjusted count means a larger
64 // probability).
65 high := low - 1
66
67 // Return these to probability values and use linear
68 // interpolation to compute the required probability of
69 // choosing the low-probability Sampler.
70 lowP := expToFloat64(-low)
71 highP := expToFloat64(-high)
72 lowProb := (highP - p) / (highP - lowP)
73
74 return uint8(low), uint8(high), lowProb //nolint:gosec // Exponent can only range from -1022 to +1023.
75 }