fix: use log-space computation in geometric_mean to prevent float underflow#347
Open
Grizouforever wants to merge 1 commit intoAffineFoundation:mainfrom
Open
Conversation
…erflow When geometric_mean receives many small positive values (e.g. 1e-200), iterative multiplication underflows to 0.0 in IEEE 754, producing an incorrect result. Replace the product loop with a log-space computation (sum of logs divided by n, then exp) which is numerically stable across the full range of positive floats. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
geometric_meanreturned0.0incorrectly when iterative multiplication of many small positive values underflowed in IEEE 754exp((1/n) * Σ log(vᵢ))0.0, empty list returns0.0, the smoothed-epsilon path is unchangedRoot Cause
IEEE 754 doubles underflow to
0.0when the running product drops below ~5e-324. With 1000 values of1e-200, the true product is1e-200000, which is far below that floor.Fix
Test plan
geometric_mean([2.0, 8.0])still returns4.0geometric_mean([1e-200] * 1000)returns~1e-200instead of0.0geometric_mean([0.5, 0.0, 0.5])still returns0.0geometric_mean([])still returns0.0tests/are unrelated to this module)🤖 Generated with Claude Code