Skip to content

Commit 57fd4c1

Browse files
mandeep-singh-sndkKai-Striega
authored andcommitted
BUG: Return decimal NaNs instead of TypeError
In case of infeasible/invalid problems npf.rate is supposed to return nan. In cases where the required output is of type Decimal a TypeError is raised instead as Decimal types do not support arithmatic with floating point values. This PR uses a Decimal nan as required for the error handling, returning a nan as expected. See #14645
1 parent 8709c4f commit 57fd4c1

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

numpy_financial/_financial.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -624,7 +624,7 @@ def rate(nper, pmt, pv, fv, when='end', guess=None, tol=None, maxiter=100):
624624
rn = rnp1
625625
if not close:
626626
# Return nan's in array of the same shape as rn
627-
return np.nan + rn
627+
return default_type(np.nan) + rn
628628
else:
629629
return rn
630630

numpy_financial/tests/test_financial.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
)
1010

1111
import numpy_financial as npf
12+
import pytest
1213

1314

1415
class TestFinancial(object):
@@ -410,3 +411,30 @@ def test_broadcast_decimal(self):
410411
[Decimal('-74.998201'), Decimal('-75.62318601'),
411412
Decimal('-75.62318601'), Decimal('-76.88882405'),
412413
Decimal('-76.88882405')], 4)
414+
415+
@pytest.mark.parametrize('number_type', [Decimal, float])
416+
def test_rate_nan(self, number_type):
417+
"""
418+
Test for checking inputs whose output is NaN
419+
Rate will return NaN, if newton raphson method's change or diff was not able to become
420+
less than default tolerance value i.e. 1e-6 in max iterations possible,
421+
Both payments and present value are positive, it is impossible to pay off the existing balance
422+
by making further withdrawals, regardless of the rate.
423+
"""
424+
rate = npf.rate(number_type(12.0), number_type('400.0'), number_type('10000.0'), number_type(0))
425+
assert_equal(numpy.nan, float(rate))
426+
rate = npf.rate(number_type(12.0), number_type('400.0'), number_type('10000.0'), number_type(5000))
427+
assert_equal(numpy.nan, float(rate))
428+
429+
# begin
430+
rate = npf.rate(number_type(12.0), number_type('400.0'), number_type('10000.0'), number_type(20000), 1)
431+
assert_equal(numpy.nan, float(rate))
432+
rate = npf.rate(number_type(12.0), number_type('400.0'), number_type('10000.0'), number_type(20000), 'begin')
433+
assert_equal(numpy.nan, float(rate))
434+
435+
# end
436+
rate = npf.rate(number_type(12.0), number_type('400.0'), number_type('10000.0'), number_type(0))
437+
assert_equal(numpy.nan, float(rate))
438+
rate = npf.rate(number_type(12.0), number_type('400.0'), number_type('10000.0'), number_type(0), 'end')
439+
assert_equal(numpy.nan, float(rate))
440+

0 commit comments

Comments
 (0)