Skip to content

Commit f0b218f

Browse files
committed
ENH: Return close results in rate calculation
1 parent 100817c commit f0b218f

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed

numpy_financial/_financial.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -658,17 +658,21 @@ def rate(nper, pmt, pv, fv, when='end', guess=None, tol=None, maxiter=100):
658658
rn = guess
659659
iterator = 0
660660
close = False
661-
while (iterator < maxiter) and not close:
661+
while (iterator < maxiter) and not np.all(close):
662662
rnp1 = rn - _g_div_gp(rn, nper, pmt, pv, fv, when)
663663
diff = abs(rnp1-rn)
664-
close = np.all(diff < tol)
664+
close = diff < tol
665665
iterator += 1
666666
rn = rnp1
667-
if not close:
668-
# Return nan's in array of the same shape as rn
669-
return default_type(np.nan) + rn
670-
else:
671-
return rn
667+
668+
if not np.all(close):
669+
if np.isscalar(rn):
670+
return default_type(np.nan)
671+
else:
672+
# Return nan's in array of the same shape as rn
673+
# where the solution is not close to tol.
674+
rn[~close] = np.nan
675+
return rn
672676

673677

674678
def _roots(p):

numpy_financial/tests/test_financial.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,19 @@ def test_rate_decimal(self):
123123
Decimal('10000'))
124124
assert_equal(Decimal('0.1106908537142689284704528100'), rate)
125125

126+
def test_gh48(self):
127+
"""
128+
Test the correct result is returned with only infeasible solutions
129+
converted to nan.
130+
"""
131+
des = [-0.39920185, -0.02305873, -0.41818459, 0.26513414, numpy.nan]
132+
nper = 2
133+
pmt = 0
134+
pv = [-593.06, -4725.38, -662.05, -428.78, -13.65]
135+
fv = [214.07, 4509.97, 224.11, 686.29, -329.67]
136+
actual = npf.rate(nper, pmt, pv, fv)
137+
assert_allclose(actual, des)
138+
126139

127140
class TestNpv:
128141
def test_npv(self):

0 commit comments

Comments
 (0)