diff options
author | David Cournapeau <cournape@gmail.com> | 2010-03-31 03:45:25 +0000 |
---|---|---|
committer | David Cournapeau <cournape@gmail.com> | 2010-03-31 03:45:25 +0000 |
commit | 9475b973951f322945a518f1cab62f2a4d21fbc1 (patch) | |
tree | 5d6a3f3d16dc5a3fbe7aa9f91fb3c48ba8bab17b | |
parent | 6f00924d2ca7a1faf09761a175ad3b4b1b7d0888 (diff) | |
download | numpy-9475b973951f322945a518f1cab62f2a4d21fbc1.tar.gz |
BUG: fix div by zero handling in nper.
-rw-r--r-- | numpy/lib/financial.py | 26 | ||||
-rw-r--r-- | numpy/lib/tests/test_financial.py | 2 |
2 files changed, 19 insertions, 9 deletions
diff --git a/numpy/lib/financial.py b/numpy/lib/financial.py index 8b77eb3fc..55ed2839e 100644 --- a/numpy/lib/financial.py +++ b/numpy/lib/financial.py @@ -255,15 +255,25 @@ def nper(rate, pmt, pv, fv=0, when='end'): """ when = _convert_when(when) rate, pmt, pv, fv, when = map(np.asarray, [rate, pmt, pv, fv, when]) + + use_zero_rate = False + old_err = np.seterr(divide="raise") try: - z = pmt*(1.0+rate*when)/rate - except ZeroDivisionError: - z = 0.0 - A = -(fv + pv)/(pmt+0.0) - B = np.log((-fv+z) / (pv+z))/np.log(1.0+rate) - miter = np.broadcast(rate, pmt, pv, fv, when) - zer = np.zeros(miter.shape) - return np.where(rate==zer, A+zer, B+zer) + 0.0 + try: + z = pmt*(1.0+rate*when)/rate + except FloatingPointError: + use_zero_rate = True + finally: + np.seterr(**old_err) + + if use_zero_rate: + return (-fv + pv) / (pmt + 0.0) + else: + A = -(fv + pv)/(pmt+0.0) + B = np.log((-fv+z) / (pv+z))/np.log(1.0+rate) + miter = np.broadcast(rate, pmt, pv, fv, when) + zer = np.zeros(miter.shape) + return np.where(rate==zer, A+zer, B+zer) + 0.0 def ipmt(rate, per, nper, pv, fv=0.0, when='end'): """ diff --git a/numpy/lib/tests/test_financial.py b/numpy/lib/tests/test_financial.py index c1d77c517..f3143049f 100644 --- a/numpy/lib/tests/test_financial.py +++ b/numpy/lib/tests/test_financial.py @@ -27,7 +27,7 @@ class TestFinancial(TestCase): assert_almost_equal(np.nper(0.075,-2000,0,100000.), 21.54, 2) - def test_nper(self): + def test_nper2(self): assert_almost_equal(np.nper(0.0,-2000,0,100000.), 50.0, 1) |