| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package consistent |
| 5 |
|
| 6 |
import ( |
| 7 |
"testing" |
| 8 |
|
| 9 |
"github.com/stretchr/testify/require" |
| 10 |
) |
| 11 |
|
| 12 |
func TestSplitProb(t *testing.T) { |
| 13 |
require.Equal(t, -1, expFromFloat64(0.6)) |
| 14 |
require.Equal(t, -2, expFromFloat64(0.4)) |
| 15 |
require.Equal(t, 0.5, expToFloat64(-1)) |
| 16 |
require.Equal(t, 0.25, expToFloat64(-2)) |
| 17 |
|
| 18 |
for _, tc := range []struct { |
| 19 |
in float64 |
| 20 |
low uint8 |
| 21 |
lowProb float64 |
| 22 |
}{ |
| 23 |
// Probability 0.75 corresponds with choosing S=1 (the |
| 24 |
// "low" probability) 50% of the time and S=0 (the |
| 25 |
// "high" probability) 50% of the time. |
| 26 |
{0.75, 1, 0.5}, |
| 27 |
{0.6, 1, 0.8}, |
| 28 |
{0.9, 1, 0.2}, |
| 29 |
|
| 30 |
// Powers of 2 exactly |
| 31 |
{1, 0, 1}, |
| 32 |
{0.5, 1, 1}, |
| 33 |
{0.25, 2, 1}, |
| 34 |
|
| 35 |
// Smaller numbers |
| 36 |
{0.05, 5, 0.4}, |
| 37 |
{0.1, 4, 0.4}, // 0.1 == 0.4 * 1/16 + 0.6 * 1/8 |
| 38 |
{0.003, 9, 0.464}, |
| 39 |
|
| 40 |
// Special cases: |
| 41 |
{0, 63, 1}, |
| 42 |
} { |
| 43 |
low, high, lowProb := splitProb(tc.in) |
| 44 |
require.Equal(t, tc.low, low, "got %v want %v", low, tc.low) |
| 45 |
if lowProb != 1 { |
| 46 |
require.Equal(t, tc.low-1, high, "got %v want %v", high, tc.low-1) |
| 47 |
} |
| 48 |
require.InEpsilon(t, tc.lowProb, lowProb, 1e-6, "got %v want %v", lowProb, tc.lowProb) |
| 49 |
} |
| 50 |
} |