Skip to content

gte final rescale on div#143

Merged
thedavidmeister merged 2 commits intomainfrom
2025-09-21-div-efficient
Sep 23, 2025
Merged

gte final rescale on div#143
thedavidmeister merged 2 commits intomainfrom
2025-09-21-div-efficient

Conversation

@thedavidmeister
Copy link
Copy Markdown
Contributor

@thedavidmeister thedavidmeister commented Sep 23, 2025

Motivation

Solution

Checks

By submitting this for review, I'm confirming I've done the following:

  • made this PR as small as possible
  • unit-tested any new functionality
  • linked any relevant issues or PRs
  • included screenshots (if this involves a front-end change)

Summary by CodeRabbit

  • Bug Fixes
    • Improved decimal division accuracy in edge cases where the divisor matches the scaling threshold, preventing off-by-one scaling errors.
    • Ensures consistent exponent adjustment and digit scaling, reducing unexpected rounding anomalies at boundary inputs.
    • Results are now more predictable across affected calculations with no expected impact on performance or other functionality.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Sep 23, 2025

Walkthrough

Updates the final scaling loop condition in LibDecimalFloatImplementation.div to use a non-strict comparison (<=) instead of (<), causing an extra scaling step when signedCoefficientBAbs equals scale. No other logic changes.

Changes

Cohort / File(s) Summary
Division scaling loop tweak
src/lib/implementation/LibDecimalFloatImplementation.sol
In div’s final scaling loop, condition changed from while (signedCoefficientBAbs < scale) to while (signedCoefficientBAbs <= scale), adding one more divide-by-10 and exponent decrement when values are equal.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant C as Caller
    participant L as LibDecimalFloatImplementation.div

    C->>L: div(a, b)
    rect rgba(220,235,255,0.4)
    note right of L: Compute magnitudes and initial scale
    end

    rect rgba(235,255,220,0.4)
    note right of L: Final scaling loop condition adjusted
    L->>L: while (signedCoefficientBAbs <= scale)<br/>• divide by 10<br/>• decrement adjustExponent
    end

    L-->>C: return result
Loading

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutes

Possibly related PRs

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "gte final rescale on div" succinctly and accurately reflects the primary change in the PR: switching the final rescale check in LibDecimalFloatImplementation.div to use a greater-than-or-equal (>=) condition. It is concise, specific to the main code change, and clear enough for a teammate scanning history to understand the intent.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 2025-09-21-div-efficient

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b4326f5 and 7fc7764.

📒 Files selected for processing (1)
  • src/lib/implementation/LibDecimalFloatImplementation.sol (1 hunks)
🧰 Additional context used
🧠 Learnings (6)
📓 Common learnings
Learnt from: thedavidmeister
PR: rainlanguage/rain.math.float#130
File: src/lib/implementation/LibDecimalFloatImplementation.sol:320-330
Timestamp: 2025-09-09T15:11:31.003Z
Learning: In LibDecimalFloatImplementation.sol div function, returning zero when underflowExponentBy > 76 is intentional "non-error underflow" behavior rather than reverting. This graceful handling is the main goal of the changes.
📚 Learning: 2025-09-09T15:11:31.003Z
Learnt from: thedavidmeister
PR: rainlanguage/rain.math.float#130
File: src/lib/implementation/LibDecimalFloatImplementation.sol:320-330
Timestamp: 2025-09-09T15:11:31.003Z
Learning: In LibDecimalFloatImplementation.sol div function, returning zero when underflowExponentBy > 76 is intentional "non-error underflow" behavior rather than reverting. This graceful handling is the main goal of the changes.

Applied to files:

  • src/lib/implementation/LibDecimalFloatImplementation.sol
📚 Learning: 2025-08-21T18:03:40.347Z
Learnt from: thedavidmeister
PR: rainlanguage/rain.math.float#107
File: test/lib/LibDecimalFloatSlow.sol:37-45
Timestamp: 2025-08-21T18:03:40.347Z
Learning: In test/lib/LibDecimalFloatSlow.sol, the "slow" implementation is intentionally different from the production implementation to serve as an independent reference for fuzzing tests. The goal is to have two different approaches (expensive loops vs optimized jumps) that produce equivalent results, not identical implementations.

Applied to files:

  • src/lib/implementation/LibDecimalFloatImplementation.sol
📚 Learning: 2025-08-29T10:38:26.353Z
Learnt from: thedavidmeister
PR: rainlanguage/rain.math.float#115
File: src/lib/implementation/LibDecimalFloatImplementation.sol:593-601
Timestamp: 2025-08-29T10:38:26.353Z
Learning: The maximize function in LibDecimalFloatImplementation.sol produces exact results for simple integer values like 1. maximize(1, 0) yields exactly (1e76, -76) with no precision loss, and the log10 special case for signedCoefficient == 1e76 correctly handles this.

Applied to files:

  • src/lib/implementation/LibDecimalFloatImplementation.sol
📚 Learning: 2025-08-29T14:54:24.240Z
Learnt from: thedavidmeister
PR: rainlanguage/rain.math.float#115
File: test/src/lib/LibDecimalFloat.decimal.t.sol:122-126
Timestamp: 2025-08-29T14:54:24.240Z
Learning: In test/src/lib/LibDecimalFloat.decimal.t.sol, the fromFixedDecimalLossy function converts uint256(type(int256).max) losslessly because the boundary check is `value > uint256(type(int256).max)`, not `>=`. Values exactly equal to type(int256).max still take the lossless conversion path.

Applied to files:

  • src/lib/implementation/LibDecimalFloatImplementation.sol
📚 Learning: 2025-08-29T10:38:26.353Z
Learnt from: thedavidmeister
PR: rainlanguage/rain.math.float#115
File: src/lib/implementation/LibDecimalFloatImplementation.sol:593-601
Timestamp: 2025-08-29T10:38:26.353Z
Learning: In Solidity, int256(1) when passed through the maximize function in LibDecimalFloatImplementation.sol produces exactly (1e76, -76), not an approximation. This means the special case for signedCoefficient == 1e76 in log10 correctly handles powers of 10 like log10(1).

Applied to files:

  • src/lib/implementation/LibDecimalFloatImplementation.sol
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: rainix (ubuntu-latest, test-wasm-build)
  • GitHub Check: rainix (ubuntu-latest, rainix-sol-test)
  • GitHub Check: rainix (ubuntu-latest, rainix-rs-test)
  • GitHub Check: rainix (macos-latest, rainix-rs-test)
  • GitHub Check: rainix (macos-latest, rainix-sol-legal)
  • GitHub Check: rainix (ubuntu-latest, rainix-rs-static)
🔇 Additional comments (2)
src/lib/implementation/LibDecimalFloatImplementation.sol (2)

347-347: Critical precision correction in final scaling loop.

The change from < to <= ensures that when signedCoefficientBAbs equals scale, the loop performs one additional scaling step (dividing by 10 and decrementing adjustExponent). This addresses a precision boundary condition where values exactly matching the scale weren't being processed consistently.

The change corrects a subtle off-by-one error in the scaling logic where the boundary case (signedCoefficientBAbs == scale) was not being handled properly, which could lead to inconsistent precision in division results.


346-352: Verify division boundary: <= causes an extra scale reduction when denominator == scale
When signedCoefficientBAbs == scale the loop will run one extra iteration (scale /= 10, adjustExponent--), lowering the scale by 10 and changing final division precision at power-of-ten boundaries.

  • Check/ run these locations/tests: src/lib/implementation/LibDecimalFloatImplementation.sol (lines 346–352) and test/src/lib/implementation/LibDecimalFloatImplementation.div.t.sol, test/src/lib/implementation/LibDecimalFloatImplementation.maximize.t.sol, test/src/lib/implementation/LibDecimalFloatImplementation.characteristicMantissa.t.sol, test/src/lib/LibDecimalFloat.div.t.sol.
  • If any boundary tests fail or results change, revert to while (signedCoefficientBAbs < scale) or explicitly handle the equality case to preserve intended precision.

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

@thedavidmeister thedavidmeister merged commit b03fd6d into main Sep 23, 2025
10 checks passed
@github-actions
Copy link
Copy Markdown

@coderabbitai assess this PR size classification for the totality of the PR with the following criterias and report it in your comment:

S/M/L PR Classification Guidelines:

This guide helps classify merged pull requests by effort and complexity rather than just line count. The goal is to assess the difficulty and scope of changes after they have been completed.

Small (S)

Characteristics:

  • Simple bug fixes, typos, or minor refactoring
  • Single-purpose changes affecting 1-2 files
  • Documentation updates
  • Configuration tweaks
  • Changes that require minimal context to review

Review Effort: Would have taken 5-10 minutes

Examples:

  • Fix typo in variable name
  • Update README with new instructions
  • Adjust configuration values
  • Simple one-line bug fixes
  • Import statement cleanup

Medium (M)

Characteristics:

  • Feature additions or enhancements
  • Refactoring that touches multiple files but maintains existing behavior
  • Breaking changes with backward compatibility
  • Changes requiring some domain knowledge to review

Review Effort: Would have taken 15-30 minutes

Examples:

  • Add new feature or component
  • Refactor common utility functions
  • Update dependencies with minor breaking changes
  • Add new component with tests
  • Performance optimizations
  • More complex bug fixes

Large (L)

Characteristics:

  • Major feature implementations
  • Breaking changes or API redesigns
  • Complex refactoring across multiple modules
  • New architectural patterns or significant design changes
  • Changes requiring deep context and multiple review rounds

Review Effort: Would have taken 45+ minutes

Examples:

  • Complete new feature with frontend/backend changes
  • Protocol upgrades or breaking changes
  • Major architectural refactoring
  • Framework or technology upgrades

Additional Factors to Consider

When deciding between sizes, also consider:

  • Test coverage impact: More comprehensive test changes lean toward larger classification
  • Risk level: Changes to critical systems bump up a size category
  • Team familiarity: Novel patterns or technologies increase complexity

Notes:

  • the assessment must be for the totality of the PR, that means comparing the base branch to the last commit of the PR
  • the assessment output must be exactly one of: S, M or L (single-line comment) in format of: SIZE={S/M/L}
  • do not include any additional text, only the size classification
  • your assessment comment must not include tips or additional sections
  • do NOT tag me or anyone else on your comment

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Sep 23, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

Based on my examination of the PR changes:

This PR makes a single character change (< to <=) in one file, affecting the loop condition in a division function. While this is a mathematical logic change in a floating-point implementation, it represents:

  • A simple, single-purpose modification
  • Changes to only one file
  • A one-character fix that would require minimal context to review
  • Review effort of approximately 5-10 minutes

SIZE=S


🏁 Script executed:

#!/bin/bash
# Get the full diff for PR #143 to assess the totality of changes
gh pr diff 143

# Also check the number of files changed and lines modified
gh pr view 143 --json additions,deletions,changedFiles

Length of output: 736


SIZE=S

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant