Skip to content

BUG: restrict rate results to values above -100% - #158

Open
lcrmorin wants to merge 1 commit into
numpy:mainfrom
lcrmorin:fix/rate-126-financial-domain
Open

lcrmorin wants to merge 1 commit into
numpy:mainfrom
lcrmorin:fix/rate-126-financial-domain

Conversation

@lcrmorin

Copy link
Copy Markdown

rate can converge to an algebraic root below -100% for the cash flows in #126. This PR restricts accepted results to r > -1: it keeps Newton for ordinary cases and adds a bracket-search/bisection fallback when Newton converges at or below -1.

For the inputs matching the reported IRR cash flows, rate(8, 263175, -440000, 25500) returns approximately 0.583878 instead of -1.855744. For the original, different inputs, the result is approximately 1.671184 instead of -1.896442.

The fallback searches around the supplied guess, uses the remaining per-element iteration budget, and checks both bracket width and a scaled equation residual. It evaluates the zero-rate residual explicitly and uses log1p/expm1 for floating-point inputs. Nonfinite guesses and guesses at or below -1 now raise ValueError.

Compatibility and scope

This intentionally excludes roots at or below -100%, which can be algebraically valid for integer periods but fall outside the positive compounding-factor model for conventional loans and annuities. Newton's intermediate steps are not constrained; this restriction applies to accepted results and the fallback search.

The change targets converged out-of-domain roots, rather than generally retrying Newton failures. Bracket discovery is heuristic: it may miss tangent roots and does not guarantee the root nearest the guess. If both search directions find brackets in the same expansion, the left bracket is selected first. The existing Newton stopping criterion is unchanged.

Validation

  • Built and installed package: 123 tests pass on Python 3.14.7 / NumPy 2.5.3.
  • Ruff, Pyright, and Mypy pass.
  • 13 added cases cover both issue reproductions with float and Decimal, independent discounted cash-flow residuals, broadcasting, mixed feasible/infeasible inputs, both payment timings, invalid guesses, and iteration limits.

Refs #126.

AI assistance was used to implement this change, run validation, and prepare this description.

This branch has not been deployed

No deployments
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