Skip to content

fix(fixed_point): snap pow base near 1.0 to dodge log2 polynomial residual - #2972

Merged
zackees merged 2 commits into
masterfrom
fix/fixed-point-pow-boundary
Jun 8, 2026
Merged

zackees merged 2 commits into
masterfrom
fix/fixed-point-pow-boundary

Conversation

@zackees

@zackees zackees commented Jun 8, 2026 •

Copy link
Copy Markdown
Member

Closes #2969

Root cause

fl::fixed_point<I,F>::pow(base, exp) is implemented as exp2_fp(exp * log2_fp(base)). The log2_fp helper uses a 4-term minimax polynomial for log2(1+t) on t ∈ [0, 1). At the upper endpoint t → 1 the polynomial evaluates to ≈0.999557 instead of 1.0 — a 0.000443 residual that, after exp2 and scale-to-u16, drops the output by ~50-100 LSB below the expected value.

The existing short-circuits caught base.mValue == SCALE exactly, base.mValue <= 0, and exp.mValue == 0. But values like 255 * (1/255) in fixed-point land one ULP below 1.0 because 1/255 is not representable exactly — so the input never hit the early-out and went through the lossy polynomial path:

pow(0.99999994, 3.2) // → ~0.99902 (raw 65478) instead of 1.0 (raw 65535)

Fix

Add a near-1.0 snap before the polynomial dispatch in every pow: if base.mValue is within 2 ULPs of SCALE, return one directly. Applied uniformly across:

  • src/fl/math/fixed_point/base.h (the templated base-class pow)
  • 12 concrete specializations: s4x12, s8x8, s8x24, s12x4, s16x16, s24x8, u4x12, u8x8, u8x24, u12x4, u16x16, u24x8

Bonus cleanup

Removed the Gamma8Impl::mLut[255] = 65535 workaround that was added in #2968 to dodge this bug. The constructor now loops through [1, 256) and lets s8x24::pow produce the correct boundary value on its own. The explanatory comment block for the workaround is gone; mLut[0] = 0 is kept (slightly cheaper than a loop branch and ensures mLut is initialised).

Tests

Added 4 new FL_TEST_CASE groups in tests/fl/math/fixed_point.cpp (4 type subcases each — s16x16, s8x24, u16x16, u8x24):

  • pow boundary - exactly 1.0 — base == 1.0 still returns 1.0
  • pow boundary - one ULP below 1.0 snaps to 1.0 — the regression case
  • pow boundary - two ULPs below 1.0 snaps to 1.0 — upper edge of snap window
  • pow boundary - far from 1.0 not snapped — pow(0.5, 2) ≈ 0.25 (signed) / pow(2, 0.5) ≈ 1.414 (unsigned) confirm the snap doesn't over-trigger

Verified locally

  • bash test fl_math_fixed_point --cpp — passes (including 16 new boundary subcases)
  • bash test fl_chipsets_ucs7604 --cpp — passes (originally-failing gamma=3.2 at i=255 → 65535 case)
  • bash test fl_math_ease --cpp — passes (Gamma8Impl rewrite)
  • bash lint --cpp — clean

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved numerical precision by snapping fixed-point pow inputs very near 1.0 to exactly 1.0, avoiding tiny endpoint errors.
    • Refined gamma lookup-table generation to ensure correct endpoint handling.
  • Tests

    • Added regression tests for pow boundary behavior.
    • Updated test baseline data to reflect new measurement.

…idual (#2969)

`pow(base, exp)` is implemented as `exp2_fp(exp * log2_fp(base))`. The
`log2_fp` helper uses a 4-term minimax polynomial for `log2(1+t)` on
`t in [0, 1)`. At the upper endpoint t->1 the polynomial evaluates to
~0.999557 instead of 1.0 — a 0.000443 error that, after exp2 and
scale-to-u16, drops the output by ~50-100 LSB below expected. The
existing short-circuits caught exact-1.0 inputs only, but `255 * (1/255)`
in fixed-point lands one ULP below 1.0, exposing the bug:

  pow(0.99999994, 3.2) returned ~0.99902 (raw 65478) instead of 1.0 (raw 65535)

Fix: in every `pow` (base class plus the 12 concrete specializations
s4x12, s8x8, s8x24, s12x4, s16x16, s24x8, u4x12, u8x8, u8x24, u12x4,
u16x16, u24x8) snap `base.mValue` values within 2 ULPs of `SCALE` to
exactly-one before invoking the polynomial.

Also drops the `Gamma8Impl::mLut[255] = 65535` workaround in
`src/fl/math/ease.cpp.hpp` that was added in #2968 — the loop now runs
through `[1, 256)` because `s8x24::pow` is correct at the boundary.

Tests added in `tests/fl/math/fixed_point.cpp`:
  - pow boundary - exactly 1.0
  - pow boundary - one ULP below 1.0 snaps to 1.0
  - pow boundary - two ULPs below 1.0 snaps to 1.0
  - pow boundary - far from 1.0 not snapped
all parameterised over s16x16, s8x24, u16x16, u8x24.

Verified:
  - bash test fl_math_fixed_point --cpp      (passes, including new pow boundary cases)
  - bash test fl_chipsets_ucs7604 --cpp      (passes, gamma=3.2 boundary at i=255 -> 65535)
  - bash test fl_math_ease --cpp             (passes)
  - bash lint --cpp                          (clean)

Closes #2969
@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 925d958f-b5d9-4e98-bf0a-98fc6b9e23ff

📥 Commits

Reviewing files that changed from the base of the PR and between 9c8c786 and d5de870.

📒 Files selected for processing (2)
  • tests/data/esp32s3_bloat_baseline.txt
  • tests/fl/math/fixed_point.cpp
✅ Files skipped from review due to trivial changes (1)
  • tests/data/esp32s3_bloat_baseline.txt
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/fl/math/fixed_point.cpp

📝 Walkthrough

Walkthrough

Adds near-1.0 snap fast-paths to fixed-point pow implementations, updates Gamma8Impl to compute the final LUT entry via the fixed-point pow path instead of manual assignment, and adds regression tests plus a baseline metric update.

Changes

Fixed-point pow snap boundary handling

Layer / File(s) Summary
Base template pow normalization
src/fl/math/fixed_point/base.h
Template pow detects when base raw is within ~2 ULPs of 1.0 and returns exact one before calling exp2_fp/log2_fp.
Type-specific pow snap implementations
src/fl/math/fixed_point/s12x4.h, s16x16.h, s24x8.h, s4x12.h, s8x24.h, s8x8.h, u12x4.h, u16x16.h, u24x8.h, u4x12.h, u8x24.h, u8x8.h
All fixed-point specializations add a kOneRaw check and early-return the precomputed one for bases within the narrow near-1.0 window.
Gamma8Impl LUT refactoring
src/fl/math/ease.cpp.hpp
Only mLut[0] is set explicitly; LUT generation loop now runs to i < 256 so mLut[255] is computed via pow (uses snapped behavior).
Pow boundary regression tests & baseline
tests/fl/math/fixed_point.cpp, tests/data/esp32s3_bloat_baseline.txt
Adds tests for exact-1.0, one-ULP and two-ULP-below-1.0 snap behavior and negative checks; updates esp32s3 baseline value.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

  • #2969: Directly addresses the pow boundary handling for base ≈ 1.0 and x = 0; the PR implements the suggested snap-based fix.

Possibly related PRs

  • FastLED/FastLED#2911: Related changes to Gamma8Impl and pow behavior that interact with LUT generation and fixed-point pow semantics.

Poem

🐰 I hopped around the pow at one,
Found polynomials failing their run,
Snapped to one where ulps were few,
Gamma LUTs now end true — woo! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly and specifically describes the main fix: adding a snap mechanism for pow base values near 1.0 to avoid log2 polynomial residual errors.
Linked Issues check ✅ Passed The PR fully addresses issue #2969 by adding near-1.0 snapping across all 12 fixed_point pow specializations and removing the Gamma8Impl workaround as required.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing #2969: pow boundary handling and Gamma8Impl LUT removal; no unrelated modifications present.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/fixed-point-pow-boundary

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Infer (1.2.0)
tests/fl/math/fixed_point.cpp

tests/fl/math/fixed_point.cpp:104:10: fatal error: 'test.h' file not found
104 | #include "test.h"
| ^~~~~~~~
1 error generated.
Error: the following clang command did not run successfully:
/opt/infer-linux-x86_64-v1.2.0/lib/infer/facebook-clang-plugins/clang/install/bin/clang-18
@/tmp/coderabbit-infer/d5de870c3449abea6626e451435a8a4b86c7b0ec-a8e2680ab9cc4f3a/tmp/clang_command_.tmp.cc4414.txt
++Contents of '/tmp/coderabbit-infer/d5de870c3449abea6626e451435a8a4b86c7b0ec-a8e2680ab9cc4f3a/tmp/clang_command_.tmp.cc4414.txt':
"-cc1" "-load"
"/opt/infer-linux-x86_64-v1.2.0/lib/infer/infer/bin/../../facebook-clang-plugins/libtooling/build/FacebookClangPlugin.dylib"
"-add-plugin" "BiniouASTExporter" "-plugin-arg-BiniouASTExporter" "-"
"-plugin-arg-BiniouASTExporter" "PREPEND_CURRENT_DIR=1"
"-plugin-arg-BiniouASTExporter" "MAX_STRING_SIZE=65535" "-cc1" "-triple"
"x86_64-unknown-linux-gnu" "-emit-obj" "-mrelax-all" "-disable-free"
"-clear-as

... [truncated 1055 characters] ...

stall/lib/clang/18/include"
"-internal-isystem" "/usr/local/include" "-internal-isystem"
"/usr/lib/gcc/x86_64-linux-gnu/12/../../../../x86_64-linux-gnu/include"
"-internal-externc-isystem" "/usr/include/x86_64-linux-gnu"
"-internal-externc-isystem" "/include" "-internal-externc-isystem"
"/usr/include" "-Wno-ignored-optimization-argument" "-Wno-everything"
"-fdeprecated-macro" "-ferror-limit" "19" "-fgnuc-version=4.2.1"
"-fskip-odr-check-in-gmf" "-fcxx-exceptions" "-fexceptions"
"-D__GCC_HAVE_DWARF2_CFI_ASM=1" "-o"
"/tmp/coderabbit-infer/a8e2680ab9cc4f3a/file.o" "-x" "c++"
"tests/fl/math/fixed_point.cpp" "-O0" "-fno-builtin" "-include"
"/opt/infer-linux-x86_64-v1.2.0/lib/infer/infer/bin/../lib/clang_wrappers/global_defines.h"
"-Wno-everything"


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/fl/math/fixed_point.cpp`:
- Around line 5133-5140: The comment block around log2_fp should be converted to
7-bit ASCII: replace Unicode math glyphs (such as ∈, ≈, →, —) with ASCII
equivalents (e.g. "in", "≈" -> "approx", "->", "--" or plain punctuation) and
ensure phrases like "t ∈ [0, 1)" become "t in [0, 1)" and "t→1" becomes "t ->
1"; update the lines referencing base.mValue, exp2 + scale-to-u16, and
Gamma8Impl::mLut[255] accordingly so the semantics remain the same but only
ASCII characters are used.
- Around line 5170-5175: The test test_pow_two_ulps_below_one_impl currently
only asserts FP::pow(just_below, gamma_2_8).raw() equals one.raw(); extend this
to also assert the same for gamma_3_2 so the 2-ULP edge uses the same exponent
fanout as the 1-ULP test: locate test_pow_two_ulps_below_one_impl, compute
just_below and one as already done, and add a second FL_CHECK_EQ calling
FP::pow(just_below, gamma_3_2).raw() == one.raw() (matching the existing pattern
for gamma_2_8).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: fec64d2a-855b-4337-8586-60c2ecec8c45

📥 Commits

Reviewing files that changed from the base of the PR and between 130fee3 and 9c8c786.

📒 Files selected for processing (15)
  • src/fl/math/ease.cpp.hpp
  • src/fl/math/fixed_point/base.h
  • src/fl/math/fixed_point/s12x4.h
  • src/fl/math/fixed_point/s16x16.h
  • src/fl/math/fixed_point/s24x8.h
  • src/fl/math/fixed_point/s4x12.h
  • src/fl/math/fixed_point/s8x24.h
  • src/fl/math/fixed_point/s8x8.h
  • src/fl/math/fixed_point/u12x4.h
  • src/fl/math/fixed_point/u16x16.h
  • src/fl/math/fixed_point/u24x8.h
  • src/fl/math/fixed_point/u4x12.h
  • src/fl/math/fixed_point/u8x24.h
  • src/fl/math/fixed_point/u8x8.h
  • tests/fl/math/fixed_point.cpp

Comment thread tests/fl/math/fixed_point.cpp Resolved
Comment thread tests/fl/math/fixed_point.cpp Resolved
CodeRabbit findings on tests/fl/math/fixed_point.cpp:
- ASCII-fy non-7-bit chars in the pow boundary tests block
  (- -> --, in [0,1) instead of glyph, t -> 1, approx instead
  of ≈) so the file stays in the project's ASCII convention.
- test_pow_two_ulps_below_one_impl now also asserts the snap
  collapses pow(just_below, gamma_3_2) to one.raw(), matching
  the gamma exponent fanout already exercised by
  test_pow_one_ulp_below_one_impl.

Also bump esp32s3 bloat baseline 338247 -> 338372 (+125 B from the
snap-to-one short-circuit added across 13 fixed_point::pow specs).
The increase is one-time and intentional; the gate's job is to catch
ongoing drift.
@zackees
zackees merged commit 6f9f38d into master Jun 8, 2026
7 of 8 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 8, 2026
@zackees
zackees deleted the fix/fixed-point-pow-boundary branch June 8, 2026 02:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

fl::fixed_point::pow boundary handling: x=0 and x≈1 produce wrong results

1 participant