diff options
author | Paul Ivanov <paul.ivanov@local> | 2009-12-28 20:49:52 +0000 |
---|---|---|
committer | Paul Ivanov <paul.ivanov@local> | 2009-12-28 20:49:52 +0000 |
commit | e4f233ecfedd2aafa258db2d3ae27e30604cc020 (patch) | |
tree | 6d32fbdd19b8dca00cd7cafd8df076bac55ddfd8 | |
parent | 5ba01996a9ab2fdfb7c120a5afae801f854a781a (diff) | |
download | numpy-e4f233ecfedd2aafa258db2d3ae27e30604cc020.tar.gz |
fixed a whole bunch of doctests
35 files changed, 363 insertions, 185 deletions
diff --git a/numpy/__init__.py b/numpy/__init__.py index 709ef373a..8247f4c7a 100644 --- a/numpy/__init__.py +++ b/numpy/__init__.py @@ -24,11 +24,13 @@ The docstring examples assume that `numpy` has been imported as `np`:: Code snippets are indicated by three greater-than signs:: + >>> x = 42 >>> x = x + 1 Use the built-in ``help`` function to view a function's docstring:: >>> help(np.sort) + ... # doctest: +SKIP For some objects, ``np.info(obj)`` may provide additional help. This is particularly true if you see the line "Help on ufunc object:" at the top @@ -39,12 +41,14 @@ np.info() function does. To search for documents containing a keyword, do:: >>> np.lookfor('keyword') + ... # doctest: +SKIP General-purpose documents like a glossary and help on the basic concepts of numpy are available under the ``doc`` sub-module:: >>> from numpy import doc >>> help(doc) + ... # doctest: +SKIP Available subpackages --------------------- diff --git a/numpy/add_newdocs.py b/numpy/add_newdocs.py index d34b01258..bbb93f6f2 100644 --- a/numpy/add_newdocs.py +++ b/numpy/add_newdocs.py @@ -404,12 +404,12 @@ add_newdoc('numpy.core.multiarray', 'empty', Examples -------- >>> np.empty([2, 2]) - array([[ -9.74499359e+001, 6.69583040e-309], #random data - [ 2.13182611e-314, 3.06959433e-309]]) + array([[ -9.74499359e+001, 6.69583040e-309], + [ 2.13182611e-314, 3.06959433e-309]]) #random >>> np.empty([2, 2], dtype=int) - array([[-1073741821, -1067949133], #random data - [ 496041986, 19249760]]) + array([[-1073741821, -1067949133], + [ 496041986, 19249760]]) #random """) @@ -1516,7 +1516,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', >>> np.ndarray(shape=(2,2), dtype=float, order='F') array([[ -1.13698227e+002, 4.25087011e-303], - [ 2.88528414e-306, 3.27025015e-309]]) + [ 2.88528414e-306, 3.27025015e-309]]) #random Second mode: diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py index c8d4e13f7..536b26f40 100644 --- a/numpy/core/arrayprint.py +++ b/numpy/core/arrayprint.py @@ -88,6 +88,11 @@ def set_printoptions(precision=None, threshold=None, edgeitems=None, >>> x**2 - (x + eps)**2 array([-0., -0., 0., 0.]) + To put back the default options, you can use: + + >>> np.set_printoptions(edgeitems=3,infstr='Inf', + ... linewidth=75, nanstr='NaN', precision=8, + ... suppress=False, threshold=1000) """ global _summaryThreshold, _summaryEdgeItems, _float_output_precision, \ diff --git a/numpy/core/defchararray.py b/numpy/core/defchararray.py index b7ad2230e..4530bd5ad 100644 --- a/numpy/core/defchararray.py +++ b/numpy/core/defchararray.py @@ -457,7 +457,7 @@ def count(a, sub, start=0, end=None): -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c - array(['aAaAaA', ' aA', 'abBABba'], + array(['aAaAaA', ' aA ', 'abBABba'], dtype='|S7') >>> np.char.count(c, 'A') array([3, 1, 1]) @@ -505,7 +505,7 @@ def decode(a, encoding=None, errors=None): -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c - array(['aAaAaA', ' aA', 'abBABba'], + array(['aAaAaA', ' aA ', 'abBABba'], dtype='|S7') >>> np.char.encode(c, encoding='cp037') array(['\\x81\\xc1\\x81\\xc1\\x81\\xc1', '@@\\x81\\xc1@@', @@ -584,9 +584,9 @@ def endswith(a, suffix, start=0, end=None): >>> s array(['foo', 'bar'], dtype='|S3') - >>> np.charendswith(s, 'ar') + >>> np.char.endswith(s, 'ar') array([False, True], dtype=bool) - >>> s.endswith(s, 'a', start=1, end=2) + >>> np.char.endswith(s, 'a', start=1, end=2) array([False, True], dtype=bool) """ @@ -1010,15 +1010,17 @@ def lstrip(a, chars=None): -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c - array(['aAaAaA', ' aA', 'abBABba'], + array(['aAaAaA', ' aA ', 'abBABba'], dtype='|S7') >>> np.char.lstrip(c, 'a') # 'a' unstripped from c[1] because whitespace leading - array(['AaAaA', ' aA', 'bBABba'], - dtype='|S6') + array(['AaAaA', ' aA ', 'bBABba'], + dtype='|S7') >>> np.char.lstrip(c, 'A') # leaves c unchanged - array(['aAaAaA', ' aA', 'abBABba'], + array(['aAaAaA', ' aA ', 'abBABba'], dtype='|S7') >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, '')).all() + ... # XXX: is this a regression? this line now returns False + ... # np.char.lstrip(c,'') does not modify c at all. True >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, None)).all() True @@ -1313,7 +1315,7 @@ def rstrip(a, chars=None): dtype='|S7') >>> np.char.rstrip(c, 'a') array(['aAaAaA', 'abBABb'], - dtype='|S6') + dtype='|S7') >>> np.char.rstrip(c, 'A') array(['aAaAa', 'abBABba'], dtype='|S7') @@ -1444,16 +1446,16 @@ def strip(a, chars=None): -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c - array(['aAaAaA', ' aA', 'abBABba'], + array(['aAaAaA', ' aA ', 'abBABba'], dtype='|S7') >>> np.char.strip(c) array(['aAaAaA', 'aA', 'abBABba'], dtype='|S7') >>> np.char.strip(c, 'a') # 'a' unstripped from c[1] because whitespace leads - array(['AaAaA', ' aA', 'bBABb'], - dtype='|S6') + array(['AaAaA', ' aA ', 'bBABb'], + dtype='|S7') >>> np.char.strip(c, 'A') # 'A' unstripped from c[1] because (unprinted) ws trails - array(['aAaAa', ' aA', 'abBABba'], + array(['aAaAa', ' aA ', 'abBABba'], dtype='|S7') """ @@ -1523,7 +1525,7 @@ def title(a): array(['a1b c', '1b ca', 'b ca1', 'ca1b'], dtype='|S5') >>> np.char.title(c) - chararray(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'], + array(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'], dtype='|S5') """ a_arr = numpy.asarray(a) @@ -1590,7 +1592,7 @@ def upper(a): >>> c = np.array(['a1b c', '1bca', 'bca1']); c array(['a1b c', '1bca', 'bca1'], dtype='|S5') - >>> numpy.char.upper(c) + >>> np.char.upper(c) array(['A1B C', '1BCA', 'BCA1'], dtype='|S5') """ @@ -1742,7 +1744,7 @@ class chararray(ndarray): Examples -------- >>> charar = np.chararray((3, 3)) - >>> charar[:, :] = 'abc' + >>> charar[:] = 'a' >>> charar chararray([['a', 'a', 'a'], ['a', 'a', 'a'], @@ -1750,7 +1752,7 @@ class chararray(ndarray): dtype='|S1') >>> charar = np.chararray(charar.shape, itemsize=5) - >>> charar[:, :] = 'abc' + >>> charar[:] = 'abc' >>> charar chararray([['abc', 'abc', 'abc'], ['abc', 'abc', 'abc'], diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py index 4b3970f00..b9265216f 100644 --- a/numpy/core/fromnumeric.py +++ b/numpy/core/fromnumeric.py @@ -1298,8 +1298,9 @@ def clip(a, a_min, a_max, out=None): array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.clip(a, 3, 6, out=a) array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6]) + >>> a = np.arange(10) >>> a - array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6]) + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.clip(a, [3,4,1,1,1,4,4,4,4,4], 8) array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8]) @@ -1500,7 +1501,7 @@ def any(a,axis=None, out=None): >>> # Check now that z is a reference to o >>> z is o True - >>> id(z), id(o) # identity of z and o + >>> id(z), id(o) # identity of z and o # doctest: +SKIP (191614240, 191614240) """ @@ -1563,7 +1564,7 @@ def all(a,axis=None, out=None): >>> o=np.array([False]) >>> z=np.all([-1, 4, 5], out=o) - >>> id(z), id(o), z + >>> id(z), id(o), z # doctest: +SKIP (28293632, 28293632, array([ True], dtype=bool)) """ diff --git a/numpy/core/function_base.py b/numpy/core/function_base.py index 33cf3a15b..b2f9dc70c 100644 --- a/numpy/core/function_base.py +++ b/numpy/core/function_base.py @@ -63,8 +63,11 @@ def linspace(start, stop, num=50, endpoint=True, retstep=False): >>> x1 = np.linspace(0, 10, N, endpoint=True) >>> x2 = np.linspace(0, 10, N, endpoint=False) >>> plt.plot(x1, y, 'o') + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.plot(x2, y + 0.5, 'o') + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.ylim([-0.5, 1]) + (-0.5, 1) >>> plt.show() """ @@ -129,8 +132,10 @@ def logspace(start,stop,num=50,endpoint=True,base=10.0): ----- Logspace is equivalent to the code - >>> y = linspace(start, stop, num=num, endpoint=endpoint) + >>> y = np.linspace(start, stop, num=num, endpoint=endpoint) + ... # doctest: +SKIP >>> power(base, y) + ... # doctest: +SKIP Examples -------- @@ -149,8 +154,11 @@ def logspace(start,stop,num=50,endpoint=True,base=10.0): >>> x2 = np.logspace(0.1, 1, N, endpoint=False) >>> y = np.zeros(N) >>> plt.plot(x1, y, 'o') + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.plot(x2, y + 0.5, 'o') + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.ylim([-0.5, 1]) + (-0.5, 1) >>> plt.show() """ diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 8c4fa2980..176212d09 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -638,6 +638,7 @@ def correlate(a,v,mode='valid',old_behavior=True): This function is equivalent to >>> np.convolve(a, v[::-1], mode=mode) + ... #doctest: +SKIP where ``v[::-1]`` is the reverse of `v`. @@ -963,6 +964,9 @@ def tensordot(a, b, axes=2): [aaaaaaacccccccc, bbbbbbbdddddddd]]], dtype=object) >>> np.tensordot(a, A, 0) # "Left for reader" (result too long to incl.) + array([[[[[a, b], + [c, d]], + ... >>> np.tensordot(a, A, (0, 1)) array([[[abbbbb, cddddd], @@ -1413,7 +1417,7 @@ def array_str(a, max_line_width=None, precision=None, suppress_small=None): Examples -------- >>> np.array_str(np.arange(3)) - >>> '[0 1 2]' + '[0 1 2]' """ return array2string(a, max_line_width, precision, suppress_small, ' ', "", str) @@ -1465,7 +1469,7 @@ def indices(dimensions, dtype=int): -------- >>> grid = np.indices((2, 3)) >>> grid.shape - (2,2,3) + (2, 2, 3) >>> grid[0] # row indices array([[0, 0, 0], [1, 1, 1]]) @@ -1973,19 +1977,19 @@ def array_equiv(a1, a2): Examples -------- >>> np.array_equiv([1, 2], [1, 2]) - >>> True + True >>> np.array_equiv([1, 2], [1, 3]) - >>> False + False Showing the shape equivalence: >>> np.array_equiv([1, 2], [[1, 2], [1, 2]]) - >>> True + True >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]]) - >>> False + False >>> np.array_equiv([1, 2], [[1, 2], [1, 3]]) - >>> False + False """ try: @@ -2064,11 +2068,12 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): Examples -------- + >>> old_settings = np.seterr(all='ignore') #seterr to known value >>> np.seterr(over='raise') {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} >>> np.seterr(all='ignore') # reset to default - {'over': 'raise', 'divide': 'warn', 'invalid': 'warn', 'under': 'warn'} + {'over': 'raise', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} >>> np.int16(32000) * np.int16(3) 30464 @@ -2078,16 +2083,28 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): File "<stdin>", line 1, in <module> FloatingPointError: overflow encountered in short_scalars - >>> np.seterr(all='print') + >>> old_settings = np.seterr(all='print') + >>> np.geterr() {'over': 'print', 'divide': 'print', 'invalid': 'print', 'under': 'print'} >>> np.int16(32000) * np.int16(3) Warning: overflow encountered in short_scalars 30464 Calling `seterr` with no arguments resets treatment for all floating-point - errors to the defaults. + errors to the defaults. XXX: lies!!! code doesn't do that + >>> np.geterr() + {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} + >>> np.seterr(all='warn') + {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} + >>> np.geterr() + {'over': 'warn', 'divide': 'warn', 'invalid': 'warn', 'under': 'warn'} + >>> np.seterr() # XXX: this should reset to defaults according to docstring above + {'over': 'warn', 'divide': 'warn', 'invalid': 'warn', 'under': 'warn'} + >>> np.geterr() # XXX: but clearly it doesn't + {'over': 'warn', 'divide': 'warn', 'invalid': 'warn', 'under': 'warn'} >>> old_settings = np.seterr() + >>> old_settings = np.seterr(all='ignore') >>> np.geterr() {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} @@ -2234,7 +2251,7 @@ def seterrcall(func): Callback upon error: >>> def err_handler(type, flag): - print "Floating point error (%s), with flag %s" % (type, flag) + ... print "Floating point error (%s), with flag %s" % (type, flag) ... >>> saved_handler = np.seterrcall(err_handler) @@ -2245,13 +2262,15 @@ def seterrcall(func): array([ Inf, Inf, Inf]) >>> np.seterrcall(saved_handler) + <function err_handler at 0x...> >>> np.seterr(**save_err) + {'over': 'call', 'divide': 'call', 'invalid': 'call', 'under': 'call'} Log error message: >>> class Log(object): - def write(self, msg): - print "LOG: %s" % msg + ... def write(self, msg): + ... print "LOG: %s" % msg ... >>> log = Log() @@ -2260,9 +2279,13 @@ def seterrcall(func): >>> np.array([1, 2, 3]) / 0.0 LOG: Warning: divide by zero encountered in divide + <BLANKLINE> + array([ Inf, Inf, Inf]) >>> np.seterrcall(saved_handler) + <__main__.Log object at 0x...> >>> np.seterr(**save_err) + {'over': 'log', 'divide': 'log', 'invalid': 'log', 'under': 'log'} """ if func is not None and not callable(func): @@ -2371,7 +2394,6 @@ class errstate(object): nan >>> with np.errstate(invalid='raise'): ... np.sqrt(-1) - ... Traceback (most recent call last): File "<stdin>", line 2, in <module> FloatingPointError: invalid value encountered in sqrt diff --git a/numpy/core/records.py b/numpy/core/records.py index b1736e0cf..77c8968f1 100644 --- a/numpy/core/records.py +++ b/numpy/core/records.py @@ -126,7 +126,7 @@ class format_parser: >>> np.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'], ... ['T1', 'T2', 'T3']).dtype dtype([(('T1', 'col1'), '<f8'), (('T2', 'col2'), '<i4'), - (('T3', 'col3'), '|S5')] + (('T3', 'col3'), '|S5')]) `names` and/or `titles` can be empty lists. If `titles` is an empty list, titles will simply not appear. If `names` is empty, default field names diff --git a/numpy/ctypeslib.py b/numpy/ctypeslib.py index 459770a47..ce90dacda 100644 --- a/numpy/ctypeslib.py +++ b/numpy/ctypeslib.py @@ -18,14 +18,14 @@ Examples -------- Load the C library: ->>> _lib = np.ctypeslib.load_library('libmystuff', '.') #DOCTEST: +ignore +>>> _lib = np.ctypeslib.load_library('libmystuff', '.') #doctest: +SKIP Our result type, an ndarray that must be of type double, be 1-dimensional and is C-contiguous in memory: >>> array_1d_double = np.ctypeslib.ndpointer( ... dtype=np.double, -... ndim=1, flags='CONTIGUOUS') #DOCTEST: +ignore +... ndim=1, flags='CONTIGUOUS') #doctest: +SKIP Our C-function typically takes an array and updates its values in-place. For example:: @@ -40,13 +40,13 @@ in-place. For example:: We wrap it using: ->>> lib.foo_func.restype = None #DOCTEST: +ignore ->>> lib.foo.argtypes = [array_1d_double, c_int] #DOCTEST: +ignore +>>> lib.foo_func.restype = None #doctest: +SKIP +>>> lib.foo.argtypes = [array_1d_double, c_int] #doctest: +SKIP Then, we're ready to call ``foo_func``: >>> out = np.empty(15, dtype=np.double) ->>> _lib.foo_func(out, len(out)) #DOCTEST: +ignore +>>> _lib.foo_func(out, len(out)) #doctest: +SKIP """ __all__ = ['load_library', 'ndpointer', 'test', 'ctypes_load_library', @@ -229,7 +229,9 @@ def ndpointer(dtype=None, ndim=None, shape=None, flags=None): >>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64, ... ndim=1, ... flags='C_CONTIGUOUS')] + ... #doctest: +SKIP >>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64)) + ... #doctest: +SKIP """ diff --git a/numpy/distutils/misc_util.py b/numpy/distutils/misc_util.py index f5b8b7823..7380ad527 100644 --- a/numpy/distutils/misc_util.py +++ b/numpy/distutils/misc_util.py @@ -775,7 +775,7 @@ class Configuration(object): Examples -------- - >>> setup(\**config.todict()). + >>> setup(**config.todict()) #doctest: +SKIP """ self._optimize_data_files() @@ -1019,9 +1019,9 @@ class Configuration(object): For example suppose the source directory contains fun/foo.dat and fun/bar/car.dat:: - >>> self.add_data_dir('fun') - >>> self.add_data_dir(('sun', 'fun')) - >>> self.add_data_dir(('gun', '/full/path/to/fun')) + >>> self.add_data_dir('fun') #doctest: +SKIP + >>> self.add_data_dir(('sun', 'fun')) #doctest: +SKIP + >>> self.add_data_dir(('gun', '/full/path/to/fun'))#doctest: +SKIP Will install data-files to the locations:: @@ -1176,9 +1176,9 @@ class Configuration(object): Add files to the list of data_files to be included with the package. >>> self.add_data_files('foo.dat', - ('fun', ['gun.dat', 'nun/pun.dat', '/tmp/sun.dat']), - 'bar/cat.dat', - '/full/path/to/can.dat') + ... ('fun', ['gun.dat', 'nun/pun.dat', '/tmp/sun.dat']), + ... 'bar/cat.dat', + ... '/full/path/to/can.dat') #doctest: +SKIP will install these data files to:: @@ -2068,7 +2068,7 @@ def get_info(pkgname, dirs=None): To get the necessary information for the npymath library from NumPy: >>> npymath_info = np.distutils.misc_util.get_info('npymath') - >>> npymath_info + >>> npymath_info #doctest: +SKIP {'define_macros': [], 'libraries': ['npymath'], 'library_dirs': ['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']} diff --git a/numpy/distutils/system_info.py b/numpy/distutils/system_info.py index d8e1ac0b6..ab375246f 100644 --- a/numpy/distutils/system_info.py +++ b/numpy/distutils/system_info.py @@ -153,11 +153,11 @@ def libpaths(paths,bits): >>> paths = ['/usr/X11R6/lib','/usr/X11/lib','/usr/lib'] For a 32-bit platform, this is already valid: - >>> libpaths(paths,32) + >>> np.distutils.system_info.libpaths(paths,32) ['/usr/X11R6/lib', '/usr/X11/lib', '/usr/lib'] On 64 bits, we prepend the '64' postfix - >>> libpaths(paths,64) + >>> np.distutils.system_info.libpaths(paths,64) ['/usr/X11R6/lib64', '/usr/X11R6/lib', '/usr/X11/lib64', '/usr/X11/lib', '/usr/lib64', '/usr/lib'] """ diff --git a/numpy/doc/__init__.py b/numpy/doc/__init__.py index 85c378182..6589b5492 100644 --- a/numpy/doc/__init__.py +++ b/numpy/doc/__init__.py @@ -20,7 +20,7 @@ The following topics are available: You can view them by ->>> help(np.doc.TOPIC) +>>> help(np.doc.TOPIC) #doctest: +SKIP """ % '\n- '.join([''] + __all__) diff --git a/numpy/doc/basics.py b/numpy/doc/basics.py index d34c1f303..5e7291957 100644 --- a/numpy/doc/basics.py +++ b/numpy/doc/basics.py @@ -67,6 +67,7 @@ functions or methods accept. Some examples:: >>> y array([1, 2, 4]) >>> z = np.arange(3, dtype=np.uint8) + >>> z array([0, 1, 2], dtype=uint8) Array types can also be referred to by character codes, mostly to retain @@ -81,8 +82,8 @@ We recommend using dtype objects instead. To convert the type of an array, use the .astype() method (preferred) or the type itself as a function. For example: :: - >>> z.astype(float) - array([0., 1., 2.]) + >>> z.astype(float) #doctest: +NORMALIZE_WHITESPACE + array([ 0., 1., 2.]) >>> np.int8(z) array([0, 1, 2], dtype=int8) diff --git a/numpy/doc/constants.py b/numpy/doc/constants.py index a4487b72a..adb7c7e02 100644 --- a/numpy/doc/constants.py +++ b/numpy/doc/constants.py @@ -322,20 +322,20 @@ add_newdoc('numpy', 'newaxis', Examples -------- - >>> newaxis is None + >>> np.newaxis is None True >>> x = np.arange(3) >>> x array([0, 1, 2]) - >>> x[:, newaxis] + >>> x[:, np.newaxis] array([[0], [1], [2]]) - >>> x[:, newaxis, newaxis] + >>> x[:, np.newaxis, np.newaxis] array([[[0]], [[1]], [[2]]]) - >>> x[:, newaxis] * x + >>> x[:, np.newaxis] * x array([[0, 0, 0], [0, 1, 2], [0, 2, 4]]) @@ -343,20 +343,20 @@ add_newdoc('numpy', 'newaxis', Outer product, same as ``outer(x, y)``: >>> y = np.arange(3, 6) - >>> x[:, newaxis] * y + >>> x[:, np.newaxis] * y array([[ 0, 0, 0], [ 3, 4, 5], [ 6, 8, 10]]) ``x[newaxis, :]`` is equivalent to ``x[newaxis]`` and ``x[None]``: - >>> x[newaxis, :].shape + >>> x[np.newaxis, :].shape (1, 3) - >>> x[newaxis].shape + >>> x[np.newaxis].shape (1, 3) >>> x[None].shape (1, 3) - >>> x[:, newaxis].shape + >>> x[:, np.newaxis].shape (3, 1) """) diff --git a/numpy/doc/glossary.py b/numpy/doc/glossary.py index f591a5424..dc7c75a0a 100644 --- a/numpy/doc/glossary.py +++ b/numpy/doc/glossary.py @@ -181,7 +181,7 @@ iterable [1, 4, 9] It is often used in combintion with ``enumerate``:: - + >>> keys = ['a','b','c'] >>> for n, k in enumerate(keys): ... print "Key %d: %s" % (n, k) ... @@ -242,13 +242,16 @@ masked array >>> x = np.ma.masked_array([np.nan, 2, np.nan], [True, False, True]) >>> x masked_array(data = [-- 2.0 --], - mask = [ True False True], - fill_value=1e+20) + mask = [ True False True], + fill_value = 1e+20) + <BLANKLINE> >>> x + [1, 2, 3] masked_array(data = [-- 4.0 --], - mask = [ True False True], - fill_value=1e+20) + mask = [ True False True], + fill_value = 1e+20) + <BLANKLINE> + Masked arrays are often used when operating on arrays containing missing or invalid entries. @@ -366,7 +369,7 @@ tuple This is often used when a function returns multiple values: >>> def return_many(): - ... return 1, 'alpha' + ... return 1, 'alpha', None >>> a, b, c = return_many() >>> a, b, c diff --git a/numpy/doc/indexing.py b/numpy/doc/indexing.py index 365edd67a..282f35288 100644 --- a/numpy/doc/indexing.py +++ b/numpy/doc/indexing.py @@ -88,7 +88,7 @@ examples illustrates best: :: >>> x[:-7] array([0, 1, 2]) >>> x[1:7:2] - array([1,3,5]) + array([1, 3, 5]) >>> y = np.arange(35).reshape(5,7) >>> y[1:5:2,::3] array([[ 7, 10, 13], @@ -294,6 +294,9 @@ remaining unspecified dimensions. For example: :: This is equivalent to: :: >>> z[1,:,:,2] + array([[29, 32, 35], + [38, 41, 44], + [47, 50, 53]]) Assigning values to indexed arrays ================================== @@ -304,6 +307,7 @@ assigned to the indexed array must be shape consistent (the same shape or broadcastable to the shape the index produces). For example, it is permitted to assign a constant to a slice: :: + >>> x = np.arange(10) >>> x[2:7] = 1 or an array of the right size: :: @@ -327,7 +331,7 @@ assignments are always made to the original data in the array actions may not work as one may naively expect. This particular example is often surprising to people: :: - >>> x[np.array([1, 1, 3, 1]) += 1 + >>> x[np.array([1, 1, 3, 1])] += 1 Where people expect that the 1st location will be incremented by 3. In fact, it will only be incremented by 1. The reason is because @@ -360,6 +364,7 @@ Slices can be specified within programs by using the slice() function in Python. For example: :: >>> indices = (1,1,1,slice(0,2)) # same as [1,1,1,0:2] + >>> z[indices] array([39, 40]) Likewise, ellipsis can be specified by code by using the Ellipsis object: :: @@ -376,9 +381,10 @@ function directly as an index since it always returns a tuple of index arrays. Because the special treatment of tuples, they are not automatically converted to an array as a list would be. As an example: :: - >>> z[[1,1,1,1]] - ... # produces a large array - >>> z[(1,1,1,1)] - 40 # returns a single value + >>> z[[1,1,1,1]] # produces a large array + array([[[[27, 28, 29], + [30, 31, 32], ... + >>> z[(1,1,1,1)] # returns a single value + 40 """ diff --git a/numpy/doc/misc.py b/numpy/doc/misc.py index eb2dc4395..8575a8e4f 100644 --- a/numpy/doc/misc.py +++ b/numpy/doc/misc.py @@ -13,12 +13,12 @@ original value was) Note: cannot use equality to test NaNs. E.g.: :: + >>> myarr = np.array([1., 0., np.nan, 3.]) >>> np.where(myarr == np.nan) >>> nan == nan # is always False! Use special numpy functions instead. >>> np.nan == np.nan False - >>> myarr = np.array([1., 0., np.nan, 3.]) >>> myarr[myarr == np.nan] = 0. # doesn't work >>> myarr array([ 1., 0., NaN, 3.]) @@ -68,7 +68,7 @@ These behaviors can be set for all kinds of errors or specific ones: :: underflow: floating point underflows Note that integer divide-by-zero is handled by the same machinery. -These behaviors are set on a per-thead basis. +These behaviors are set on a per-thread basis. Examples: ------------ @@ -86,6 +86,7 @@ Examples: >>> def errorhandler(errstr, errflag): ... print "saw stupid error!" >>> np.seterrcall(errorhandler) +<function err_handler at 0x...> >>> j = np.seterr(all='call') >>> np.zeros(5, dtype=np.int32)/0 FloatingPointError: invalid value encountered in divide diff --git a/numpy/doc/structured_arrays.py b/numpy/doc/structured_arrays.py index 59af4eb57..21fdf87ea 100644 --- a/numpy/doc/structured_arrays.py +++ b/numpy/doc/structured_arrays.py @@ -105,7 +105,7 @@ dtype definition (using any of the variants being described here). As an example (using a definition using a list, so see 3) for further details): :: - >>> x = zeros(3, dtype=('i4',[('r','u1'), ('g','u1'), ('b','u1'), ('a','u1')])) + >>> x = np.zeros(3, dtype=('i4',[('r','u1'), ('g','u1'), ('b','u1'), ('a','u1')])) >>> x array([0, 0, 0]) >>> x['r'] @@ -145,6 +145,7 @@ The other dictionary form permitted is a dictionary of name keys with tuple values specifying type, offset, and an optional title. >>> x = np.zeros(3, dtype={'col1':('i1',0,'title 1'), 'col2':('f4',1,'title 2')}) + >>> x array([(0, 0.0), (0, 0.0), (0, 0.0)], dtype=[(('title 1', 'col1'), '|i1'), (('title 2', 'col2'), '>f4')]) diff --git a/numpy/doc/ufuncs.py b/numpy/doc/ufuncs.py index 4819e5268..d6a1cd62a 100644 --- a/numpy/doc/ufuncs.py +++ b/numpy/doc/ufuncs.py @@ -82,7 +82,7 @@ array. A couple examples: :: >>> np.add.accumulate(np.arange(10)) array([ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45]) - >>> np.multiply.accumulate(np.arange(1,9)) + >>> np.multiply.accumulate(np.arange(1,9)) array([ 1, 2, 6, 24, 120, 720, 5040, 40320]) The behavior for multidimensional arrays is the same as for .reduce(), as is the use of the axis keyword). diff --git a/numpy/fft/fftpack.py b/numpy/fft/fftpack.py index a63977912..3e2c0e1e7 100644 --- a/numpy/fft/fftpack.py +++ b/numpy/fft/fftpack.py @@ -154,6 +154,7 @@ def fft(a, n=None, axis=-1): >>> sp = np.fft.fft(np.sin(t)) >>> freq = np.fft.fftfreq(t.shape[-1]) >>> plt.plot(freq, sp.real, freq, sp.imag) + [<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>] >>> plt.show() In this example, real input has an FFT which is Hermitian, i.e., symmetric @@ -233,7 +234,9 @@ def ifft(a, n=None, axis=-1): >>> n[40:60] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20,))) >>> s = np.fft.ifft(n) >>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--') + [<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>] >>> plt.legend(('real', 'imaginary')) + <matplotlib.legend.Legend object at 0x...> >>> plt.show() """ @@ -586,7 +589,7 @@ def fftn(a, s=None, axes=None): Examples -------- - >>> a = mgrid[:3, :3, :3][0] + >>> a = np.mgrid[:3, :3, :3][0] >>> np.fft.fftn(a, axes=(1, 2)) array([[[ 0.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j], @@ -605,10 +608,11 @@ def fftn(a, s=None, axes=None): >>> import matplotlib.pyplot as plt >>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12, - 2 * np.pi * np.arange(200) / 34) + ... 2 * np.pi * np.arange(200) / 34) >>> S = np.sin(X) + np.cos(Y) + np.random.uniform(0, 1, X.shape) >>> FS = np.fft.fftn(S) >>> plt.imshow(np.log(np.abs(np.fft.fftshift(FS))**2)) + <matplotlib.image.AxesImage object at 0x...> >>> plt.show() """ @@ -700,6 +704,7 @@ def ifftn(a, s=None, axes=None): >>> n[60:80, 20:40] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20, 20))) >>> im = np.fft.ifftn(n).real >>> plt.imshow(im) + <matplotlib.image.AxesImage object at 0x...> >>> plt.show() """ diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 76ea08dfb..7253740be 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -112,7 +112,6 @@ def histogram(a, bins=10, range=None, normed=False, weights=None, new=None): (array([ 0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4])) >>> np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3]) (array([1, 4, 1]), array([0, 1, 2, 3])) - ]), array([0, 1, 2, 3])) >>> a = np.arange(5) >>> hist, bin_edges = np.histogram(a, normed=True) @@ -147,7 +146,7 @@ def histogram(a, bins=10, range=None, normed=False, weights=None, new=None): if mn == mx: mn -= 0.5 mx += 0.5 - bins = linspace(mn, mx, bins, endpoint=False) + bins = np.linspace(mn, mx, bins, endpoint=False) else: if normed: raise ValueError, 'Use new=True to pass bin edges explicitly.' @@ -293,7 +292,7 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None): >>> r = np.random.randn(100,3) >>> H, edges = np.histogramdd(r, bins = (5, 8, 4)) >>> H.shape, edges[0].size, edges[1].size, edges[2].size - ((5,8,4), 6, 9, 5) + ((5, 8, 4), 6, 9, 5) """ @@ -791,7 +790,7 @@ def copy(a): ----- This is equivalent to - >>> np.array(a, copy=True) + >>> np.array(a, copy=True) #doctest: +SKIP Examples -------- @@ -1019,7 +1018,7 @@ def interp(x, xp, fp, left=None, right=None): >>> np.interp(2.5, xp, fp) 1.0 >>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp) - array([ 3. , 3. , 2.5, 0.56, 0. ]) + array([ 3. , 3. , 2.5 , 0.56, 0. ]) >>> UNDEF = -99.0 >>> np.interp(3.14, xp, fp, right=UNDEF) -99.0 @@ -1032,7 +1031,9 @@ def interp(x, xp, fp, left=None, right=None): >>> yinterp = np.interp(xvals, x, y) >>> import matplotlib.pyplot as plt >>> plt.plot(x, y, 'o') + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.plot(xvals, yinterp, '-x') + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.show() """ @@ -1161,7 +1162,7 @@ def sort_complex(a): array([ 1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j]) >>> np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j]) - array([ 1.+2.j, 2.-1.j, 3.-5.j, 3.-3.j, 3.+2.j]) + array([ 1.+2.j, 2.-1.j, 3.-3.j, 3.-2.j, 3.+5.j]) """ b = array(a,copy=True) @@ -2041,28 +2042,38 @@ def blackman(M): Plot the window and the frequency response: - >>> from numpy import clip, log10, array, bartlett, linspace - >>> from scipy.fftpack import fft, fftshift + >>> from numpy import clip, log10, array, blackman, linspace + >>> from numpy.fft import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = blackman(51) >>> plt.plot(window) + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Blackman window") + <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") + <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Sample") + <matplotlib.text.Text object at 0x...> >>> plt.show() >>> plt.figure() + <matplotlib.figure.Figure object at 0x...> >>> A = fft(window, 2048) / 25.5 >>> mag = abs(fftshift(A)) >>> freq = linspace(-0.5,0.5,len(A)) >>> response = 20*log10(mag) >>> response = clip(response,-100,100) >>> plt.plot(freq, response) + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Blackman window") + <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Magnitude [dB]") + <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Normalized frequency [cycles per sample]") + <matplotlib.text.Text object at 0x...> >>> plt.axis('tight') + (-0.5, 0.5, -100.0, ...) >>> plt.show() """ @@ -2146,22 +2157,32 @@ def bartlett(M): >>> window = bartlett(51) >>> plt.plot(window) + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Bartlett window") + <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") + <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Sample") + <matplotlib.text.Text object at 0x...> >>> plt.show() >>> plt.figure() + <matplotlib.figure.Figure object at 0x...> >>> A = fft(window, 2048) / 25.5 >>> mag = abs(fftshift(A)) >>> freq = linspace(-0.5,0.5,len(A)) >>> response = 20*log10(mag) >>> response = clip(response,-100,100) >>> plt.plot(freq, response) - >>> plt.title("Frequency response of Blackman window") + [<matplotlib.lines.Line2D object at 0x...>] + >>> plt.title("Frequency response of Bartlett window") + <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Magnitude [dB]") + <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Normalized frequency [cycles per sample]") + <matplotlib.text.Text object at 0x...> >>> plt.axis('tight') + (-0.5, 0.5, -100.0, ...) >>> plt.show() """ @@ -2237,25 +2258,39 @@ def hanning(M): >>> window = np.hanning(51) >>> plt.plot(window) + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Hann window") + <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") + <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Sample") + <matplotlib.text.Text object at 0x...> >>> plt.show() >>> plt.figure() + <matplotlib.figure.Figure object at 0x...> >>> A = fft(window, 2048) / 25.5 >>> mag = abs(fftshift(A)) >>> freq = np.linspace(-0.5,0.5,len(A)) >>> response = 20*np.log10(mag) >>> response = np.clip(response,-100,100) >>> plt.plot(freq, response) + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of the Hann window") + <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Magnitude [dB]") + <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Normalized frequency [cycles per sample]") + <matplotlib.text.Text object at 0x...> >>> plt.axis('tight') + (-0.5, 0.5, -100.0, ...) >>> plt.show() """ + # XXX: this docstring is inconsistent with other filter windows, e.g. + # Blackman and Bartlett - they should all follow the same convention for + # clarity. Either use np. for all numpy members (as above), or import all + # numpy members (as in Blackman and Bartlett examples) if M < 1: return array([]) if M == 1: @@ -2321,27 +2356,37 @@ def hamming(M): Plot the window and the frequency response: - >>> from scipy.fftpack import fft, fftshift + >>> from numpy.fft import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = np.hamming(51) >>> plt.plot(window) + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Hamming window") + <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") + <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Sample") + <matplotlib.text.Text object at 0x...> >>> plt.show() >>> plt.figure() + <matplotlib.figure.Figure object at 0x...> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Hamming window") + <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Magnitude [dB]") + <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Normalized frequency [cycles per sample]") + <matplotlib.text.Text object at 0x...> >>> plt.axis('tight') + (-0.5, 0.5, -100.0, ...) >>> plt.show() """ @@ -2587,27 +2632,37 @@ def kaiser(M,beta): Plot the window and the frequency response: >>> from numpy import clip, log10, array, kaiser, linspace - >>> from scipy.fftpack import fft, fftshift + >>> from numpy.fft import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = kaiser(51, 14) >>> plt.plot(window) + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Kaiser window") + <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") + <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Sample") + <matplotlib.text.Text object at 0x...> >>> plt.show() >>> plt.figure() + <matplotlib.figure.Figure object at 0x...> >>> A = fft(window, 2048) / 25.5 >>> mag = abs(fftshift(A)) >>> freq = linspace(-0.5,0.5,len(A)) >>> response = 20*log10(mag) >>> response = clip(response,-100,100) >>> plt.plot(freq, response) + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Kaiser window") + <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Magnitude [dB]") + <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Normalized frequency [cycles per sample]") + <matplotlib.text.Text object at 0x...> >>> plt.axis('tight') + (-0.5, 0.5, -100.0, ...) >>> plt.show() """ @@ -2674,9 +2729,13 @@ def sinc(x): >>> import matplotlib.pyplot as plt >>> plt.plot(x, np.sinc(x)) + [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Sinc Function") + <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") + <matplotlib.text.Text object at 0x...> >>> plt.xlabel("X") + <matplotlib.text.Text object at 0x...> >>> plt.show() It works in 2-D as well: @@ -2684,6 +2743,7 @@ def sinc(x): >>> x = np.arange(-200., 201.)/50. >>> xx = np.outer(x, x) >>> plt.imshow(np.sinc(xx)) + <matplotlib.image.AxesImage object at 0x...> """ y = pi* where(x == 0, 1.0e-20, x) @@ -3277,7 +3337,7 @@ def append(arr, values, axis=None): >>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0) Traceback (most recent call last): ... - ValueError: arrays must have same number of dimension + ValueError: arrays must have same number of dimensions """ arr = asanyarray(arr) diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py index 450ac4df8..8bbdeae1e 100644 --- a/numpy/lib/index_tricks.py +++ b/numpy/lib/index_tricks.py @@ -462,6 +462,7 @@ class RClass(AxisConcatenator): String integers specify the axis to concatenate along or the minimum number of dimensions to force entries into. + >>> a = np.array([[0, 1, 2], [3, 4, 5]]) >>> np.r_['-1', a, a] # concatenate along last axis array([[0, 1, 2, 0, 1, 2], [3, 4, 5, 3, 4, 5]]) @@ -757,8 +758,8 @@ def fill_diagonal(a, val): Examples -------- - >>> a = zeros((3, 3), int) - >>> fill_diagonal(a, 5) + >>> a = np.zeros((3, 3), int) + >>> np.fill_diagonal(a, 5) >>> a array([[5, 0, 0], [0, 5, 0], @@ -766,8 +767,8 @@ def fill_diagonal(a, val): The same function can operate on a 4-D array: - >>> a = zeros((3, 3, 3, 3), int) - >>> fill_diagonal(a, 4) + >>> a = np.zeros((3, 3, 3, 3), int) + >>> np.fill_diagonal(a, 4) We only show a few blocks for clarity: diff --git a/numpy/lib/io.py b/numpy/lib/io.py index 7d2ac1c0e..66d695b00 100644 --- a/numpy/lib/io.py +++ b/numpy/lib/io.py @@ -734,9 +734,10 @@ def savetxt(fname, X, fmt='%.18e', delimiter=' '): Examples -------- - >>> savetxt('test.out', x, delimiter=',') # X is an array - >>> savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays - >>> savetxt('test.out', x, fmt='%1.4e') # use exponential notation + >>> x = y = z = np.arange(0.0,5.0,1.0) + >>> np.savetxt('test.out', x, delimiter=',') # X is an array + >>> np.savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays + >>> np.savetxt('test.out', x, fmt='%1.4e') # use exponential notation """ @@ -833,7 +834,7 @@ def fromregex(file, regexp, dtype): >>> regexp = r"(\\d+)\\s+(...)" # match [digits, whitespace, anything] >>> output = np.fromregex('test.dat', regexp, - [('num', np.int64), ('key', 'S3')]) + ... [('num', np.int64), ('key', 'S3')]) >>> output array([(1312L, 'foo'), (1534L, 'bar'), (444L, 'qux')], dtype=[('num', '<i8'), ('key', '|S3')]) @@ -974,7 +975,7 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, >>> s = StringIO("1,1.3,abcde") >>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'), - ('mystring','S5')], delimiter=",") + ... ('mystring','S5')], delimiter=",") >>> data array((1, 1.3, 'abcde'), dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')]) @@ -983,7 +984,7 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, >>> s.seek(0) # needed for StringIO example only >>> data = np.genfromtxt(s, dtype=None, - names = ['myint','myfloat','mystring'], delimiter=",") + ... names = ['myint','myfloat','mystring'], delimiter=",") >>> data array((1, 1.3, 'abcde'), dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')]) @@ -992,7 +993,7 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, >>> s.seek(0) >>> data = np.genfromtxt(s, dtype="i8,f8,S5", - names=['myint','myfloat','mystring'], delimiter=",") + ... names=['myint','myfloat','mystring'], delimiter=",") >>> data array((1, 1.3, 'abcde'), dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')]) @@ -1001,7 +1002,7 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, >>> s = StringIO("11.3abcde") >>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'], - delimiter=[1,3,5]) + ... delimiter=[1,3,5]) >>> data array((1, 1.3, 'abcde'), dtype=[('intvar', '<i8'), ('fltvar', '<f8'), ('strvar', '|S5')]) diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py index cf6cd65be..e953f71ba 100644 --- a/numpy/lib/polynomial.py +++ b/numpy/lib/polynomial.py @@ -92,11 +92,17 @@ def poly(seq_of_zeros): Given a sequence of a polynomial's zeros: >>> np.poly((0, 0, 0)) # Multiple root example - array([1, 0, 0, 0]) # i.e., z**3 + 0*z**2 + 0*z + 0 + array([1, 0, 0, 0]) + + The line above represents z**3 + 0*z**2 + 0*z + 0. + >>> np.poly((-1./2, 0, 1./2)) - array([ 1. , 0. , -0.25, 0. ]) # z**3 - z/4 + array([ 1. , 0. , -0.25, 0. ]) + + The line above represents z**3 - z/4 + >>> np.poly((np.random.random(1.)[0], 0, np.random.random(1.)[0])) - array([ 1. , -0.77086955, 0.08618131, 0. ]) + array([ 1. , -0.77086955, 0.08618131, 0. ]) #random Given a square array object: @@ -264,6 +270,7 @@ def polyint(p, m=1, k=None): >>> p = np.poly1d([1,1,1]) >>> P = np.polyint(p) + >>> P poly1d([ 0.33333333, 0.5 , 1. , 0. ]) >>> np.polyder(P) == p True @@ -279,7 +286,7 @@ def polyint(p, m=1, k=None): 0.0 >>> P = np.polyint(p, 3, k=[6,5,3]) >>> P - poly1d([ 0.01666667, 0.04166667, 0.16666667, 3., 5., 3. ]) + poly1d([ 0.01666667, 0.04166667, 0.16666667, 3. , 5. , 3. ]) Note that 3 = 6 / 2!, and that the constants are given in the order of integrations. Constant of the highest-order polynomial term comes first: @@ -484,6 +491,7 @@ def polyfit(x, y, deg, rcond=None, full=False): >>> x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) >>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0]) >>> z = np.polyfit(x, y, 3) + >>> z array([ 0.08703704, -0.81349206, 1.69312169, -0.03968254]) It is convenient to use `poly1d` objects for dealing with polynomials: @@ -512,7 +520,9 @@ def polyfit(x, y, deg, rcond=None, full=False): >>> import matplotlib.pyplot as plt >>> xp = np.linspace(-2, 6, 100) >>> plt.plot(x, y, '.', xp, p(xp), '-', xp, p30(xp), '--') + [<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>] >>> plt.ylim(-2,2) + (-2, 2) >>> plt.show() """ @@ -836,7 +846,7 @@ def polydiv(u, v): >>> x = np.array([3.0, 5.0, 2.0]) >>> y = np.array([2.0, 1.0]) >>> np.polydiv(x, y) - >>> (array([ 1.5 , 1.75]), array([ 0.25])) + (array([ 1.5 , 1.75]), array([ 0.25])) """ truepoly = (isinstance(u, poly1d) or isinstance(u, poly1d)) @@ -930,7 +940,9 @@ class poly1d(object): >>> p.r array([-1.+1.41421356j, -1.-1.41421356j]) >>> p(p.r) - array([ -4.44089210e-16+0.j, -4.44089210e-16+0.j]) # i.e., (0, 0) + array([ -4.44089210e-16+0.j, -4.44089210e-16+0.j]) + + These numbers in the previous line represent (0, 0) to machine precision Show the coefficients: @@ -955,7 +967,7 @@ class poly1d(object): poly1d([ 1, 4, 10, 12, 9]) >>> (p**3 + 4) / p - (poly1d([ 1., 4., 10., 12., 9.]), poly1d([4])) + (poly1d([ 1., 4., 10., 12., 9.]), poly1d([ 4.])) ``asarray(p)`` gives the coefficient array, so polynomials can be used in all functions that accept arrays: diff --git a/numpy/lib/recfunctions.py b/numpy/lib/recfunctions.py index b3eecdc0e..3f99a1ba8 100644 --- a/numpy/lib/recfunctions.py +++ b/numpy/lib/recfunctions.py @@ -50,10 +50,12 @@ def recursive_fill_fields(input, output): Examples -------- + >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, 10.), (2, 20.)], dtype=[('A', int), ('B', float)]) >>> b = np.zeros((3,), dtype=a.dtype) - >>> recursive_fill_fields(a, b) - np.array([(1, 10.), (2, 20.), (0, 0.)], dtype=[('A', int), ('B', float)]) + >>> rfn.recursive_fill_fields(a, b) + array([(1, 10.0), (2, 20.0), (0, 0.0)], + dtype=[('A', '<i4'), ('B', '<f8')]) """ newdtype = output.dtype @@ -81,12 +83,13 @@ def get_names(adtype): Examples -------- - >>> get_names(np.empty((1,), dtype=int)) is None + >>> from numpy.lib import recfunctions as rfn + >>> rfn.get_names(np.empty((1,), dtype=int)) is None True - >>> get_names(np.empty((1,), dtype=[('A',int), ('B', float)])) + >>> rfn.get_names(np.empty((1,), dtype=[('A',int), ('B', float)])) ('A', 'B') >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) - >>> get_names(adtype) + >>> rfn.get_names(adtype) ('a', ('b', ('ba', 'bb'))) """ listnames = [] @@ -112,12 +115,13 @@ def get_names_flat(adtype): Examples -------- - >>> get_names_flat(np.empty((1,), dtype=int)) is None + >>> from numpy.lib import recfunctions as rfn + >>> rfn.get_names_flat(np.empty((1,), dtype=int)) is None True - >>> get_names_flat(np.empty((1,), dtype=[('A',int), ('B', float)])) + >>> rfn.get_names_flat(np.empty((1,), dtype=[('A',int), ('B', float)])) ('A', 'B') >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) - >>> get_names_flat(adtype) + >>> rfn.get_names_flat(adtype) ('a', 'b', 'ba', 'bb') """ listnames = [] @@ -136,8 +140,9 @@ def flatten_descr(ndtype): Examples -------- + >>> from numpy.lib import recfunctions as rfn >>> ndtype = np.dtype([('a', '<i4'), ('b', [('ba', '<f8'), ('bb', '<i4')])]) - >>> flatten_descr(ndtype) + >>> rfn.flatten_descr(ndtype) (('a', dtype('int32')), ('ba', dtype('float64')), ('bb', dtype('int32'))) """ @@ -198,12 +203,13 @@ def get_fieldstructure(adtype, lastname=None, parents=None,): Examples -------- - >>> ndtype = np.dtype([('A', int), + >>> from numpy.lib import recfunctions as rfn + >>> ndtype = np.dtype([('A', int), ... ('B', [('BA', int), ... ('BB', [('BBA', int), ('BBB', int)])])]) - >>> get_fieldstructure(ndtype) - {'A': [], 'B': [], 'BA': ['B'], 'BB': ['B'], - 'BBA': ['B', 'BB'], 'BBB': ['B', 'BB']} + >>> rfn.get_fieldstructure(ndtype) + ... # XXX: possible regression, order of BBA and BBB is swapped + {'A': [], 'B': [], 'BA': ['B'], 'BB': ['B'], 'BBA': ['B', 'BB'], 'BBB': ['B', 'BB']} """ if parents is None: @@ -340,20 +346,33 @@ def merge_arrays(seqarrays, Examples -------- - >>> merge_arrays((np.array([1, 2]), np.array([10., 20., 30.]))) + >>> from numpy.lib import recfunctions as rfn + >>> rfn.merge_arrays((np.array([1, 2]), np.array([10., 20., 30.]))) masked_array(data = [(1, 10.0) (2, 20.0) (--, 30.0)], - mask = [(False, False) (False, False) (True, False)], - fill_value=(999999, 1e+20) - dtype=[('f0', '<i4'), ('f1', '<f8')]) - >>> merge_arrays((np.array([1, 2]), np.array([10., 20., 30.])), + mask = [(False, False) (False, False) (True, False)], + fill_value = (999999, 1e+20), + dtype = [('f0', '<i4'), ('f1', '<f8')]) + + >>> rfn.merge_arrays((np.array([1, 2]), np.array([10., 20., 30.])), ... usemask=False) - array(data = [(1, 10.0) (2, 20.0) (-1, 30.0)], + array([(1, 10.0), (2, 20.0), (-1, 30.0)], dtype=[('f0', '<i4'), ('f1', '<f8')]) - >>> merge_arrays((np.array([1, 2]).view([('a', int)]), - np.array([10., 20., 30.])), - usemask=False, asrecarray=True) - rec.array(data = [(1, 10.0) (2, 20.0) (-1, 30.0)], - dtype=[('a', int), ('f1', '<f8')]) + >>> rfn.merge_arrays((np.array([1, 2]).view([('a', int)]), + ... np.array([10., 20., 30.])), + ... usemask=False, asrecarray=True) + rec.array([(1, 10.0), (2, 20.0), (-1, 30.0)], + dtype=[('a', '<i4'), ('f1', '<f8')]) + + Notes + ----- + * Without a mask, the missing value will be filled with something, + * depending on what its corresponding type: + -1 for integers + -1.0 for floating point numbers + '-' for characters + '-1' for strings + True for boolean values + * XXX: I just obtained these values empirically """ if (len(seqarrays) == 1): seqarrays = seqarrays[0] @@ -436,15 +455,16 @@ def drop_fields(base, drop_names, usemask=True, asrecarray=False): Examples -------- + >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], - dtype=[('a', int), ('b', [('ba', float), ('bb', int)])]) - >>> drop_fields(a, 'a') + ... dtype=[('a', int), ('b', [('ba', float), ('bb', int)])]) + >>> rfn.drop_fields(a, 'a') array([((2.0, 3),), ((5.0, 6),)], dtype=[('b', [('ba', '<f8'), ('bb', '<i4')])]) - >>> drop_fields(a, 'ba') + >>> rfn.drop_fields(a, 'ba') array([(1, (3,)), (4, (6,))], dtype=[('a', '<i4'), ('b', [('bb', '<i4')])]) - >>> drop_fields(a, ['ba', 'bb']) + >>> rfn.drop_fields(a, ['ba', 'bb']) array([(1,), (4,)], dtype=[('a', '<i4')]) """ @@ -500,12 +520,12 @@ def rename_fields(base, namemapper): Examples -------- + >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, (2, [3.0, 30.])), (4, (5, [6.0, 60.]))], - dtype=[('a', int), - ('b', [('ba', float), ('bb', (float, 2))])]) - >>> rename_fields(a, {'a':'A', 'bb':'BB'}) - array([(1, (2.0, 3)), (4, (5.0, 6))], - dtype=[('A', '<i4'), ('b', [('ba', '<f8'), ('BB', '<i4')])]) + ... dtype=[('a', int),('b', [('ba', float), ('bb', (float, 2))])]) + >>> rfn.rename_fields(a, {'a':'A', 'bb':'BB'}) + array([(1, (2.0, [3.0, 30.0])), (4, (5.0, [6.0, 60.0]))], + dtype=[('A', '<i4'), ('b', [('ba', '<f8'), ('BB', '<f8', 2)])]) """ def _recursive_rename_fields(ndtype, namemapper): @@ -650,19 +670,21 @@ def stack_arrays(arrays, defaults=None, usemask=True, asrecarray=False, Examples -------- + >>> from numpy.lib import recfunctions as rfn >>> x = np.array([1, 2,]) - >>> stack_arrays(x) is x + >>> rfn.stack_arrays(x) is x True >>> z = np.array([('A', 1), ('B', 2)], dtype=[('A', '|S3'), ('B', float)]) >>> zz = np.array([('a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)], - dtype=[('A', '|S3'), ('B', float), ('C', float)]) - >>> test = stack_arrays((z,zz)) - >>> masked_array(data = [('A', 1.0, --) ('B', 2.0, --) ('a', 10.0, 100.0) - ... ('b', 20.0, 200.0) ('c', 30.0, 300.0)], - ... mask = [(False, False, True) (False, False, True) (False, False, False) - ... (False, False, False) (False, False, False)], - ... fill_value=('N/A', 1e+20, 1e+20) - ... dtype=[('A', '|S3'), ('B', '<f8'), ('C', '<f8')]) + ... dtype=[('A', '|S3'), ('B', float), ('C', float)]) + >>> test = rfn.stack_arrays((z,zz)) + >>> test + masked_array(data = [('A', 1.0, --) ('B', 2.0, --) ('a', 10.0, 100.0) ('b', 20.0, 200.0) + ('c', 30.0, 300.0)], + mask = [(False, False, True) (False, False, True) (False, False, False) + (False, False, False) (False, False, False)], + fill_value = ('N/A', 1e+20, 1e+20), + dtype = [('A', '|S3'), ('B', '<f8'), ('C', '<f8')]) """ if isinstance(arrays, ndarray): @@ -735,10 +757,12 @@ def find_duplicates(a, key=None, ignoremask=True, return_index=False): Examples -------- + >>> from numpy.lib import recfunctions as rfn >>> ndtype = [('a', int)] - >>> a = ma.array([1, 1, 1, 2, 2, 3, 3], + >>> a = np.ma.array([1, 1, 1, 2, 2, 3, 3], ... mask=[0, 0, 1, 0, 0, 0, 1]).view(ndtype) - >>> find_duplicates(a, ignoremask=True, return_index=True) + >>> rfn.find_duplicates(a, ignoremask=True, return_index=True) + ... # XXX: judging by the output, the ignoremask flag has no effect """ a = np.asanyarray(a).ravel() # Get a dictionary of fields diff --git a/numpy/lib/shape_base.py b/numpy/lib/shape_base.py index f21786805..69fe98314 100644 --- a/numpy/lib/shape_base.py +++ b/numpy/lib/shape_base.py @@ -46,9 +46,9 @@ def apply_along_axis(func1d,axis,arr,*args): ... return (a[0] + a[-1]) * 0.5 >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]]) >>> np.apply_along_axis(my_func, 0, b) - array([4., 5., 6.]) + array([ 4., 5., 6.]) >>> np.apply_along_axis(my_func, 1, b) - array([2., 5., 8.]) + array([ 2., 5., 8.]) For a function that doesn't return a scalar, the number of dimensions in `outarr` is the same as `arr`. @@ -729,7 +729,7 @@ def kron(a,b): >>> J1 = (0,) + J # extend to ndim=4 >>> S1 = (1,) + b.shape >>> K = tuple(np.array(I) * np.array(S1) + np.array(J1)) - >>> C[K] == A[I]*B[J] + >>> c[K] == a[I]*b[J] True """ diff --git a/numpy/lib/tests/test_format.py b/numpy/lib/tests/test_format.py index 35558400f..ec035ca28 100644 --- a/numpy/lib/tests/test_format.py +++ b/numpy/lib/tests/test_format.py @@ -108,7 +108,7 @@ Test the header writing. >>> for arr in basic_arrays + record_arrays: ... f = StringIO() - ... format.write_array_header_1_0(f, arr) + ... format.write_array_header_1_0(f, arr) # XXX: arr is not a dict, items gets called on it ... print repr(f.getvalue()) ... "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (0,)} \n" diff --git a/numpy/lib/twodim_base.py b/numpy/lib/twodim_base.py index 0d53bbb68..40a5aec33 100644 --- a/numpy/lib/twodim_base.py +++ b/numpy/lib/twodim_base.py @@ -52,7 +52,7 @@ def fliplr(m): [ 3., 0., 0.]]) >>> A = np.random.randn(2,3,5) - >>> np.all(numpy.fliplr(A)==A[:,::-1,...]) + >>> np.all(np.fliplr(A)==A[:,::-1,...]) True """ @@ -582,7 +582,7 @@ def histogram2d(x,y, bins=10, range=None, normed=False, weights=None): >>> x, y = np.random.randn(2, 100) >>> H, xedges, yedges = np.histogram2d(x, y, bins=(5, 8)) >>> H.shape, xedges.shape, yedges.shape - ((5,8), (6,), (9,)) + ((5, 8), (6,), (9,)) We can now use the Matplotlib to visualize this 2-dimensional histogram: diff --git a/numpy/lib/type_check.py b/numpy/lib/type_check.py index f11672609..c0a5760a4 100644 --- a/numpy/lib/type_check.py +++ b/numpy/lib/type_check.py @@ -260,7 +260,7 @@ def iscomplexobj(x): False >>> np.iscomplexobj(1+0j) True - np.iscomplexobj([3, 1+0j, True]) + >>> np.iscomplexobj([3, 1+0j, True]) True """ @@ -345,6 +345,7 @@ def nan_to_num(x): Examples -------- + >>> np.set_printoptions(precision=8) >>> x = np.array([np.inf, -np.inf, np.nan, -128, 128]) >>> np.nan_to_num(x) array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, diff --git a/numpy/lib/ufunclike.py b/numpy/lib/ufunclike.py index 5e89b0930..bb8ee7808 100644 --- a/numpy/lib/ufunclike.py +++ b/numpy/lib/ufunclike.py @@ -99,9 +99,9 @@ def isposinf(x, y=None): >>> x = np.array([-np.inf, 0., np.inf]) >>> y = np.array([2, 2, 2]) >>> np.isposinf(x, y) - array([1, 0, 0]) + array([0, 0, 1]) >>> y - array([1, 0, 0]) + array([0, 0, 1]) """ if y is None: diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index 43d6ede1f..3e73c2a0f 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -344,7 +344,7 @@ def who(vardict=None): >>> d = {'x': np.arange(2.0), 'y': np.arange(3.0), 'txt': 'Some str', ... 'idx':5} - >>> np.whos(d) + >>> np.who(d) Name Shape Bytes Type =========================================================== y 3 24 float64 @@ -666,7 +666,7 @@ def source(object, output=sys.stdout): Examples -------- - >>> np.source(np.interp) + >>> np.source(np.interp) #doctest: +SKIP In file: /usr/lib/python2.6/dist-packages/numpy/lib/function_base.py def interp(x, xp, fp, left=None, right=None): \"\"\".... (full docstring printed)\"\"\" @@ -677,7 +677,7 @@ def source(object, output=sys.stdout): The source code is only returned for objects written in Python. - >>> np.source(np.array) + >>> np.source(np.array) #doctest: +SKIP Not available for this object. """ @@ -737,6 +737,8 @@ def lookfor(what, module=None, import_modules=True, regenerate=False, ------------------------------------------ numpy.binary_repr Return the binary representation of the input number as a string. + numpy.core.setup_common.long_double_representation + Given a binary dump as given by GNU od -b, look for long double numpy.base_repr Return a string representation of a number in the given base system. ... @@ -1066,7 +1068,7 @@ def safe_eval(source): ... SyntaxError: invalid syntax - >>> safe_eval('open("/home/user/.ssh/id_dsa").read()') + >>> np.safe_eval('open("/home/user/.ssh/id_dsa").read()') Traceback (most recent call last): ... SyntaxError: Unsupported source construct: compiler.ast.CallFunc diff --git a/numpy/matlib.py b/numpy/matlib.py index 9e80dd475..06bbaa02b 100644 --- a/numpy/matlib.py +++ b/numpy/matlib.py @@ -38,10 +38,10 @@ def empty(shape, dtype=None, order='C'): >>> import numpy.matlib >>> np.matlib.empty((2, 2)) # filled with random data matrix([[ 6.76425276e-320, 9.79033856e-307], - [ 7.39337286e-309, 3.22135945e-309]]) + [ 7.39337286e-309, 3.22135945e-309]]) #random >>> np.matlib.empty((2, 2), dtype=int) matrix([[ 6600475, 0], - [ 6586976, 22740995]]) + [ 6586976, 22740995]]) #random """ return ndarray.__new__(matrix, shape, dtype, order=order) @@ -239,16 +239,16 @@ def rand(*args): >>> import numpy.matlib >>> np.matlib.rand(2, 3) matrix([[ 0.68340382, 0.67926887, 0.83271405], - [ 0.00793551, 0.20468222, 0.95253525]]) + [ 0.00793551, 0.20468222, 0.95253525]]) #random >>> np.matlib.rand((2, 3)) matrix([[ 0.84682055, 0.73626594, 0.11308016], - [ 0.85429008, 0.3294825 , 0.89139555]]) + [ 0.85429008, 0.3294825 , 0.89139555]]) #random If the first argument is a tuple, other arguments are ignored: >>> np.matlib.rand((2, 3), 4) matrix([[ 0.46898646, 0.15163588, 0.95188261], - [ 0.59208621, 0.09561818, 0.00583606]]) + [ 0.59208621, 0.09561818, 0.00583606]]) #random """ if isinstance(args[0], tuple): @@ -289,16 +289,16 @@ def randn(*args): -------- >>> import numpy.matlib >>> np.matlib.randn(1) - matrix([[-0.09542833]]) + matrix([[-0.09542833]]) #random >>> np.matlib.randn(1, 2, 3) matrix([[ 0.16198284, 0.0194571 , 0.18312985], - [-0.7509172 , 1.61055 , 0.45298599]]) + [-0.7509172 , 1.61055 , 0.45298599]]) #random Two-by-four matrix of samples from :math:`N(3, 6.25)`: >>> 2.5 * np.matlib.randn((2, 4)) + 3 matrix([[ 4.74085004, 8.89381862, 4.09042411, 4.83721922], - [ 7.52373709, 5.07933944, -2.64043543, 0.45610557]]) + [ 7.52373709, 5.07933944, -2.64043543, 0.45610557]]) #random """ if isinstance(args[0], tuple): diff --git a/numpy/matrixlib/defmatrix.py b/numpy/matrixlib/defmatrix.py index 34cdaff29..7728ea229 100644 --- a/numpy/matrixlib/defmatrix.py +++ b/numpy/matrixlib/defmatrix.py @@ -647,10 +647,10 @@ class matrix(N.ndarray): >>> x.max() 11 >>> x.max(0) - matrix([[8, 9, 10, 11]]) - >>> x.argmax(1) - matrix([[3], - [7], + matrix([[ 8, 9, 10, 11]]) + >>> x.max(1) + matrix([[ 3], + [ 7], [11]]) """ diff --git a/numpy/testing/noseclasses.py b/numpy/testing/noseclasses.py index 05d244083..aae7c5da4 100644 --- a/numpy/testing/noseclasses.py +++ b/numpy/testing/noseclasses.py @@ -148,6 +148,21 @@ class NumpyOutputChecker(doctest.OutputChecker): if not ret: if "#random" in want: return True + + # it would be useful to normalize endianness so that + # bigendian machines don't fail all the tests (and there are + # actually some bigendian examples in the doctests). Let's try + # making them all little endian + got = got.replace("'>","'<") + want= want.replace("'>","'<") + + # try to normalize out 32 and 64 bit default int sizes + for sz in [4,8]: + got = got.replace("'<i%d'"%sz,"int") + want= want.replace("'<i%d'"%sz,"int") + + ret = doctest.OutputChecker.check_output(self, want, + got, optionflags) return ret diff --git a/numpy/testing/utils.py b/numpy/testing/utils.py index 87ca389f7..abb2956a1 100644 --- a/numpy/testing/utils.py +++ b/numpy/testing/utils.py @@ -381,6 +381,7 @@ def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=True): Examples -------- + >>> import numpy.testing as npt >>> npt.assert_almost_equal(2.3333333333333, 2.33333334) >>> npt.assert_almost_equal(2.3333333333333, 2.33333334, decimal=10) ... |