diff options
Diffstat (limited to 'numpy/core')
-rw-r--r-- | numpy/core/arrayprint.py | 15 | ||||
-rw-r--r-- | numpy/core/code_generators/ufunc_docstrings.py | 323 | ||||
-rw-r--r-- | numpy/core/defmatrix.py | 20 | ||||
-rw-r--r-- | numpy/core/fromnumeric.py | 82 | ||||
-rw-r--r-- | numpy/core/memmap.py | 4 | ||||
-rw-r--r-- | numpy/core/numeric.py | 252 | ||||
-rw-r--r-- | numpy/core/numerictypes.py | 3 |
7 files changed, 540 insertions, 159 deletions
diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py index a3edb64d4..5e5a96b68 100644 --- a/numpy/core/arrayprint.py +++ b/numpy/core/arrayprint.py @@ -56,10 +56,14 @@ def set_printoptions(precision=None, threshold=None, edgeitems=None, suppress : bool, optional Whether or not suppress printing of small floating point values using scientific notation (default False). - nanstr : string, optional - String representation of floating point not-a-number (default nan). - infstr : string, optional - String representation of floating point infinity (default inf). + nanstr : str, optional + String representation of floating point not-a-number (default NaN). + infstr : str, optional + String representation of floating point infinity (default Inf). + + See Also + -------- + get_printoptions, set_string_function Examples -------- @@ -79,12 +83,9 @@ def set_printoptions(precision=None, threshold=None, edgeitems=None, >>> eps = np.finfo(float).eps >>> x = np.arange(4.) - >>> x**2 - (x + eps)**2 array([ -4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00]) - >>> np.set_printoptions(suppress=True) - >>> x**2 - (x + eps)**2 array([-0., -0., 0., 0.]) diff --git a/numpy/core/code_generators/ufunc_docstrings.py b/numpy/core/code_generators/ufunc_docstrings.py index e880f21a2..76bbd3a65 100644 --- a/numpy/core/code_generators/ufunc_docstrings.py +++ b/numpy/core/code_generators/ufunc_docstrings.py @@ -93,6 +93,9 @@ add_newdoc('numpy.core.umath', 'arccos', `x`-coordinate on the unit circle. For real arguments, the domain is [-1, 1]. + out : ndarray, optional + Array to store results in. + Returns ------- angle : ndarray @@ -153,6 +156,8 @@ add_newdoc('numpy.core.umath', 'arccosh', ---------- x : array_like Input array. + out : ndarray, optional + Array of the same shape as `x`. Returns ------- @@ -715,16 +720,44 @@ add_newdoc('numpy.core.umath', 'cos', ---------- x : array_like Input array in radians. + out : ndarray, optional + Output array of same shape as `x`. Returns ------- - out : ndarray - Output array of same shape as `x`. + y : ndarray + The corresponding cosine values. + + Raises + ------ + ValueError: invalid return array shape + if `out` is provided and `out.shape` != `x.shape` (See Examples) + + Notes + ----- + If `out` is provided, the function writes the result into it, + and returns a reference to `out`. (See Examples) + + References + ---------- + M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. + New York, NY: Dover, 1972. Examples -------- >>> np.cos(np.array([0, np.pi/2, np.pi])) array([ 1.00000000e+00, 6.12303177e-17, -1.00000000e+00]) + >>> + >>> # Example of providing the optional output parameter + >>> out2 = np.cos([0.1], out1) + >>> out2 is out1 + True + >>> + >>> # Example of ValueError due to provision of shape mis-matched `out` + >>> np.cos(np.zeros((3,3)),np.zeros((2,2))) + Traceback (most recent call last): + File "<stdin>", line 1, in <module> + ValueError: invalid return array shape """) @@ -903,7 +936,7 @@ add_newdoc('numpy.core.umath', 'equal', add_newdoc('numpy.core.umath', 'exp', """ - Calculate the exponential of the elements in the input array. + Calculate the exponential of all elements in the input array. Parameters ---------- @@ -913,7 +946,12 @@ add_newdoc('numpy.core.umath', 'exp', Returns ------- out : ndarray - Element-wise exponential of `x`. + Output array, element-wise exponential of `x`. + + See Also + -------- + expm1 : Calculate ``exp(x) - 1`` for all elements in the array. + exp2 : Calculate ``2**x`` for all elements in the array. Notes ----- @@ -968,20 +1006,34 @@ add_newdoc('numpy.core.umath', 'exp2', x : array_like Input values. + out : ndarray, optional + \tArray to insert results into. + Returns ------- out : ndarray Element-wise 2 to the power `x`. + See Also + -------- + exp : calculate x**p. + Notes ----- .. versionadded:: 1.3.0 + + + Examples + -------- + >>> np.exp2([2,3]) + array([4,9]) + """) add_newdoc('numpy.core.umath', 'expm1', """ - Compute ``exp(x) - 1`` for all elements in the array. + Calculate ``exp(x) - 1`` for all elements in the array. Parameters ---------- @@ -1621,7 +1673,7 @@ add_newdoc('numpy.core.umath', 'log', add_newdoc('numpy.core.umath', 'log10', """ - Compute the logarithm in base 10 element-wise. + Return the base 10 logarithm of the input array, element-wise. Parameters ---------- @@ -1631,7 +1683,8 @@ add_newdoc('numpy.core.umath', 'log10', Returns ------- y : ndarray - Base-10 logarithm of `x`. + The logarithm to the base 10 of `x`, element-wise. NaNs are + returned where x is negative. Notes ----- @@ -1656,7 +1709,7 @@ add_newdoc('numpy.core.umath', 'log10', Examples -------- - >>> np.log10([1.e-15,-3.]) + >>> np.log10([1e-15, -3.]) array([-15., NaN]) """) @@ -1687,71 +1740,91 @@ add_newdoc('numpy.core.umath', 'log2', add_newdoc('numpy.core.umath', 'logaddexp', """ - Logarithm of `exp(x) + exp(y)`. + Logarithm of the sum of exponentiations of the inputs. - This function is useful in statistics where the calculated probabilities of - events may be so small as to excede the range of normal floating point - numbers. In such cases the logarithm of the calculated probability is - stored. This function allows adding probabilities stored in such a fashion. + Calculates ``log(exp(x1) + exp(x2))``. This function is useful in + statistics where the calculated probabilities of events may be so small + as to exceed the range of normal floating point numbers. In such cases + the logarithm of the calculated probability is stored. This function + allows adding probabilities stored in such a fashion. Parameters ---------- - x : array_like - Input values. - y : array_like + x1, x2 : array_like Input values. - Returns ------- result : ndarray - Logarithm of `exp(x) + exp(y)`. + Logarithm of ``exp(x1) + exp(x2)``. See Also -------- - logaddexp2 + logaddexp2: Logarithm of the sum of exponentiations of inputs in base-2. Notes ----- .. versionadded:: 1.3.0 + Examples + -------- + >>> prob1 = np.log(1e-50) + >>> prob2 = np.log(2.5e-50) + >>> prob12 = np.logaddexp(prob1, prob2) + >>> prob12 + -113.87649168120691 + >>> np.exp(prob12) + 3.5000000000000057e-50 + """) add_newdoc('numpy.core.umath', 'logaddexp2', """ - Base-2 Logarithm of `2**x + 2**y`. + Logarithm of the sum of exponentiations of the inputs in base-2. - This function is useful in machine learning when the calculated probabilities of - events may be so small as to excede the range of normal floating point - numbers. In such cases the base-2 logarithm of the calculated probability - can be used instead. This function allows adding probabilities stored in such a fashion. + Calculates ``log2(2**x1 + 2**x2)``. This function is useful in machine + learning when the calculated probabilities of events may be so small + as to exceed the range of normal floating point numbers. In such cases + the base-2 logarithm of the calculated probability can be used instead. + This function allows adding probabilities stored in such a fashion. Parameters ---------- - x : array_like - Input values. - y : array_like + x1, x2 : array_like Input values. - + out : ndarray, optional + Array to store results in. Returns ------- result : ndarray - Base-2 logarithm of `2**x + 2**y`. + Base-2 logarithm of ``2**x1 + 2**x2``. See Also -------- - logaddexp + logaddexp: Logarithm of the sum of exponentiations of the inputs. Notes ----- .. versionadded:: 1.3.0 + Examples + -------- + >>> prob1 = np.log2(1e-50) + >>> prob2 = np.log2(2.5e-50) + >>> prob12 = np.logaddexp2(prob1, prob2) + >>> prob1, prob2, prob12 + (-166.09640474436813, -164.77447664948076, -164.28904982231052) + >>> 2**prob12 + 3.4999999999999914e-50 + """) add_newdoc('numpy.core.umath', 'log1p', """ - `log(1 + x)` in base `e`, elementwise. + Return the natural logarithm of one plus the input array, element-wise. + + Calculates ``log(1 + x)``. Parameters ---------- @@ -1761,7 +1834,11 @@ add_newdoc('numpy.core.umath', 'log1p', Returns ------- y : ndarray - Natural logarithm of `1 + x`, elementwise. + Natural logarithm of `1 + x`, element-wise. + + See Also + -------- + expm1 : ``exp(x) - 1``, the inverse of `log1p`. Notes ----- @@ -2022,8 +2099,6 @@ add_newdoc('numpy.core.umath', 'minimum', add_newdoc('numpy.core.umath', 'fmax', """ - fmax(x1, x2[, out]) - Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise @@ -2132,7 +2207,7 @@ add_newdoc('numpy.core.umath', 'fmin', add_newdoc('numpy.core.umath', 'modf', """ - Return the fractional and integral part of a number. + Return the fractional and integral parts of an array, element-wise. The fractional and integral parts are negative if the given number is negative. @@ -2140,7 +2215,7 @@ add_newdoc('numpy.core.umath', 'modf', Parameters ---------- x : array_like - Input number. + Input array. Returns ------- @@ -2149,33 +2224,37 @@ add_newdoc('numpy.core.umath', 'modf', y2 : ndarray Integral part of `x`. + Notes + ----- + For integer input the return values are floats. + Examples -------- - >>> np.modf(2.5) - (0.5, 2.0) - >>> np.modf(-.4) - (-0.40000000000000002, -0.0) + >>> np.modf([0, 3.5]) + (array([ 0. , 0.5]), array([ 0., 3.])) + >>> np.modf(-0.5) + (-0.5, -0) """) add_newdoc('numpy.core.umath', 'multiply', """ - Multiply arguments elementwise. + Multiply arguments element-wise. Parameters ---------- x1, x2 : array_like - The arrays to be multiplied. + Input arrays to be multiplied. Returns ------- y : ndarray - The product of `x1` and `x2`, elementwise. Returns a scalar if + The product of `x1` and `x2`, element-wise. Returns a scalar if both `x1` and `x2` are scalars. Notes ----- - Equivalent to `x1` * `x2` in terms of array-broadcasting. + Equivalent to `x1` * `x2` in terms of array broadcasting. Examples -------- @@ -2353,23 +2432,34 @@ add_newdoc('numpy.core.umath', 'deg2rad', add_newdoc('numpy.core.umath', 'reciprocal', """ - Return element-wise reciprocal. + Return the reciprocal of the argument, element-wise. + + Calculates ``1/x``. Parameters ---------- x : array_like - Input value. + Input array. Returns ------- y : ndarray - Return value. + Return array. + + Notes + ----- + .. note:: + This function is not designed to work with integers. + + For integer arguments with absolute value larger than 1 the result is + always zero because of the way Python handles integer division. + For integer zero the result is an overflow. Examples -------- - >>> reciprocal(2.) + >>> np.reciprocal(2.) 0.5 - >>> reciprocal([1, 2., 3.33]) + >>> np.reciprocal([1, 2., 3.33]) array([ 1. , 0.5 , 0.3003003]) """) @@ -2378,7 +2468,7 @@ add_newdoc('numpy.core.umath', 'remainder', """ Returns element-wise remainder of division. - Computes `x1 - floor(x1/x2)*x2`. + Computes ``x1 - floor(x1/x2)*x2``. Parameters ---------- @@ -2390,22 +2480,23 @@ add_newdoc('numpy.core.umath', 'remainder', Returns ------- y : ndarray - The remainder of the quotient `x1/x2`, element-wise. Returns a scalar + The remainder of the quotient ``x1/x2``, element-wise. Returns a scalar if both `x1` and `x2` are scalars. See Also -------- - divide - floor + divide, floor Notes ----- - Returns 0 when `x2` is 0. + Returns 0 when `x2` is 0 and both `x1` and `x2` are (arrays of) integers. Examples -------- - >>> np.remainder([4,7],[2,3]) + >>> np.remainder([4,7], [2,3]) array([0, 1]) + >>> np.remainder(np.arange(7), 5) + array([0, 1, 2, 3, 4, 0, 1]) """) @@ -2590,11 +2681,50 @@ add_newdoc('numpy.core.umath', 'sinh', ---------- x : array_like Input array. + out : ndarray, optional + Output array of same shape as `x`. Returns ------- - out : ndarray - Output array of same shape as `x`. + y : ndarray + The corresponding hyperbolic sine values. + + Raises + ------ + ValueError: invalid return array shape + if `out` is provided and `out.shape` != `x.shape` (See Examples) + + Notes + ----- + If `out` is provided, the function writes the result into it, + and returns a reference to `out`. (See Examples) + + References + ---------- + M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. + New York, NY: Dover, 1972, pg. 83. + + Examples + -------- + >>> import numpy as np + >>> np.sinh(0) + 0.0 + >>> np.sinh(np.pi*1j/2) + 1j + >>> np.sinh(np.pi*1j) + 1.2246063538223773e-016j (exact value is 0) + >>> # Discrepancy due to vagaries of floating point arithmetic. + >>> + >>> # Example of providing the optional output parameter + >>> out2 = np.sinh([0.1], out1) + >>> out2 is out1 + True + >>> + >>> # Example of ValueError due to provision of shape mis-matched `out` + >>> np.sinh(np.zeros((3,3)),np.zeros((2,2))) + Traceback (most recent call last): + File "<stdin>", line 1, in <module> + ValueError: invalid return array shape """) @@ -2667,13 +2797,12 @@ add_newdoc('numpy.core.umath', 'square', add_newdoc('numpy.core.umath', 'subtract', """ - Subtract arguments element-wise. + Subtract arguments, element-wise. Parameters ---------- x1, x2 : array_like - The arrays to be subtracted from each other. If type is 'array_like' - the `x1` and `x2` shapes must be identical. + The arrays to be subtracted from each other. Returns ------- @@ -2683,7 +2812,7 @@ add_newdoc('numpy.core.umath', 'subtract', Notes ----- - Equivalent to `x1` - `x2` in terms of array-broadcasting. + Equivalent to ``x1 - x2`` in terms of array broadcasting. Examples -------- @@ -2703,39 +2832,107 @@ add_newdoc('numpy.core.umath', 'tan', """ Compute tangent element-wise. + Equivalent to ``np.sin(x)/np.cos(x)`` element-wise. + Parameters ---------- x : array_like - Angles in radians. + Input array. + out : ndarray, optional + Output array of same shape as `x`. Returns ------- y : ndarray The corresponding tangent values. + Raises + ------ + ValueError: invalid return array shape + if `out` is provided and `out.shape` != `x.shape` (See Examples) + + Notes + ----- + If `out` is provided, the function writes the result into it, + and returns a reference to `out`. (See Examples) + + References + ---------- + M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. + New York, NY: Dover, 1972. Examples -------- >>> from math import pi >>> np.tan(np.array([-pi,pi/2,pi])) array([ 1.22460635e-16, 1.63317787e+16, -1.22460635e-16]) + >>> + >>> # Example of providing the optional output parameter illustrating + >>> # that what is returned is a reference to said parameter + >>> out2 = np.cos([0.1], out1) + >>> out2 is out1 + True + >>> + >>> # Example of ValueError due to provision of shape mis-matched `out` + >>> np.cos(np.zeros((3,3)),np.zeros((2,2))) + Traceback (most recent call last): + File "<stdin>", line 1, in <module> + ValueError: invalid return array shape """) add_newdoc('numpy.core.umath', 'tanh', """ - Hyperbolic tangent element-wise. + Compute hyperbolic tangent element-wise. + + Equivalent to ``np.sinh(x)/np.cosh(x)`` or + ``-1j * np.tan(1j*x)``. Parameters ---------- x : array_like Input array. + out : ndarray, optional + Output array of same shape as `x`. Returns ------- y : ndarray The corresponding hyperbolic tangent values. + Raises + ------ + ValueError: invalid return array shape + if `out` is provided and `out.shape` != `x.shape` (See Examples) + + Notes + ----- + If `out` is provided, the function writes the result into it, + and returns a reference to `out`. (See Examples) + + References + ---------- + M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. + New York, NY: Dover, 1972, pg. 83. + + Examples + -------- + >>> import numpy as np + >>> np.tanh((0, np.pi*1j, np.pi*1j/2)) + array([ 0. +0.00000000e+00j, 0. -1.22460635e-16j, 0. +1.63317787e+16j]) + >>> + >>> # Example of providing the optional output parameter illustrating + >>> # that what is returned is a reference to said parameter + >>> out2 = np.tanh([0.1], out1) + >>> out2 is out1 + True + >>> + >>> # Example of ValueError due to provision of shape mis-matched `out` + >>> np.tanh(np.zeros((3,3)),np.zeros((2,2))) + Traceback (most recent call last): + File "<stdin>", line 1, in <module> + ValueError: invalid return array shape + """) add_newdoc('numpy.core.umath', 'true_divide', diff --git a/numpy/core/defmatrix.py b/numpy/core/defmatrix.py index d1636e8b5..cbb338469 100644 --- a/numpy/core/defmatrix.py +++ b/numpy/core/defmatrix.py @@ -490,6 +490,26 @@ class matrix(N.ndarray): return N.ndarray.prod(self, axis, dtype, out)._align(axis) def any(self, axis=None, out=None): + """ + Test whether any array element along a given axis evaluates to True. + + Refer to `numpy.any` for full documentation. + + Parameters + ---------- + axis: int, optional + Axis along which logical OR is performed + out: ndarray, optional + Output to existing array instead of creating new one, must have + same shape as expected output + + Returns + ------- + any : bool, ndarray + Returns a single bool if `axis` is ``None``; otherwise, + returns `ndarray` + + """ return N.ndarray.any(self, axis, out)._align(axis) def all(self, axis=None, out=None): diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py index 99b837ba2..176ef3e6f 100644 --- a/numpy/core/fromnumeric.py +++ b/numpy/core/fromnumeric.py @@ -256,15 +256,14 @@ def repeat(a, repeats, axis=None): def put(a, ind, v, mode='raise'): """ - Changes specific elements of one array by replacing from another array. + Replaces specified elements of an array with given values. - The indexing works on the flattened target array, `put` is roughly + The indexing works on the flattened target array. `put` is roughly equivalent to: :: - for i, val in zip(ind, v): - x.flat[i] = val + a.flat[ind] = v Parameters ---------- @@ -292,14 +291,14 @@ def put(a, ind, v, mode='raise'): Examples -------- - >>> x = np.arange(5) - >>> np.put(x, [0, 2], [-44, -55]) - >>> x + >>> a = np.arange(5) + >>> np.put(a, [0, 2], [-44, -55]) + >>> a array([-44, 1, -55, 3, 4]) - >>> x = np.arange(5) - >>> np.put(x, 22, -5, mode='clip') - >>> x + >>> a = np.arange(5) + >>> np.put(a, 22, -5, mode='clip') + >>> a array([ 0, 1, 2, 3, -5]) """ @@ -1086,10 +1085,14 @@ def compress(condition, a, axis=None, out=None): """ Return selected slices of an array along given axis. + When working along a given axis, a slice along that axis is returned in + `output` for each index where `condition` evaluates to True. When + working on a 1-D array, `compress` is equivalent to `extract`. + Parameters ---------- - condition : array_like - Boolean 1-D array selecting which entries to return. If len(condition) + condition : 1-D array of bools + Array that selects which entries to return. If len(condition) is less than the size of `a` along the given axis, then output is truncated to the length of the condition array. a : array_like @@ -1109,18 +1112,31 @@ def compress(condition, a, axis=None, out=None): See Also -------- - ndarray.compress: Equivalent method. + take, choose, diag, diagonal, select + ndarray.compress : Equivalent method. Examples -------- - >>> a = np.array([[1, 2], [3, 4]]) + >>> a = np.array([[1, 2], [3, 4], [5, 6]]) + >>> a + array([[1, 2], + [3, 4], + [5, 6]]) >>> np.compress([0, 1], a, axis=0) array([[3, 4]]) - >>> np.compress([1], a, axis=1) - array([[1], - [3]]) - >>> np.compress([0,1,1], a) - array([2, 3]) + >>> np.compress([False, True, True], a, axis=0) + array([[3, 4], + [5, 6]]) + >>> np.compress([False, True], a, axis=1) + array([[2], + [4], + [6]]) + + Working on the flattened array does not return slices along an axis but + selects elements. + + >>> np.compress([False, True], a) + array([2]) """ try: @@ -1306,6 +1322,8 @@ def any(a,axis=None, out=None): """ Test whether any array element along a given axis evaluates to True. + Returns single boolean unless `axis` is not ``None`` + Parameters ---------- a : array_like @@ -1322,8 +1340,8 @@ def any(a,axis=None, out=None): Returns ------- - any : ndarray, bool - A new boolean or array is returned unless `out` is + any : bool, ndarray + A new boolean or `ndarray` is returned unless `out` is specified, in which case a reference to `out` is returned. See Also @@ -1429,12 +1447,10 @@ def cumsum (a, axis=None, dtype=None, out=None): Parameters ---------- a : array_like - Input array or object that can be converted to an array. + Input array. axis : int, optional Axis along which the cumulative sum is computed. The default - (`axis` = `None`) is to compute the cumsum over the flattened - array. `axis` may be negative, in which case it counts from the - last to the first axis. + (None) is to compute the cumsum over the flattened array. dtype : dtype, optional Type of the returned array and of the accumulator in which the elements are summed. If `dtype` is not specified, it defaults @@ -1459,11 +1475,12 @@ def cumsum (a, axis=None, dtype=None, out=None): Examples -------- - >>> a = np.array([[1,2,3],[4,5,6]]) + >>> a = np.array([[1,2,3], [4,5,6]]) >>> np.cumsum(a) array([ 1, 3, 6, 10, 15, 21]) - >>> np.cumsum(a,dtype=float) # specifies type of output value(s) + >>> np.cumsum(a, dtype=float) # specifies type of output value(s) array([ 1., 3., 6., 10., 15., 21.]) + >>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns array([[1, 2, 3], [5, 7, 9]]) @@ -2122,14 +2139,13 @@ def std(a, axis=None, dtype=None, out=None, ddof=0): Returns ------- - standard_deviation : {ndarray, scalar}; see dtype parameter above. + standard_deviation : ndarray, see dtype parameter above. If `out` is None, return a new array containing the standard deviation, otherwise return a reference to the output array. See Also -------- - numpy.var : Variance - numpy.mean : Average + var, mean Notes ----- @@ -2145,7 +2161,7 @@ def std(a, axis=None, dtype=None, out=None, ddof=0): is the square root of the estimated variance, so even with ``ddof=1``, it will not be an unbiased estimate of the standard deviation per se. - Note that, for complex numbers, std takes the absolute + Note that, for complex numbers, `std` takes the absolute value before squaring, so that the result is always real and nonnegative. Examples @@ -2153,9 +2169,9 @@ def std(a, axis=None, dtype=None, out=None, ddof=0): >>> a = np.array([[1, 2], [3, 4]]) >>> np.std(a) 1.1180339887498949 - >>> np.std(a, 0) + >>> np.std(a, axis=0) array([ 1., 1.]) - >>> np.std(a, 1) + >>> np.std(a, axis=1) array([ 0.5, 0.5]) """ diff --git a/numpy/core/memmap.py b/numpy/core/memmap.py index 65f4938fe..2392c3aa7 100644 --- a/numpy/core/memmap.py +++ b/numpy/core/memmap.py @@ -17,7 +17,7 @@ mode_equivalents = { class memmap(ndarray): """ - Create a memory-map to an array stored in a file on disk. + Create a memory-map to an array stored in a *binary* file on disk. Memory-mapped files are used for accessing small segments of large files on disk, without reading the entire file into memory. Numpy's @@ -58,7 +58,7 @@ class memmap(ndarray): order : {'C', 'F'}, optional Specify the order of the ndarray memory layout: C (row-major) or Fortran (column-major). This only has an effect if the shape is - greater than 1-D. The defaullt order is 'C'. + greater than 1-D. The default order is 'C'. Methods ------- diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 50e3fd75b..aacd476b6 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -362,24 +362,52 @@ def require(a, dtype=None, requirements=None): Parameters ---------- a : array_like - The object to be converted to a type-and-requirement satisfying array + The object to be converted to a type-and-requirement-satisfying array. dtype : data-type - The required data-type (None is the default data-type -- float64) - requirements : list of strings + The required data-type, the default data-type is float64). + requirements : str or list of str The requirements list can be any of the following - * 'ENSUREARRAY' ('E') - ensure that a base-class ndarray * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array * 'ALIGNED' ('A') - ensure a data-type aligned array - * 'WRITEABLE' ('W') - ensure a writeable array + * 'WRITEABLE' ('W') - ensure a writable array * 'OWNDATA' ('O') - ensure an array that owns its own data + See Also + -------- + asarray : Convert input to an ndarray. + asanyarray : Convert to an ndarray, but pass through ndarray subclasses. + ascontiguousarray : Convert input to a contiguous array. + asfortranarray : Convert input to an ndarray with column-major + memory order. + ndarray.flags : Information about the memory layout of the array. + Notes ----- The returned array will be guaranteed to have the listed requirements by making a copy if needed. + Examples + -------- + >>> x = np.arange(6).reshape(2,3) + >>> x.flags + C_CONTIGUOUS : True + F_CONTIGUOUS : False + OWNDATA : False + WRITEABLE : True + ALIGNED : True + UPDATEIFCOPY : False + + >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F']) + >>> y.flags + C_CONTIGUOUS : False + F_CONTIGUOUS : True + OWNDATA : True + WRITEABLE : True + ALIGNED : True + UPDATEIFCOPY : False + """ if requirements is None: requirements = [] @@ -582,6 +610,16 @@ def correlate(a,v,mode='valid'): acorrelate: Discrete correlation following the usual signal processing definition for complex arrays, and without assuming that correlate(a, b) == correlate(b, a) + + Examples + -------- + >>> np.correlate([1, 2, 3], [0, 1, 0.5]) + array([ 3.5]) + >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same") + array([ 2. , 3.5, 3. ]) + >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full") + array([ 0.5, 2. , 3.5, 3. , 0. ]) + """ mode = _mode_from_name(mode) return multiarray.correlate(a,v,mode) @@ -591,9 +629,9 @@ def acorrelate(a, v, mode='valid'): Discrete, linear correlation of two 1-dimensional sequences. This function computes the correlation as generally defined in signal - processing texts: + processing texts:: - z[k] = sum_n a[n] * conj(v[n+k]) + z[k] = sum_n a[n] * conj(v[n+k]) with a and v sequences being zero-padded where necessary and conj being the conjugate. @@ -606,15 +644,16 @@ def acorrelate(a, v, mode='valid'): Refer to the `convolve` docstring. Note that the default is `valid`, unlike `convolve`, which uses `full`. - Note - ---- - This is the function which corresponds to matlab xcorr. - See Also -------- convolve : Discrete, linear convolution of two one-dimensional sequences. correlate: Deprecated function to compute correlation + + Notes + ----- + This is the function which corresponds to matlab xcorr. + """ mode = _mode_from_name(mode) return multiarray.acorrelate(a, v, mode) @@ -1170,20 +1209,26 @@ def array_repr(arr, max_line_width=None, precision=None, suppress_small=None): Parameters ---------- arr : ndarray - Input array. - max_line_width : int - The maximum number of columns the string should span. Newline - characters splits the string appropriately after array elements. - precision : int - Floating point precision. - suppress_small : bool - Represent very small numbers as zero. + Input array. + max_line_width : int, optional + The maximum number of columns the string should span. Newline + characters split the string appropriately after array elements. + precision : int, optional + Floating point precision. Default is the current printing precision + (usually 8), which can be altered using `set_printoptions`. + suppress_small : bool, optional + Represent very small numbers as zero, default is False. Very small + is defined by `precision`, if the precision is 8 then + numbers smaller than 5e-9 are represented as zero. Returns ------- string : str The string representation of an array. + See Also + -------- + array_str, array2string, set_printoptions Examples -------- @@ -1194,6 +1239,10 @@ def array_repr(arr, max_line_width=None, precision=None, suppress_small=None): >>> np.array_repr(np.array([], np.int32)) 'array([], dtype=int32)' + >>> x = np.array([1e-6, 4e-7, 2, 3]) + >>> np.array_repr(x, precision=6, suppress_small=True) + 'array([ 0.000001, 0. , 2. , 3. ])' + """ if arr.size > 0 or arr.shape==(0,): lst = array2string(arr, max_line_width, precision, suppress_small, @@ -1221,7 +1270,11 @@ def array_repr(arr, max_line_width=None, precision=None, suppress_small=None): def array_str(a, max_line_width=None, precision=None, suppress_small=None): """ - Return a string representation of an array. + Return a string representation of the data in an array. + + The data in the array is returned as a single string. This function + is similar to `array_repr`, the difference is that `array_repr` also + returns information on the type of array and data type. Parameters ---------- @@ -1230,13 +1283,16 @@ def array_str(a, max_line_width=None, precision=None, suppress_small=None): max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. precision : int, optional - If `a` is float, `precision` sets floating point precision. - suppress_small : boolean, optional - Represent very small numbers as zero. + Floating point precision. Default is the current printing precision + (usually 8), which can be altered using set_printoptions. + suppress_small : bool, optional + Represent very small numbers as zero, default is False. Very small is + defined by precision, if the precision is 8 then numbers smaller than + 5e-9 are represented as zero. See Also -------- - array2string, array_repr + array2string, array_repr, set_printoptions Examples -------- @@ -1264,8 +1320,8 @@ def indices(dimensions, dtype=int): ---------- dimensions : sequence of ints The shape of the grid. - dtype : optional - Data_type of the result. + dtype : dtype, optional + Data type of the result. Returns ------- @@ -1291,7 +1347,7 @@ def indices(dimensions, dtype=int): Examples -------- - >>> grid = np.indices((2,3)) + >>> grid = np.indices((2, 3)) >>> grid.shape (2,2,3) >>> grid[0] # row indices @@ -1301,6 +1357,17 @@ def indices(dimensions, dtype=int): array([[0, 1, 2], [0, 1, 2]]) + The indices can be used as an index into an array. + + >>> x = np.arange(20).reshape(5, 4) + >>> row, col = np.indices((2, 3)) + >>> x[row, col] + array([[0, 1, 2], + [4, 5, 6]]) + + Note that it would be more straightforward in the above example to + extract the required elements directly with ``x[:2, :3]``. + """ dimensions = tuple(dimensions) N = len(dimensions) @@ -1816,22 +1883,24 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): Parameters ---------- - all : {'ignore', 'warn', 'raise', 'call'}, optional + all : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Set treatment for all types of floating-point errors at once: - - ignore: Take no action when the exception occurs - - warn: Print a `RuntimeWarning` (via the Python `warnings` module) - - raise: Raise a `FloatingPointError` + - ignore: Take no action when the exception occurs. + - warn: Print a `RuntimeWarning` (via the Python `warnings` module). + - raise: Raise a `FloatingPointError`. - call: Call a function specified using the `seterrcall` function. + - print: Print a warning directly to ``stdout``. + - log: Record error in a Log object specified by `seterrcall`. The default is not to change the current behavior. - divide : {'ignore', 'warn', 'raise', 'call'}, optional + divide : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Treatment for division by zero. - over : {'ignore', 'warn', 'raise', 'call'}, optional + over : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Treatment for floating-point overflow. - under : {'ignore', 'warn', 'raise', 'call'}, optional + under : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Treatment for floating-point underflow. - invalid : {'ignore', 'warn', 'raise', 'call'}, optional + invalid : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Treatment for invalid floating-point operation. Returns @@ -1859,22 +1928,25 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): Examples -------- - - Set mode: - - >>> seterr(over='raise') # doctest: +SKIP + >>> 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'} - >>> old_settings = seterr(all='warn', over='raise') # doctest: +SKIP - - >>> int16(32000) * int16(3) # doctest: +SKIP + >>> np.int16(32000) * np.int16(3) + 30464 + >>> old_settings = np.seterr(all='warn', over='raise') + >>> np.int16(32000) * np.int16(3) Traceback (most recent call last): - File "<stdin>", line 1, in ? + File "<stdin>", line 1, in <module> FloatingPointError: overflow encountered in short_scalars - >>> seterr(all='ignore') # doctest: +SKIP - {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', - 'under': 'ignore'} + + >>> np.seterr(all='print') + {'over': 'print', 'divide': 'print', 'invalid': 'print', 'under': 'print'} + >>> np.int16(32000) * np.int16(3) + Warning: overflow encountered in short_scalars + 30464 """ @@ -1897,11 +1969,41 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): def geterr(): - """Get the current way of handling floating-point errors. + """ + Get the current way of handling floating-point errors. + + Returns + ------- + res : dict + A dictionary with keys "divide", "over", "under", and "invalid", + whose values are from the strings "ignore", "print", "log", "warn", + "raise", and "call". The keys represent possible floating-point + exceptions, and the values define how these exceptions are handled. + + See Also + -------- + geterrcall, seterr, seterrcall + + Notes + ----- + For complete documentation of the types of floating-point exceptions and + treatment options, see `seterr`. + + Examples + -------- + >>> np.geterr() # default is all set to 'ignore' + {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', + 'under': 'ignore'} + >>> np.arange(3.) / np.arange(3.) + array([ NaN, 1., 1.]) + + >>> oldsettings = np.seterr(all='warn', over='raise') + >>> np.geterr() + {'over': 'raise', 'divide': 'warn', 'invalid': 'warn', 'under': 'warn'} + >>> np.arange(3.) / np.arange(3.) + __main__:1: RuntimeWarning: invalid value encountered in divide + array([ NaN, 1., 1.]) - Returns a dictionary with entries "divide", "over", "under", and - "invalid", whose values are from the strings - "ignore", "print", "log", "warn", "raise", and "call". """ maskvalue = umath.geterrobj()[1] mask = 7 @@ -1952,13 +2054,13 @@ def seterrcall(func): is to set the error-handler to 'call', using `seterr`. Then, set the function to call using this function. - The second is to set the error-handler to `log`, using `seterr`. + The second is to set the error-handler to 'log', using `seterr`. Floating-point errors then trigger a call to the 'write' method of the provided object. Parameters ---------- - log_func_or_obj : callable f(err, flag) or object with write method + func : callable f(err, flag) or object with write method Function to call upon floating-point errors ('call'-mode) or object whose 'write' method is used to log such message ('log'-mode). @@ -1971,7 +2073,7 @@ def seterrcall(func): In other words, ``flags = divide + 2*over + 4*under + 8*invalid``. - If an object is provided, it's write method should take one argument, + If an object is provided, its write method should take one argument, a string. Returns @@ -1979,6 +2081,10 @@ def seterrcall(func): h : callable or log instance The old error handler. + See Also + -------- + seterr, geterr, geterrcall + Examples -------- Callback upon error: @@ -2025,7 +2131,45 @@ def seterrcall(func): return old def geterrcall(): - """Return the current callback function used on floating-point errors. + """ + Return the current callback function used on floating-point errors. + + When the error handling for a floating-point error (one of "divide", + "over", "under", or "invalid") is set to 'call' or 'log', the function + that is called or the log instance that is written to is returned by + `geterrcall`. This function or log instance has been set with + `seterrcall`. + + Returns + ------- + errobj : callable, log instance or None + The current error handler. If no handler was set through `seterrcall`, + ``None`` is returned. + + See Also + -------- + seterrcall, seterr, geterr + + Notes + ----- + For complete documentation of the types of floating-point exceptions and + treatment options, see `seterr`. + + Examples + -------- + >>> np.geterrcall() # we did not yet set a handler, returns None + + >>> oldsettings = np.seterr(all='call') + >>> def err_handler(type, flag): + ... print "Floating point error (%s), with flag %s" % (type, flag) + >>> oldhandler = np.seterrcall(err_handler) + >>> np.array([1,2,3])/0.0 + Floating point error (divide by zero), with flag 1 + array([ Inf, Inf, Inf]) + >>> cur_handler = np.geterrcall() + >>> cur_handler is err_handler + True + """ return umath.geterrobj()[2] diff --git a/numpy/core/numerictypes.py b/numpy/core/numerictypes.py index 3d34ceb7f..e773c77ae 100644 --- a/numpy/core/numerictypes.py +++ b/numpy/core/numerictypes.py @@ -517,6 +517,9 @@ def issubdtype(arg1, arg2): arg2 : dtype_like dtype or string representing a typecode. + Returns + ------- + out : bool See Also -------- |