[Numpy-svn] r8312 - in trunk/numpy/lib: . tests

numpy-svn@scip... numpy-svn@scip...
Tue Mar 30 22:45:25 CDT 2010


Author: cdavid
Date: 2010-03-30 22:45:25 -0500 (Tue, 30 Mar 2010)
New Revision: 8312

Modified:
   trunk/numpy/lib/financial.py
   trunk/numpy/lib/tests/test_financial.py
Log:
BUG: fix div by zero handling in nper.

Modified: trunk/numpy/lib/financial.py
===================================================================
--- trunk/numpy/lib/financial.py	2010-03-31 03:45:16 UTC (rev 8311)
+++ trunk/numpy/lib/financial.py	2010-03-31 03:45:25 UTC (rev 8312)
@@ -255,16 +255,26 @@
     """
     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'):
     """
     Not implemented. Compute the payment portion for loan interest.

Modified: trunk/numpy/lib/tests/test_financial.py
===================================================================
--- trunk/numpy/lib/tests/test_financial.py	2010-03-31 03:45:16 UTC (rev 8311)
+++ trunk/numpy/lib/tests/test_financial.py	2010-03-31 03:45:25 UTC (rev 8312)
@@ -27,7 +27,7 @@
         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)
 



More information about the Numpy-svn mailing list