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_100(self): x, w = herme.hermegauss(100) # test orthogonality. Note that the results need to be normalized, # otherwise the huge values that can arise from fast growing # functions like Laguerre can be very confusing. v = herme.hermevander(x, 99) vv = np.dot(v.T * w, v) vd = 1 / np.sqrt(vv.diagonal()) vv = vd[:, None] * vv * vd assert_almost_equal(vv, np.eye(100)) # check that the integral of 1 is correct tgt = np.sqrt(2 * np.pi) assert_almost_equal(w.sum(), tgt)
def test_simple_conjugate(self): ref = np.conj(np.sqrt(complex(1, 1))) def f(z): return np.sqrt(np.conj(z)) check_complex_value(f, 1, 1, ref.real, ref.imag, False)
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 _hist_bin_doane(x): """ Doane's histogram bin estimator. Improved version of Sturges' formula which works better for non-normal data. See stats.stackexchange.com/questions/55134/doanes-formula-for-histogram-binning Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ if x.size > 2: sg1 = np.sqrt(6.0 * (x.size - 2) / ((x.size + 1.0) * (x.size + 3))) sigma = np.std(x) if sigma > 0.0: # These three operations add up to # g1 = np.mean(((x - np.mean(x)) / sigma)**3) # but use only one temp array instead of three temp = x - np.mean(x) np.true_divide(temp, sigma, temp) np.power(temp, 3, temp) g1 = np.mean(temp) return x.ptp() / (1.0 + np.log2(x.size) + np.log2(1.0 + np.absolute(g1) / sg1)) return 0.0
def test_ifftn(self): x = random((30, 20, 10)) + 1j*random((30, 20, 10)) assert_array_almost_equal( np.fft.ifft(np.fft.ifft(np.fft.ifft(x, axis=2), axis=1), axis=0), np.fft.ifftn(x)) assert_array_almost_equal(np.fft.ifftn(x) * np.sqrt(30 * 20 * 10), np.fft.ifftn(x, norm="ortho"))
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 test_hfft(self): x = random(14) + 1j*random(14) x_herm = np.concatenate((random(1), x, random(1))) x = np.concatenate((x_herm, x[::-1].conj())) assert_array_almost_equal(np.fft.fft(x), np.fft.hfft(x_herm)) assert_array_almost_equal(np.fft.hfft(x_herm) / np.sqrt(30), np.fft.hfft(x_herm, norm="ortho"))
def test_rfft(self): x = random(30) for n in [x.size, 2*x.size]: for norm in [None, 'ortho']: assert_array_almost_equal( np.fft.fft(x, n=n, norm=norm)[:(n//2 + 1)], np.fft.rfft(x, n=n, norm=norm)) assert_array_almost_equal(np.fft.rfft(x, n=n) / np.sqrt(n), np.fft.rfft(x, n=n, norm="ortho"))
def test_simple(self): # sqrt(1) check_complex_value(np.sqrt, 1, 0, 1, 0) # sqrt(1i) rres = 0.5*np.sqrt(2) ires = rres check_complex_value(np.sqrt, 0, 1, rres, ires, False) # sqrt(-1) check_complex_value(np.sqrt, -1, 0, 0, 1)
def test_varstd(self): (x, X, XX, m, mx, mX, mXX,) = self.d assert_(eq(mX.var(axis=None), mX.compressed().var())) assert_(eq(mX.std(axis=None), mX.compressed().std())) assert_(eq(mXX.var(axis=3).shape, XX.var(axis=3).shape)) assert_(eq(mX.var().shape, X.var().shape)) (mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1)) for k in range(6): assert_(eq(mXvar1[k], mX[k].compressed().var())) assert_(eq(mXvar0[k], mX[:, k].compressed().var())) assert_(eq(np.sqrt(mXvar0[k]), mX[:, k].compressed().std()))
def test_poly(self): assert_array_almost_equal(np.poly([3, -np.sqrt(2), np.sqrt(2)]), [1, -3, -2, 6]) # From matlab docs A = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] assert_array_almost_equal(np.poly(A), [1, -6, -72, -27]) # Should produce real output for perfect conjugates assert_(np.isrealobj(np.poly([+1.082j, +2.613j, -2.613j, -1.082j]))) assert_(np.isrealobj(np.poly([0+1j, -0+-1j, 1+2j, 1-2j, 1.+3.5j, 1-3.5j]))) assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j, 1+3j, 1-3.j]))) assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j]))) assert_(np.isrealobj(np.poly([1j, -1j, 2j, -2j]))) assert_(np.isrealobj(np.poly([1j, -1j]))) assert_(np.isrealobj(np.poly([1, -1]))) assert_(np.iscomplexobj(np.poly([1j, -1.0000001j]))) np.random.seed(42) a = np.random.randn(100) + 1j*np.random.randn(100) assert_(np.isrealobj(np.poly(np.concatenate((a, np.conjugate(a))))))
def test_py2_float_print(self): # gh-10753 # In python2, the python float type implements an obsolte method # tp_print, which overrides tp_repr and tp_str when using "print" to # output to a "real file" (ie, not a StringIO). Make sure we don't # inherit it. x = np.double(0.1999999999999) with TemporaryFile('r+t') as f: print(x, file=f) f.seek(0) output = f.read() assert_equal(output, str(x) + '\n') # In python2 the value float('0.1999999999999') prints with reduced # precision as '0.2', but we want numpy's np.double('0.1999999999999') # to print the unique value, '0.1999999999999'. # gh-11031 # Only in the python2 interactive shell and when stdout is a "real" # file, the output of the last command is printed to stdout without # Py_PRINT_RAW (unlike the print statement) so `>>> x` and `>>> print # x` are potentially different. Make sure they are the same. The only # way I found to get prompt-like output is using an actual prompt from # the 'code' module. Again, must use tempfile to get a "real" file. # dummy user-input which enters one line and then ctrl-Ds. def userinput(): yield 'np.sqrt(2)' raise EOFError gen = userinput() input_func = lambda prompt="": next(gen) with TemporaryFile('r+t') as fo, TemporaryFile('r+t') as fe: orig_stdout, orig_stderr = sys.stdout, sys.stderr sys.stdout, sys.stderr = fo, fe # py2 code.interact sends irrelevant internal DeprecationWarnings with suppress_warnings() as sup: sup.filter(DeprecationWarning) code.interact(local={'np': np}, readfunc=input_func, banner='') sys.stdout, sys.stderr = orig_stdout, orig_stderr fo.seek(0) capture = fo.read().strip() assert_equal(capture, repr(np.sqrt(2)))
def _hist_bin_sqrt(x): """ Square root histogram bin estimator. Bin width is inversely proportional to the data size. Used by many programs for its simplicity. Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ return x.ptp() / np.sqrt(x.size)
def test_complex(self): # Purely imaginary y = geomspace(1j, 16j, num=5) assert_allclose(y, [1j, 2j, 4j, 8j, 16j]) assert_array_equal(y.real, 0) y = geomspace(-4j, -324j, num=5) assert_allclose(y, [-4j, -12j, -36j, -108j, -324j]) assert_array_equal(y.real, 0) y = geomspace(1 + 1j, 1000 + 1000j, num=4) assert_allclose(y, [1 + 1j, 10 + 10j, 100 + 100j, 1000 + 1000j]) y = geomspace(-1 + 1j, -1000 + 1000j, num=4) assert_allclose(y, [-1 + 1j, -10 + 10j, -100 + 100j, -1000 + 1000j]) # Logarithmic spirals y = geomspace(-1, 1, num=3, dtype=complex) assert_allclose(y, [-1, 1j, +1]) y = geomspace(0 + 3j, -3 + 0j, 3) assert_allclose(y, [0 + 3j, -3 / sqrt(2) + 3j / sqrt(2), -3 + 0j]) y = geomspace(0 + 3j, 3 + 0j, 3) assert_allclose(y, [0 + 3j, 3 / sqrt(2) + 3j / sqrt(2), 3 + 0j]) y = geomspace(-3 + 0j, 0 - 3j, 3) assert_allclose(y, [-3 + 0j, -3 / sqrt(2) - 3j / sqrt(2), 0 - 3j]) y = geomspace(0 + 3j, -3 + 0j, 3) assert_allclose(y, [0 + 3j, -3 / sqrt(2) + 3j / sqrt(2), -3 + 0j]) y = geomspace(-2 - 3j, 5 + 7j, 7) assert_allclose(y, [ -2 - 3j, -0.29058977 - 4.15771027j, 2.08885354 - 4.34146838j, 4.58345529 - 3.16355218j, 6.41401745 - 0.55233457j, 6.75707386 + 3.11795092j, 5 + 7j ]) # Type promotion should prevent the -5 from becoming a NaN y = geomspace(3j, -5, 2) assert_allclose(y, [3j, -5]) y = geomspace(-5, 3j, 2) assert_allclose(y, [-5, 3j])
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_fft2(self): x = random((30, 20)) + 1j*random((30, 20)) assert_array_almost_equal(np.fft.fft(np.fft.fft(x, axis=1), axis=0), np.fft.fft2(x)) assert_array_almost_equal(np.fft.fft2(x) / np.sqrt(30 * 20), np.fft.fft2(x, norm="ortho"))
def test_rfft2(self): x = random((30, 20)) assert_array_almost_equal(np.fft.fft2(x)[:, :11], np.fft.rfft2(x)) assert_array_almost_equal(np.fft.rfft2(x) / np.sqrt(30 * 20), np.fft.rfft2(x, norm="ortho"))
def test_fft(self): x = random(30) + 1j*random(30) assert_array_almost_equal(fft1(x), np.fft.fft(x)) assert_array_almost_equal(fft1(x) / np.sqrt(30), np.fft.fft(x, norm="ortho"))
def test_simple(self): x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan]) y_r = np.array([np.sqrt(2.), 2, np.sqrt(5), np.inf, np.nan]) y = np.abs(x) for i in range(len(x)): assert_almost_equal(y[i], y_r[i])
def test_weight(self): x = np.linspace(-1, 1, 11)[1:-1] tgt = 1./(np.sqrt(1 + x) * np.sqrt(1 - x)) res = cheb.chebweight(x) assert_almost_equal(res, tgt)
def f(z): return np.sqrt(np.conj(z))