Skip to content

Commit

Permalink
ManagedDecimal log2 optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
andrei-marinica committed Jun 28, 2024
1 parent d19a8e9 commit 9fa6083
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
24 changes: 21 additions & 3 deletions framework/base/src/types/math_util/logarithm_i64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub type I64Decimal9 = i64;

/// Approximates the logarithm between 1 and 2 with a polynomial.
///
/// The polynomial is: `-1.7417939 + (2.8212026 + (-1.4699568 + (0.44717955 - 0.056570851 * x) * x) * x) * x`
/// The polynomial is: `-1.7417939 + x * (2.8212026 + (-1.4699568 + (0.44717955 - 0.056570851 * x) * x) * x)`
pub fn ln_polynomial(x: I64Decimal9) -> I64Decimal9 {
// x normalized to [1.0, 2.0]
debug_assert!(x >= DENOMINATOR);
Expand All @@ -32,9 +32,27 @@ pub fn ln_polynomial(x: I64Decimal9) -> I64Decimal9 {
result
}

// log2(x) = ln(x) / ln(2)
/// Just took the coeficients from ln and dividem them all by ln(2).
pub fn log2_polynomial(x: I64Decimal9) -> I64Decimal9 {
ln_polynomial(x) * DENOMINATOR / LN_OF_2_SCALE_9
// x normalized to [1.0, 2.0]
debug_assert!(x >= DENOMINATOR);
debug_assert!(x <= 2 * DENOMINATOR);

let mut result: i64 = -81614486; // -0.08161448626
result *= x;
result /= DENOMINATOR;
result += 645143719; // 0.645143719
result *= x;
result /= DENOMINATOR;
result += -2120699387; // -2.120699387
result *= x;
result /= DENOMINATOR;
result += 4070135003; // 4.070135003
result *= x;
result /= DENOMINATOR;
result += -2512877423; // -2.512877423

result
}

pub fn ln_add_bit_log2(result: &mut I64Decimal9, bit_log2: u32) {
Expand Down
7 changes: 0 additions & 7 deletions tools/plotter/src/plotter_log2_managed_decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,6 @@ pub fn draw_md_log2(
&RED,
))?;

chart.draw_series(LineSeries::new(
(0..=RANGE_MAX)
.map(|x| x as f32 * max_x / RANGE_MAX as f32)
.map(|x| (x, x.ln())),
&YELLOW,
))?;

chart.draw_series(LineSeries::new(
(0..=RANGE_MAX)
.map(|x| x as f32 * max_x / RANGE_MAX as f32)
Expand Down

0 comments on commit 9fa6083

Please sign in to comment.