def test_errcall(self): def foo(*args): print(args) olderrcall = np.geterrcall() with np.errstate(call=foo): assert_(np.geterrcall() is foo, 'call is not foo') with np.errstate(call=None): assert_(np.geterrcall() is None, 'call is not None') assert_(np.geterrcall() is olderrcall, 'call is not olderrcall')
def test_invalid(self): with np.errstate(all='raise', under='ignore'): a = -np.arange(3) # This should work with np.errstate(invalid='ignore'): np.sqrt(a) # While this should fail! try: np.sqrt(a) except FloatingPointError: pass else: self.fail("Did not raise an invalid error")
def test_divide(self): with np.errstate(all='raise', under='ignore'): a = -np.arange(3) # This should work with np.errstate(divide='ignore'): a // 0 # While this should fail! try: a // 0 except FloatingPointError: pass else: self.fail("Did not raise divide by zero error")
def test_complex_bad2(self): with np.errstate(divide='ignore', invalid='ignore'): v = 1 + 1j v += np.array(-1 + 1.j) / 0. vals = nan_to_num(v) assert_all(np.isfinite(vals)) assert_equal(type(vals), np.complex_)
def test_testUfuncs1(self): # Test various functions such as sin, cos. (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d assert_(eq(np.cos(x), cos(xm))) assert_(eq(np.cosh(x), cosh(xm))) assert_(eq(np.sin(x), sin(xm))) assert_(eq(np.sinh(x), sinh(xm))) assert_(eq(np.tan(x), tan(xm))) assert_(eq(np.tanh(x), tanh(xm))) with np.errstate(divide='ignore', invalid='ignore'): assert_(eq(np.sqrt(abs(x)), sqrt(xm))) assert_(eq(np.log(abs(x)), log(xm))) assert_(eq(np.log10(abs(x)), log10(xm))) assert_(eq(np.exp(x), exp(xm))) assert_(eq(np.arcsin(z), arcsin(zm))) assert_(eq(np.arccos(z), arccos(zm))) assert_(eq(np.arctan(z), arctan(zm))) assert_(eq(np.arctan2(x, y), arctan2(xm, ym))) assert_(eq(np.absolute(x), absolute(xm))) assert_(eq(np.equal(x, y), equal(xm, ym))) assert_(eq(np.not_equal(x, y), not_equal(xm, ym))) assert_(eq(np.less(x, y), less(xm, ym))) assert_(eq(np.greater(x, y), greater(xm, ym))) assert_(eq(np.less_equal(x, y), less_equal(xm, ym))) assert_(eq(np.greater_equal(x, y), greater_equal(xm, ym))) assert_(eq(np.conjugate(x), conjugate(xm))) assert_(eq(np.concatenate((x, y)), concatenate((xm, ym)))) assert_(eq(np.concatenate((x, y)), concatenate((x, y)))) assert_(eq(np.concatenate((x, y)), concatenate((xm, y)))) assert_(eq(np.concatenate((x, y, x)), concatenate((x, ym, x))))
def _check_ninf_nan(dummy): msgform = "csqrt(-inf, nan) is (%f, %f), expected (nan, +-inf)" z = np.sqrt(np.array(complex(-np.inf, np.nan))) #Fixme: ugly workaround for isinf bug. with np.errstate(invalid='ignore'): if not (np.isnan(z.real) and np.isinf(z.imag)): raise AssertionError(msgform % (z.real, z.imag))
def test_nans_infs(self): with np.errstate(all='ignore'): # Check some of the ufuncs assert_equal(np.isnan(self.all_f16), np.isnan(self.all_f32)) assert_equal(np.isinf(self.all_f16), np.isinf(self.all_f32)) assert_equal(np.isfinite(self.all_f16), np.isfinite(self.all_f32)) assert_equal(np.signbit(self.all_f16), np.signbit(self.all_f32)) assert_equal(np.spacing(float16(65504)), np.inf) # Check comparisons of all values with NaN nan = float16(np.nan) assert_(not (self.all_f16 == nan).any()) assert_(not (nan == self.all_f16).any()) assert_((self.all_f16 != nan).all()) assert_((nan != self.all_f16).all()) assert_(not (self.all_f16 < nan).any()) assert_(not (nan < self.all_f16).any()) assert_(not (self.all_f16 <= nan).any()) assert_(not (nan <= self.all_f16).any()) assert_(not (self.all_f16 > nan).any()) assert_(not (nan > self.all_f16).any()) assert_(not (self.all_f16 >= nan).any()) assert_(not (nan >= self.all_f16).any())
def test_branches(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = list() # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by else condition as neither are == 0 data.append(((2.0, 1.0), (2.0, 1.0), (1.0, 0.0))) # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by if condition as both are == 0 # is performed in test_zero_division(), so this is skipped # trigger else if branch: real(fabs(denom)) < imag(fabs(denom)) data.append(((1.0, 2.0), (1.0, 2.0), (1.0, 0.0))) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1])
def test_complex_bad(self): with np.errstate(divide='ignore', invalid='ignore'): v = 1 + 1j v += np.array(0 + 1.j) / 0. vals = nan_to_num(v) # !! This is actually (unexpectedly) zero assert_all(np.isfinite(vals)) assert_equal(type(vals), np.complex_)
def check_complex_value(f, x1, y1, x2, y2, exact=True): z1 = np.array([complex(x1, y1)]) z2 = complex(x2, y2) with np.errstate(invalid='ignore'): if exact: assert_equal(f(z1), z2) else: assert_almost_equal(f(z1), z2)
def test_generic(self): with np.errstate(divide='ignore', invalid='ignore'): vals = nan_to_num(np.array((-1., 0, 1)) / 0.) assert_all(vals[0] < -1e10) and assert_all(np.isfinite(vals[0])) assert_(vals[1] == 0) assert_all(vals[2] > 1e10) and assert_all(np.isfinite(vals[2])) assert_equal(type(vals), np.ndarray) # perform the same test but in-place with np.errstate(divide='ignore', invalid='ignore'): vals = np.array((-1., 0, 1)) / 0. result = nan_to_num(vals, copy=False) assert_(result is vals) assert_all(vals[0] < -1e10) and assert_all(np.isfinite(vals[0])) assert_(vals[1] == 0) assert_all(vals[2] > 1e10) and assert_all(np.isfinite(vals[2])) assert_equal(type(vals), np.ndarray)
def test_underlow(self): # Regression test for #759: # instantiating MachAr for dtype = np.float96 raises spurious warning. with errstate(all='raise'): try: self._run_machar_highprec() except FloatingPointError as e: msg = "Caught %s exception, should not have been raised." % e raise AssertionError(msg)
def test_inf_edges(self): # Test using +/-inf bin edges works. See #1788. with np.errstate(invalid='ignore'): x = np.arange(6).reshape(3, 2) expected = np.array([[1, 0], [0, 1], [0, 1]]) h, e = np.histogramdd(x, bins=[3, [-np.inf, 2, 10]]) assert_allclose(h, expected) h, e = np.histogramdd(x, bins=[3, np.array([-1, 2, np.inf])]) assert_allclose(h, expected) h, e = np.histogramdd(x, bins=[3, [-np.inf, 3, np.inf]]) assert_allclose(h, expected)
def test_testScalarArithmetic(self): xm = array(0, mask=1) #TODO FIXME: Find out what the following raises a warning in r8247 with np.errstate(divide='ignore'): assert_((1 / array(0)).mask) assert_((1 + xm).mask) assert_((-xm).mask) assert_((-xm).mask) assert_(maximum(xm, xm).mask) assert_(minimum(xm, xm).mask) assert_(xm.filled().dtype is xm._data.dtype) x = array(0, mask=0) assert_(x.filled() == x._data) assert_equal(str(xm), str(masked_print_option))
def test_testArithmetic(self): # Test of basic arithmetic. (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d a2d = array([[1, 2], [0, 4]]) a2dm = masked_array(a2d, [[0, 0], [1, 0]]) assert_(eq(a2d * a2d, a2d * a2dm)) assert_(eq(a2d + a2d, a2d + a2dm)) assert_(eq(a2d - a2d, a2d - a2dm)) for s in [(12,), (4, 3), (2, 6)]: x = x.reshape(s) y = y.reshape(s) xm = xm.reshape(s) ym = ym.reshape(s) xf = xf.reshape(s) assert_(eq(-x, -xm)) assert_(eq(x + y, xm + ym)) assert_(eq(x - y, xm - ym)) assert_(eq(x * y, xm * ym)) with np.errstate(divide='ignore', invalid='ignore'): assert_(eq(x / y, xm / ym)) assert_(eq(a10 + y, a10 + ym)) assert_(eq(a10 - y, a10 - ym)) assert_(eq(a10 * y, a10 * ym)) with np.errstate(divide='ignore', invalid='ignore'): assert_(eq(a10 / y, a10 / ym)) assert_(eq(x + a10, xm + a10)) assert_(eq(x - a10, xm - a10)) assert_(eq(x * a10, xm * a10)) assert_(eq(x / a10, xm / a10)) assert_(eq(x ** 2, xm ** 2)) assert_(eq(abs(x) ** 2.5, abs(xm) ** 2.5)) assert_(eq(x ** y, xm ** ym)) assert_(eq(np.add(x, y), add(xm, ym))) assert_(eq(np.subtract(x, y), subtract(xm, ym))) assert_(eq(np.multiply(x, y), multiply(xm, ym))) with np.errstate(divide='ignore', invalid='ignore'): assert_(eq(np.divide(x, y), divide(xm, ym)))
def test_zero_division(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: a = t(0.0) b = t(1.0) assert_(np.isinf(b / a)) b = t(complex(np.inf, np.inf)) assert_(np.isinf(b / a)) b = t(complex(np.inf, np.nan)) assert_(np.isinf(b / a)) b = t(complex(np.nan, np.inf)) assert_(np.isinf(b / a)) b = t(complex(np.nan, np.nan)) assert_(np.isnan(b / a)) b = t(0.) assert_(np.isnan(b / a))
def test_known_types(): # Test we are correctly compiling parameters for known types for ftype, ma_like in ((np.float16, _float16_ma), (np.float32, _float32_ma), (np.float64, _float64_ma)): assert_ma_equal(_discovered_machar(ftype), ma_like) # Suppress warning for broken discovery of double double on PPC with np.errstate(all='ignore'): ld_ma = _discovered_machar(np.longdouble) bytes = np.dtype(np.longdouble).itemsize if (ld_ma.it, ld_ma.maxexp) == (63, 16384) and bytes in (12, 16): # 80-bit extended precision assert_ma_equal(ld_ma, _float80_ma) elif (ld_ma.it, ld_ma.maxexp) == (112, 16384) and bytes == 16: # IEE 754 128-bit assert_ma_equal(ld_ma, _float128_ma)
def test_unary_gufunc_fuzz(self): shapes = [7, 13, 8, 21, 29, 32] gufunc = _umath_tests.euclidean_pdist rng = np.random.RandomState(1234) for ndim in range(2, 6): x = rng.rand(*shapes[:ndim]) it = iter_random_view_pairs(x, same_steps=False, equal_size=True) min_count = 500 // (ndim + 1)**2 overlapping = 0 while overlapping < min_count: a, b = next(it) if min(a.shape[-2:]) < 2 or min(b.shape[-2:]) < 2 or a.shape[-1] < 2: continue # Ensure the shapes are so that euclidean_pdist is happy if b.shape[-1] > b.shape[-2]: b = b[...,0,:] else: b = b[...,:,0] n = a.shape[-2] p = n * (n - 1) // 2 if p <= b.shape[-1] and p > 0: b = b[...,:p] else: n = max(2, int(np.sqrt(b.shape[-1]))//2) p = n * (n - 1) // 2 a = a[...,:n,:] b = b[...,:p] # Call if np.shares_memory(a, b): overlapping += 1 with np.errstate(over='ignore', invalid='ignore'): assert_copy_equivalent(gufunc, [a], out=b)
def test_signed_zeros(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = (((0.0, -1.0), (0.0, 1.0), (-1.0, -0.0)), ((0.0, -1.0), (0.0, -1.0), (1.0, -0.0)), ((0.0, -1.0), (-0.0, -1.0), (1.0, 0.0)), ((0.0, -1.0), (-0.0, 1.0), (-1.0, 0.0)), ((0.0, 1.0), (0.0, -1.0), (-1.0, 0.0)), ((0.0, -1.0), (0.0, -1.0), (1.0, -0.0)), ((-0.0, -1.0), (0.0, -1.0), (1.0, -0.0)), ((-0.0, 1.0), (0.0, -1.0), (-1.0, -0.0))) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1])
def test_testUfuncRegression(self): f_invalid_ignore = [ 'sqrt', 'arctanh', 'arcsin', 'arccos', 'arccosh', 'arctanh', 'log', 'log10', 'divide', 'true_divide', 'floor_divide', 'remainder', 'fmod'] for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate', 'sin', 'cos', 'tan', 'arcsin', 'arccos', 'arctan', 'sinh', 'cosh', 'tanh', 'arcsinh', 'arccosh', 'arctanh', 'absolute', 'fabs', 'negative', 'floor', 'ceil', 'logical_not', 'add', 'subtract', 'multiply', 'divide', 'true_divide', 'floor_divide', 'remainder', 'fmod', 'hypot', 'arctan2', 'equal', 'not_equal', 'less_equal', 'greater_equal', 'less', 'greater', 'logical_and', 'logical_or', 'logical_xor']: try: uf = getattr(umath, f) except AttributeError: uf = getattr(fromnumeric, f) mf = getattr(np.ma, f) args = self.d[:uf.nin] with np.errstate(): if f in f_invalid_ignore: np.seterr(invalid='ignore') if f in ['arctanh', 'log', 'log10']: np.seterr(divide='ignore') ur = uf(*args) mr = mf(*args) assert_(eq(ur.filled(0), mr.filled(0), f)) assert_(eqmask(ur.mask, mr.mask))
def test_ind(self): with np.errstate(divide='ignore', invalid='ignore'): assert_all(np.isinf(np.array((0., )) / 0.) == 0)
def test_half_fpe(self): with np.errstate(all='raise'): sx16 = np.array((1e-4, ), dtype=float16) bx16 = np.array((1e4, ), dtype=float16) sy16 = float16(1e-4) by16 = float16(1e4) # Underflow errors assert_raises_fpe('underflow', lambda a, b: a * b, sx16, sx16) assert_raises_fpe('underflow', lambda a, b: a * b, sx16, sy16) assert_raises_fpe('underflow', lambda a, b: a * b, sy16, sx16) assert_raises_fpe('underflow', lambda a, b: a * b, sy16, sy16) assert_raises_fpe('underflow', lambda a, b: a / b, sx16, bx16) assert_raises_fpe('underflow', lambda a, b: a / b, sx16, by16) assert_raises_fpe('underflow', lambda a, b: a / b, sy16, bx16) assert_raises_fpe('underflow', lambda a, b: a / b, sy16, by16) assert_raises_fpe('underflow', lambda a, b: a / b, float16(2.**-14), float16(2**11)) assert_raises_fpe('underflow', lambda a, b: a / b, float16(-2.**-14), float16(2**11)) assert_raises_fpe('underflow', lambda a, b: a / b, float16(2.**-14 + 2**-24), float16(2)) assert_raises_fpe('underflow', lambda a, b: a / b, float16(-2.**-14 - 2**-24), float16(2)) assert_raises_fpe('underflow', lambda a, b: a / b, float16(2.**-14 + 2**-23), float16(4)) # Overflow errors assert_raises_fpe('overflow', lambda a, b: a * b, bx16, bx16) assert_raises_fpe('overflow', lambda a, b: a * b, bx16, by16) assert_raises_fpe('overflow', lambda a, b: a * b, by16, bx16) assert_raises_fpe('overflow', lambda a, b: a * b, by16, by16) assert_raises_fpe('overflow', lambda a, b: a / b, bx16, sx16) assert_raises_fpe('overflow', lambda a, b: a / b, bx16, sy16) assert_raises_fpe('overflow', lambda a, b: a / b, by16, sx16) assert_raises_fpe('overflow', lambda a, b: a / b, by16, sy16) assert_raises_fpe('overflow', lambda a, b: a + b, float16(65504), float16(17)) assert_raises_fpe('overflow', lambda a, b: a - b, float16(-65504), float16(17)) assert_raises_fpe('overflow', np.nextafter, float16(65504), float16(np.inf)) assert_raises_fpe('overflow', np.nextafter, float16(-65504), float16(-np.inf)) assert_raises_fpe('overflow', np.spacing, float16(65504)) # Invalid value errors assert_raises_fpe('invalid', np.divide, float16(np.inf), float16(np.inf)) assert_raises_fpe('invalid', np.spacing, float16(np.inf)) assert_raises_fpe('invalid', np.spacing, float16(np.nan)) assert_raises_fpe('invalid', np.nextafter, float16(np.inf), float16(0)) assert_raises_fpe('invalid', np.nextafter, float16(-np.inf), float16(0)) assert_raises_fpe('invalid', np.nextafter, float16(0), float16(np.nan)) # These should not raise float16(65472) + float16(32) float16(2**-13) / float16(2) float16(2**-14) / float16(2**10) np.spacing(float16(-65504)) np.nextafter(float16(65504), float16(-np.inf)) np.nextafter(float16(-65504), float16(np.inf)) float16(2**-14) / float16(2**10) float16(-2**-14) / float16(2**10) float16(2**-14 + 2**-23) / float16(2) float16(-2**-14 - 2**-23) / float16(2)
def test_posinf(self): with np.errstate(divide='ignore'): assert_all(np.isnan(np.array((1., )) / 0.) == 0)
def test_complex1(self): with np.errstate(divide='ignore', invalid='ignore'): assert_all(np.isnan(np.array(0 + 0j) / 0.) == 1)
def test_neginf(self): with np.errstate(divide='ignore', invalid='ignore'): assert_all(np.isfinite(np.array((-1., )) / 0.) == 0)
def nper(rate, pmt, pv, fv=0, when='end'): """ Compute the number of periodic payments. :class:`decimal.Decimal` type is not supported. Parameters ---------- rate : array_like Rate of interest (per period) pmt : array_like Payment pv : array_like Present value fv : array_like, optional Future value when : {{'begin', 1}, {'end', 0}}, {string, int}, optional When payments are due ('begin' (1) or 'end' (0)) Notes ----- The number of periods ``nper`` is computed by solving the equation:: fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate*((1+rate)**nper-1) = 0 but if ``rate = 0`` then:: fv + pv + pmt*nper = 0 Examples -------- If you only had $150/month to pay towards the loan, how long would it take to pay-off a loan of $8,000 at 7% annual interest? >>> print(round(np.nper(0.07/12, -150, 8000), 5)) 64.07335 So, over 64 months would be required to pay off the loan. The same analysis could be done with several different interest rates and/or payments and/or total amounts to produce an entire table. >>> np.nper(*(np.ogrid[0.07/12: 0.08/12: 0.01/12, ... -150 : -99 : 50 , ... 8000 : 9001 : 1000])) array([[[ 64.07334877, 74.06368256], [ 108.07548412, 127.99022654]], [[ 66.12443902, 76.87897353], [ 114.70165583, 137.90124779]]]) """ when = _convert_when(when) (rate, pmt, pv, fv, when) = map(np.asarray, [rate, pmt, pv, fv, when]) use_zero_rate = False with np.errstate(divide="raise"): try: z = pmt * (1 + rate * when) / rate except FloatingPointError: use_zero_rate = True if use_zero_rate: return (-fv + pv) / pmt else: A = -(fv + pv) / (pmt + 0) B = np.log((-fv + z) / (pv + z)) / np.log(1 + rate) return np.where(rate == 0, A, B)
def test_unary_ufunc_1d_manual(self): # Exercise branches in PyArray_EQUIVALENTLY_ITERABLE def check(a, b): a_orig = a.copy() b_orig = b.copy() b0 = b.copy() c1 = ufunc(a, out=b0) c2 = ufunc(a, out=b) assert_array_equal(c1, c2) # Trigger "fancy ufunc loop" code path mask = view_element_first_byte(b).view(np.bool_) a[...] = a_orig b[...] = b_orig c1 = ufunc(a, out=b.copy(), where=mask.copy()).copy() a[...] = a_orig b[...] = b_orig c2 = ufunc(a, out=b, where=mask.copy()).copy() # Also, mask overlapping with output a[...] = a_orig b[...] = b_orig c3 = ufunc(a, out=b, where=mask).copy() assert_array_equal(c1, c2) assert_array_equal(c1, c3) dtypes = [np.int8, np.int16, np.int32, np.int64, np.float32, np.float64, np.complex64, np.complex128] dtypes = [np.dtype(x) for x in dtypes] for dtype in dtypes: if np.issubdtype(dtype, np.integer): ufunc = np.invert else: ufunc = np.reciprocal n = 1000 k = 10 indices = [ np.index_exp[:n], np.index_exp[k:k+n], np.index_exp[n-1::-1], np.index_exp[k+n-1:k-1:-1], np.index_exp[:2*n:2], np.index_exp[k:k+2*n:2], np.index_exp[2*n-1::-2], np.index_exp[k+2*n-1:k-1:-2], ] for xi, yi in itertools.product(indices, indices): v = np.arange(1, 1 + n*2 + k, dtype=dtype) x = v[xi] y = v[yi] with np.errstate(all='ignore'): check(x, y) # Scalar cases check(x[:1], y) check(x[-1:], y) check(x[:1].reshape([]), y) check(x[-1:].reshape([]), y)
def test_complex1(self): with np.errstate(divide='ignore', invalid='ignore'): assert_all(np.isfinite(np.array(1 + 1j) / 0.) == 0)
def test_neginf_scalar(self): with np.errstate(divide='ignore', invalid='ignore'): assert_all(np.isinf(np.array(-1.) / 0.) == 1)
def test_generic(self): with np.errstate(divide='ignore', invalid='ignore'): vals = isneginf(np.array((-1., 0, 1)) / 0.) assert_(vals[0] == 1) assert_(vals[1] == 0) assert_(vals[2] == 0)