Skip to content

BUG: avoid integer arithmetic in the fv, pv and pmt powers - #174

Open
milliondreamsblog wants to merge 1 commit into
numpy:mainfrom
milliondreamsblog:fix/integer-power-overflow
Open

milliondreamsblog wants to merge 1 commit into
numpy:mainfrom
milliondreamsblog:fix/integer-power-overflow

Conversation

@milliondreamsblog

Copy link
Copy Markdown

Closes #173.

With integer rate and nper, fv, pv and pmt compute (1 + rate) ** nper with integer arithmetic. That wraps around on overflow (2**64 is 0 in int64) and raises for negative exponents:

import numpy_financial as npf

npf.fv(1, 64, 0, -2.0**-64)   # 0.0 on main, 1.0 here
npf.pv(1, 64, -1, 0)          # -inf on main, 1.0 here
npf.pmt(1, 64, 1)             # -0.0 on main, -1.0 here
npf.pv(1, -1, 0, -1)          # ValueError on main, 2.0 here

This PR evaluates the power in float64 when its base is an integer or boolean array or NumPy scalar. Float inputs are unchanged, and so are Decimal inputs and other object arrays; the existing Decimal tests still pass.

It only changes how the power is computed, so it is independent of #166 and #170, which concern the dtype of fv's output array. Until that lands, fv still truncates fractional results for integer rate, which is why the new fv test uses an example whose exact result is 1.

@AtharvRG offered to pick this up on 31 October. As the reporter, I went ahead after a week without a PR; I'm happy to close this in favour of yours if you're close.

Tests: seven new tests in TestIntegerRates cover the examples above, int32 and int64 arrays, and negative integer nper. All seven fail on main and pass here. With a native build on Python 3.13.15 and NumPy 2.5.3 (Linux), 125 tests and doctests pass (118 on main), and ruff check, mypy --no-incremental . and pyright report no issues.

With integer rate and nper, (1 + rate) ** nper was evaluated with integer
arithmetic, which wraps around on overflow and rejects negative exponents.
Evaluate integer and boolean bases in float64. Decimal and other object
inputs are unchanged.

Closes numpy#173

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.

BUG: integer power overflow in fv, pv and pmt

1 participant