diff options
Diffstat (limited to 'numpy')
-rw-r--r-- | numpy/add_newdocs.py | 77 | ||||
-rw-r--r-- | numpy/core/code_generators/ufunc_docstrings.py | 443 | ||||
-rw-r--r-- | numpy/core/include/numpy/npy_common.h | 10 | ||||
-rw-r--r-- | numpy/core/src/multiarray/number.c | 47 | ||||
-rw-r--r-- | numpy/core/src/multiarray/scalartypes.c.src | 14 | ||||
-rw-r--r-- | numpy/core/src/umath/loops.c.src | 8 | ||||
-rw-r--r-- | numpy/core/src/umath/simd.inc.src | 43 | ||||
-rw-r--r-- | numpy/core/src/umath/umathmodule.c | 96 | ||||
-rw-r--r-- | numpy/core/tests/test_scalarinherit.py | 34 | ||||
-rw-r--r-- | numpy/core/tests/test_umath.py | 25 | ||||
-rw-r--r-- | numpy/distutils/system_info.py | 6 | ||||
-rw-r--r-- | numpy/lib/function_base.py | 8 | ||||
-rw-r--r-- | numpy/lib/npyio.py | 36 | ||||
-rw-r--r-- | numpy/lib/tests/test_function_base.py | 28 | ||||
-rw-r--r-- | numpy/random/mtrand/mtrand.pyx | 2 | ||||
-rw-r--r-- | numpy/testing/utils.py | 7 |
16 files changed, 565 insertions, 319 deletions
diff --git a/numpy/add_newdocs.py b/numpy/add_newdocs.py index 6934cadcc..30d5a68ea 100644 --- a/numpy/add_newdocs.py +++ b/numpy/add_newdocs.py @@ -4693,45 +4693,6 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('view', # ############################################################################## -add_newdoc('numpy.core.umath', 'frexp', - """ - Return normalized fraction and exponent of 2 of input array, element-wise. - - Returns (`out1`, `out2`) from equation ``x` = out1 * 2**out2``. - - Parameters - ---------- - x : array_like - Input array. - - Returns - ------- - (out1, out2) : tuple of ndarrays, (float, int) - `out1` is a float array with values between -1 and 1. - `out2` is an int array which represent the exponent of 2. - - See Also - -------- - ldexp : Compute ``y = x1 * 2**x2``, the inverse of `frexp`. - - Notes - ----- - Complex dtypes are not supported, they will raise a TypeError. - - Examples - -------- - >>> x = np.arange(9) - >>> y1, y2 = np.frexp(x) - >>> y1 - array([ 0. , 0.5 , 0.5 , 0.75 , 0.5 , 0.625, 0.75 , 0.875, - 0.5 ]) - >>> y2 - array([0, 1, 2, 2, 3, 3, 3, 3, 4]) - >>> y1 * 2**y2 - array([ 0., 1., 2., 3., 4., 5., 6., 7., 8.]) - - """) - add_newdoc('numpy.core.umath', 'frompyfunc', """ frompyfunc(func, nin, nout) @@ -4772,44 +4733,6 @@ add_newdoc('numpy.core.umath', 'frompyfunc', """) -add_newdoc('numpy.core.umath', 'ldexp', - """ - Compute y = x1 * 2**x2. - - Parameters - ---------- - x1 : array_like - The array of multipliers. - x2 : array_like - The array of exponents. - - Returns - ------- - y : array_like - The output array, the result of ``x1 * 2**x2``. - - See Also - -------- - frexp : Return (y1, y2) from ``x = y1 * 2**y2``, the inverse of `ldexp`. - - Notes - ----- - Complex dtypes are not supported, they will raise a TypeError. - - `ldexp` is useful as the inverse of `frexp`, if used by itself it is - more clear to simply use the expression ``x1 * 2**x2``. - - Examples - -------- - >>> np.ldexp(5, np.arange(4)) - array([ 5., 10., 20., 40.], dtype=float32) - - >>> x = np.arange(6) - >>> np.ldexp(*np.frexp(x)) - array([ 0., 1., 2., 3., 4., 5.]) - - """) - add_newdoc('numpy.core.umath', 'geterrobj', """ geterrobj() diff --git a/numpy/core/code_generators/ufunc_docstrings.py b/numpy/core/code_generators/ufunc_docstrings.py index 59e877750..4d302969e 100644 --- a/numpy/core/code_generators/ufunc_docstrings.py +++ b/numpy/core/code_generators/ufunc_docstrings.py @@ -162,7 +162,7 @@ add_newdoc('numpy.core.umath', 'arccos', add_newdoc('numpy.core.umath', 'arccosh', """ - Inverse hyperbolic cosine, elementwise. + Inverse hyperbolic cosine, element-wise. Parameters ---------- @@ -272,7 +272,7 @@ add_newdoc('numpy.core.umath', 'arcsin', add_newdoc('numpy.core.umath', 'arcsinh', """ - Inverse hyperbolic sine elementwise. + Inverse hyperbolic sine element-wise. Parameters ---------- @@ -467,7 +467,7 @@ add_newdoc('numpy.core.umath', '_arg', add_newdoc('numpy.core.umath', 'arctanh', """ - Inverse hyperbolic tangent elementwise. + Inverse hyperbolic tangent element-wise. Parameters ---------- @@ -486,15 +486,15 @@ add_newdoc('numpy.core.umath', 'arctanh', Notes ----- `arctanh` is a multivalued function: for each `x` there are infinitely - many numbers `z` such that `tanh(z) = x`. The convention is to return the - `z` whose imaginary part lies in `[-pi/2, pi/2]`. + many numbers `z` such that `tanh(z) = x`. The convention is to return + the `z` whose imaginary part lies in `[-pi/2, pi/2]`. For real-valued input data types, `arctanh` always returns real output. - For each value that cannot be expressed as a real number or infinity, it - yields ``nan`` and sets the `invalid` floating point error flag. + For each value that cannot be expressed as a real number or infinity, + it yields ``nan`` and sets the `invalid` floating point error flag. - For complex-valued input, `arctanh` is a complex analytical function that - has branch cuts `[-1, -inf]` and `[1, inf]` and is continuous from + For complex-valued input, `arctanh` is a complex analytical function + that has branch cuts `[-1, -inf]` and `[1, inf]` and is continuous from above on the former and from below on the latter. The inverse hyperbolic tangent is also known as `atanh` or ``tanh^-1``. @@ -524,7 +524,7 @@ add_newdoc('numpy.core.umath', 'bitwise_and', Parameters ---------- x1, x2 : array_like - Only integer types are handled (including booleans). + Only integer and boolean types are handled. Returns ------- @@ -575,7 +575,7 @@ add_newdoc('numpy.core.umath', 'bitwise_or', Parameters ---------- x1, x2 : array_like - Only integer types are handled (including booleans). + Only integer and boolean types are handled. out : ndarray, optional Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. See doc.ufuncs. @@ -634,7 +634,7 @@ add_newdoc('numpy.core.umath', 'bitwise_xor', Parameters ---------- x1, x2 : array_like - Only integer types are handled (including booleans). + Only integer and boolean types are handled. Returns ------- @@ -766,7 +766,7 @@ add_newdoc('numpy.core.umath', 'conjugate', add_newdoc('numpy.core.umath', 'cos', """ - Cosine elementwise. + Cosine element-wise. Parameters ---------- @@ -937,8 +937,8 @@ add_newdoc('numpy.core.umath', 'divide', See Also -------- - seterr : Set whether to raise or warn on overflow, underflow and division - by zero. + seterr : Set whether to raise or warn on overflow, underflow and + division by zero. Notes ----- @@ -1048,8 +1048,8 @@ add_newdoc('numpy.core.umath', 'exp', For complex arguments, ``x = a + ib``, we can write :math:`e^x = e^a e^{ib}`. The first term, :math:`e^a`, is already known (it is the real argument, described above). The second term, - :math:`e^{ib}`, is :math:`\\cos b + i \\sin b`, a function with magnitude - 1 and a periodic phase. + :math:`e^{ib}`, is :math:`\\cos b + i \\sin b`, a function with + magnitude 1 and a periodic phase. References ---------- @@ -1137,7 +1137,7 @@ add_newdoc('numpy.core.umath', 'expm1', Notes ----- - This function provides greater precision than the formula ``exp(x) - 1`` + This function provides greater precision than ``exp(x) - 1`` for small values of ``x``. Examples @@ -1155,10 +1155,10 @@ add_newdoc('numpy.core.umath', 'expm1', add_newdoc('numpy.core.umath', 'fabs', """ - Compute the absolute values elementwise. + Compute the absolute values element-wise. - This function returns the absolute values (positive magnitude) of the data - in `x`. Complex values are not handled, use `absolute` to find the + This function returns the absolute values (positive magnitude) of the + data in `x`. Complex values are not handled, use `absolute` to find the absolute values of complex data. Parameters @@ -1212,8 +1212,8 @@ add_newdoc('numpy.core.umath', 'floor', Notes ----- Some spreadsheet programs calculate the "floor-towards-zero", in other - words ``floor(-2.5) == -2``. NumPy, however, uses the a definition of - `floor` such that `floor(-2.5) == -3`. + words ``floor(-2.5) == -2``. NumPy instead uses the definition of + `floor` where `floor(-2.5) == -3`. Examples -------- @@ -1225,7 +1225,8 @@ add_newdoc('numpy.core.umath', 'floor', add_newdoc('numpy.core.umath', 'floor_divide', """ - Return the largest integer smaller or equal to the division of the inputs. + Return the largest integer smaller or equal to the division of the + inputs. Parameters ---------- @@ -1259,7 +1260,10 @@ add_newdoc('numpy.core.umath', 'fmod', """ Return the element-wise remainder of division. - This is the NumPy implementation of the Python modulo operator `%`. + This is the NumPy implementation of the C library function fmod, the + remainder has the same sign as the dividend `x1`. It is equivalent to + the Matlab(TM) ``rem`` function and should not be confused with the + Python modulus operator ``x1 % x2``. Parameters ---------- @@ -1275,15 +1279,16 @@ add_newdoc('numpy.core.umath', 'fmod', See Also -------- - remainder : Modulo operation where the quotient is `floor(x1/x2)`. + remainder : Equivalent to the Python ``%`` operator. divide Notes ----- - The result of the modulo operation for negative dividend and divisors is - bound by conventions. In `fmod`, the sign of the remainder is the sign of - the dividend. In `remainder`, the sign of the divisor does not affect the - sign of the result. + The result of the modulo operation for negative dividend and divisors + is bound by conventions. For `fmod`, the sign of result is the sign of + the dividend, while for `remainder` the sign of the result is the sign + of the divisor. The `fmod` function is equivalent to the Matlab(TM) + ``rem`` function. Examples -------- @@ -1414,17 +1419,17 @@ add_newdoc('numpy.core.umath', 'invert', the integers in the input arrays. This ufunc implements the C/Python operator ``~``. - For signed integer inputs, the two's complement is returned. - In a two's-complement system negative numbers are represented by the two's + For signed integer inputs, the two's complement is returned. In a + two's-complement system negative numbers are represented by the two's complement of the absolute value. This is the most common method of - representing signed integers on computers [1]_. A N-bit two's-complement - system can represent every integer in the range + representing signed integers on computers [1]_. A N-bit + two's-complement system can represent every integer in the range :math:`-2^{N-1}` to :math:`+2^{N-1}-1`. Parameters ---------- x1 : array_like - Only integer types are handled (including booleans). + Only integer and boolean types are handled. Returns ------- @@ -1488,7 +1493,7 @@ add_newdoc('numpy.core.umath', 'invert', add_newdoc('numpy.core.umath', 'isfinite', """ - Test element-wise for finite-ness (not infinity or not Not a Number). + Test element-wise for finiteness (not infinity or not Not a Number). The result is returned as a boolean array. @@ -1508,9 +1513,10 @@ add_newdoc('numpy.core.umath', 'isfinite', either positive infinity, negative infinity or Not a Number). For array input, the result is a boolean array with the same - dimensions as the input and the values are True if the corresponding - element of the input is finite; otherwise the values are False (element - is either positive infinity, negative infinity or Not a Number). + dimensions as the input and the values are True if the + corresponding element of the input is finite; otherwise the values + are False (element is either positive infinity, negative infinity + or Not a Number). See Also -------- @@ -1524,9 +1530,9 @@ add_newdoc('numpy.core.umath', 'isfinite', Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Also that positive infinity is not equivalent to negative infinity. But - infinity is equivalent to positive infinity. - Errors result if the second argument is also supplied when `x` is a scalar - input, or if first and second arguments have different shapes. + infinity is equivalent to positive infinity. Errors result if the + second argument is also supplied when `x` is a scalar input, or if + first and second arguments have different shapes. Examples -------- @@ -1556,8 +1562,8 @@ add_newdoc('numpy.core.umath', 'isinf', """ Test element-wise for positive or negative infinity. - Return a bool-type array, the same shape as `x`, True where ``x == - +/-inf``, False everywhere else. + Returns a boolean array of the same shape as `x`, True where ``x == + +/-inf``, otherwise False. Parameters ---------- @@ -1568,19 +1574,19 @@ add_newdoc('numpy.core.umath', 'isinf', Returns ------- - y : bool (scalar) or bool-type ndarray - For scalar input, the result is a new boolean with value True - if the input is positive or negative infinity; otherwise the value - is False. + y : bool (scalar) or boolean ndarray + For scalar input, the result is a new boolean with value True if + the input is positive or negative infinity; otherwise the value is + False. - For array input, the result is a boolean array with the same - shape as the input and the values are True where the - corresponding element of the input is positive or negative - infinity; elsewhere the values are False. If a second argument - was supplied the result is stored there. If the type of that array - is a numeric type the result is represented as zeros and ones, if - the type is boolean then as False and True, respectively. - The return value `y` is then a reference to that array. + For array input, the result is a boolean array with the same shape + as the input and the values are True where the corresponding + element of the input is positive or negative infinity; elsewhere + the values are False. If a second argument was supplied the result + is stored there. If the type of that array is a numeric type the + result is represented as zeros and ones, if the type is boolean + then as False and True, respectively. The return value `y` is then + a reference to that array. See Also -------- @@ -1617,7 +1623,7 @@ add_newdoc('numpy.core.umath', 'isinf', add_newdoc('numpy.core.umath', 'isnan', """ - Test element-wise for Not a Number (NaN), return result as a bool array. + Test element-wise for NaN and return result as a boolean array. Parameters ---------- @@ -1627,12 +1633,13 @@ add_newdoc('numpy.core.umath', 'isnan', Returns ------- y : {ndarray, bool} - For scalar input, the result is a new boolean with value True - if the input is NaN; otherwise the value is False. + For scalar input, the result is a new boolean with value True if + the input is NaN; otherwise the value is False. - For array input, the result is a boolean array with the same - dimensions as the input and the values are True if the corresponding - element of the input is NaN; otherwise the values are False. + For array input, the result is a boolean array of the same + dimensions as the input and the values are True if the + corresponding element of the input is NaN; otherwise the values are + False. See Also -------- @@ -1753,7 +1760,8 @@ add_newdoc('numpy.core.umath', 'log', Natural logarithm, element-wise. The natural logarithm `log` is the inverse of the exponential function, - so that `log(exp(x)) = x`. The natural logarithm is logarithm in base `e`. + so that `log(exp(x)) = x`. The natural logarithm is logarithm in base + `e`. Parameters ---------- @@ -1772,8 +1780,8 @@ add_newdoc('numpy.core.umath', 'log', Notes ----- Logarithm is a multivalued function: for each `x` there is an infinite - number of `z` such that `exp(z) = x`. The convention is to return the `z` - whose imaginary part lies in `[-pi, pi]`. + number of `z` such that `exp(z) = x`. The convention is to return the + `z` whose imaginary part lies in `[-pi, pi]`. For real-valued input data types, `log` always returns real output. For each value that cannot be expressed as a real number or infinity, it @@ -1819,17 +1827,17 @@ add_newdoc('numpy.core.umath', 'log10', Notes ----- Logarithm is a multivalued function: for each `x` there is an infinite - number of `z` such that `10**z = x`. The convention is to return the `z` - whose imaginary part lies in `[-pi, pi]`. + number of `z` such that `10**z = x`. The convention is to return the + `z` whose imaginary part lies in `[-pi, pi]`. - For real-valued input data types, `log10` always returns real output. For - each value that cannot be expressed as a real number or infinity, it - yields ``nan`` and sets the `invalid` floating point error flag. + For real-valued input data types, `log10` always returns real output. + For each value that cannot be expressed as a real number or infinity, + it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `log10` is a complex analytical function that - has a branch cut `[-inf, 0]` and is continuous from above on it. `log10` - handles the floating-point negative zero as an infinitesimal negative - number, conforming to the C99 standard. + has a branch cut `[-inf, 0]` and is continuous from above on it. + `log10` handles the floating-point negative zero as an infinitesimal + negative number, conforming to the C99 standard. References ---------- @@ -1870,9 +1878,9 @@ add_newdoc('numpy.core.umath', 'log2', number of `z` such that `2**z = x`. The convention is to return the `z` whose imaginary part lies in `[-pi, pi]`. - For real-valued input data types, `log2` always returns real output. For - each value that cannot be expressed as a real number or infinity, it - yields ``nan`` and sets the `invalid` floating point error flag. + For real-valued input data types, `log2` always returns real output. + For each value that cannot be expressed as a real number or infinity, + it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `log2` is a complex analytical function that has a branch cut `[-inf, 0]` and is continuous from above on it. `log2` @@ -1913,7 +1921,7 @@ add_newdoc('numpy.core.umath', 'logaddexp', See Also -------- - logaddexp2: Logarithm of the sum of exponentiations of inputs in base-2. + logaddexp2: Logarithm of the sum of exponentiations of inputs in base 2. Notes ----- @@ -1936,8 +1944,8 @@ add_newdoc('numpy.core.umath', 'logaddexp2', Logarithm of the sum of exponentiations of the inputs in base-2. 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 + 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. @@ -2002,14 +2010,14 @@ add_newdoc('numpy.core.umath', 'log1p', number of `z` such that `exp(z) = 1 + x`. The convention is to return the `z` whose imaginary part lies in `[-pi, pi]`. - For real-valued input data types, `log1p` always returns real output. For - each value that cannot be expressed as a real number or infinity, it - yields ``nan`` and sets the `invalid` floating point error flag. + For real-valued input data types, `log1p` always returns real output. + For each value that cannot be expressed as a real number or infinity, + it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `log1p` is a complex analytical function that - has a branch cut `[-inf, -1]` and is continuous from above on it. `log1p` - handles the floating-point negative zero as an infinitesimal negative - number, conforming to the C99 standard. + has a branch cut `[-inf, -1]` and is continuous from above on it. + `log1p` handles the floating-point negative zero as an infinitesimal + negative number, conforming to the C99 standard. References ---------- @@ -2028,7 +2036,7 @@ add_newdoc('numpy.core.umath', 'log1p', add_newdoc('numpy.core.umath', 'logical_and', """ - Compute the truth value of x1 AND x2 elementwise. + Compute the truth value of x1 AND x2 element-wise. Parameters ---------- @@ -2062,7 +2070,7 @@ add_newdoc('numpy.core.umath', 'logical_and', add_newdoc('numpy.core.umath', 'logical_not', """ - Compute the truth value of NOT x elementwise. + Compute the truth value of NOT x element-wise. Parameters ---------- @@ -2094,7 +2102,7 @@ add_newdoc('numpy.core.umath', 'logical_not', add_newdoc('numpy.core.umath', 'logical_or', """ - Compute the truth value of x1 OR x2 elementwise. + Compute the truth value of x1 OR x2 element-wise. Parameters ---------- @@ -2171,11 +2179,11 @@ add_newdoc('numpy.core.umath', 'maximum', Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise - maxima. If one of the elements being compared is a nan, then that element - is returned. If both elements are nans then the first is returned. The - latter distinction is important for complex nans, which are defined as at - least one of the real or imaginary parts being a nan. The net effect is - that nans are propagated. + maxima. If one of the elements being compared is a NaN, then that + element is returned. If both elements are NaNs then the first is + returned. The latter distinction is important for complex NaNs, which + are defined as at least one of the real or imaginary parts being a NaN. + The net effect is that NaNs are propagated. Parameters ---------- @@ -2192,20 +2200,21 @@ add_newdoc('numpy.core.umath', 'maximum', See Also -------- minimum : - Element-wise minimum of two arrays, propagating any NaNs. + Element-wise minimum of two arrays, propagates NaNs. fmax : - Element-wise maximum of two arrays, ignoring any NaNs. + Element-wise maximum of two arrays, ignores NaNs. amax : - The maximum value of an array along a given axis, propagating any NaNs. + The maximum value of an array along a given axis, propagates NaNs. nanmax : - The maximum value of an array along a given axis, ignoring any NaNs. + The maximum value of an array along a given axis, ignores NaNs. fmin, amin, nanmin Notes ----- - The maximum is equivalent to ``np.where(x1 >= x2, x1, x2)`` when neither - x1 nor x2 are nans, but it is faster and does proper broadcasting. + The maximum is equivalent to ``np.where(x1 >= x2, x1, x2)`` when + neither x1 nor x2 are nans, but it is faster and does proper + broadcasting. Examples -------- @@ -2228,11 +2237,11 @@ add_newdoc('numpy.core.umath', 'minimum', Element-wise minimum of array elements. Compare two arrays and returns a new array containing the element-wise - minima. If one of the elements being compared is a nan, then that element - is returned. If both elements are nans then the first is returned. The - latter distinction is important for complex nans, which are defined as at - least one of the real or imaginary parts being a nan. The net effect is - that nans are propagated. + minima. If one of the elements being compared is a NaN, then that + element is returned. If both elements are NaNs then the first is + returned. The latter distinction is important for complex NaNs, which + are defined as at least one of the real or imaginary parts being a NaN. + The net effect is that NaNs are propagated. Parameters ---------- @@ -2249,20 +2258,21 @@ add_newdoc('numpy.core.umath', 'minimum', See Also -------- maximum : - Element-wise maximum of two arrays, propagating any NaNs. + Element-wise maximum of two arrays, propagates NaNs. fmin : - Element-wise minimum of two arrays, ignoring any NaNs. + Element-wise minimum of two arrays, ignores NaNs. amin : - The minimum value of an array along a given axis, propagating any NaNs. + The minimum value of an array along a given axis, propagates NaNs. nanmin : - The minimum value of an array along a given axis, ignoring any NaNs. + The minimum value of an array along a given axis, ignores NaNs. fmax, amax, nanmax Notes ----- - The minimum is equivalent to ``np.where(x1 <= x2, x1, x2)`` when neither - x1 nor x2 are nans, but it is faster and does proper broadcasting. + The minimum is equivalent to ``np.where(x1 <= x2, x1, x2)`` when + neither x1 nor x2 are NaNs, but it is faster and does proper + broadcasting. Examples -------- @@ -2285,11 +2295,11 @@ add_newdoc('numpy.core.umath', 'fmax', Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise - maxima. If one of the elements being compared is a nan, then the non-nan - element is returned. If both elements are nans then the first is returned. - The latter distinction is important for complex nans, which are defined as - at least one of the real or imaginary parts being a nan. The net effect is - that nans are ignored when possible. + maxima. If one of the elements being compared is a NaN, then the + non-nan element is returned. If both elements are NaNs then the first + is returned. The latter distinction is important for complex NaNs, + which are defined as at least one of the real or imaginary parts being + a NaN. The net effect is that NaNs are ignored when possible. Parameters ---------- @@ -2306,13 +2316,13 @@ add_newdoc('numpy.core.umath', 'fmax', See Also -------- fmin : - Element-wise minimum of two arrays, ignoring any NaNs. + Element-wise minimum of two arrays, ignores NaNs. maximum : - Element-wise maximum of two arrays, propagating any NaNs. + Element-wise maximum of two arrays, propagates NaNs. amax : - The maximum value of an array along a given axis, propagating any NaNs. + The maximum value of an array along a given axis, propagates NaNs. nanmax : - The maximum value of an array along a given axis, ignoring any NaNs. + The maximum value of an array along a given axis, ignores NaNs. minimum, amin, nanmin @@ -2321,7 +2331,7 @@ add_newdoc('numpy.core.umath', 'fmax', .. versionadded:: 1.3.0 The fmax is equivalent to ``np.where(x1 >= x2, x1, x2)`` when neither - x1 nor x2 are nans, but it is faster and does proper broadcasting. + x1 nor x2 are NaNs, but it is faster and does proper broadcasting. Examples -------- @@ -2342,11 +2352,11 @@ add_newdoc('numpy.core.umath', 'fmin', Element-wise minimum of array elements. Compare two arrays and returns a new array containing the element-wise - minima. If one of the elements being compared is a nan, then the non-nan - element is returned. If both elements are nans then the first is returned. - The latter distinction is important for complex nans, which are defined as - at least one of the real or imaginary parts being a nan. The net effect is - that nans are ignored when possible. + minima. If one of the elements being compared is a NaN, then the + non-nan element is returned. If both elements are NaNs then the first + is returned. The latter distinction is important for complex NaNs, + which are defined as at least one of the real or imaginary parts being + a NaN. The net effect is that NaNs are ignored when possible. Parameters ---------- @@ -2363,13 +2373,13 @@ add_newdoc('numpy.core.umath', 'fmin', See Also -------- fmax : - Element-wise maximum of two arrays, ignoring any NaNs. + Element-wise maximum of two arrays, ignores NaNs. minimum : - Element-wise minimum of two arrays, propagating any NaNs. + Element-wise minimum of two arrays, propagates NaNs. amin : - The minimum value of an array along a given axis, propagating any NaNs. + The minimum value of an array along a given axis, propagates NaNs. nanmin : - The minimum value of an array along a given axis, ignoring any NaNs. + The minimum value of an array along a given axis, ignores NaNs. maximum, amax, nanmax @@ -2378,7 +2388,7 @@ add_newdoc('numpy.core.umath', 'fmin', .. versionadded:: 1.3.0 The fmin is equivalent to ``np.where(x1 <= x2, x1, x2)`` when neither - x1 nor x2 are nans, but it is faster and does proper broadcasting. + x1 nor x2 are NaNs, but it is faster and does proper broadcasting. Examples -------- @@ -2461,7 +2471,7 @@ add_newdoc('numpy.core.umath', 'multiply', add_newdoc('numpy.core.umath', 'negative', """ - Returns an array with the negative of each element of the original array. + Numerical negative, element-wise. Parameters ---------- @@ -2515,10 +2525,9 @@ add_newdoc('numpy.core.umath', 'not_equal', add_newdoc('numpy.core.umath', '_ones_like', """ - This function used to be the numpy.ones_like, but now a - specific function for that has been written for consistency with - the other *_like functions. It is only used internally in a limited - fashion now. + This function used to be the numpy.ones_like, but now a specific + function for that has been written for consistency with the other + *_like functions. It is only used internally in a limited fashion now. See Also -------- @@ -2664,8 +2673,8 @@ add_newdoc('numpy.core.umath', 'reciprocal', 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. + always zero because of the way Python handles integer division. For + integer zero the result is an overflow. Examples -------- @@ -2680,7 +2689,10 @@ add_newdoc('numpy.core.umath', 'remainder', """ Return element-wise remainder of division. - Computes ``x1 - floor(x1 / x2) * x2``. + Computes ``x1 - floor(x1 / x2) * x2``, the result has the same sign as + the divisor `x2`. It is equivalent to the Python modulus operator + ``x1 % x2`` and should not be confused with the Matlab(TM) ``rem`` + function. Parameters ---------- @@ -2695,16 +2707,18 @@ add_newdoc('numpy.core.umath', 'remainder', Returns ------- y : ndarray - The remainder of the quotient ``x1/x2``, element-wise. Returns a scalar - if both `x1` and `x2` are scalars. + The remainder of the quotient ``x1/x2``, element-wise. Returns a + scalar if both `x1` and `x2` are scalars. See Also -------- + fmod : Equivalent of the Matlab(TM) ``rem`` function. divide, floor Notes ----- - Returns 0 when `x2` is 0 and both `x1` and `x2` are (arrays of) integers. + Returns 0 when `x2` is 0 and both `x1` and `x2` are (arrays of) + integers. Examples -------- @@ -2719,9 +2733,9 @@ add_newdoc('numpy.core.umath', 'right_shift', """ Shift the bits of an integer to the right. - Bits are shifted to the right by removing `x2` bits at the right of `x1`. - Since the internal representation of numbers is in binary format, this - operation is equivalent to dividing `x1` by ``2**x2``. + Bits are shifted to the right `x2`. Because the internal + representation of numbers is in binary format, this operation is + equivalent to dividing `x1` by ``2**x2``. Parameters ---------- @@ -2815,9 +2829,8 @@ add_newdoc('numpy.core.umath', 'signbit', x : array_like The input value(s). out : ndarray, optional - Array into which the output is placed. Its type is preserved - and it must be of the right shape to hold the output. - See `doc.ufuncs`. + Array into which the output is placed. Its type is preserved and it + must be of the right shape to hold the output. See `doc.ufuncs`. Returns ------- @@ -2874,8 +2887,7 @@ add_newdoc('numpy.core.umath', 'copysign', add_newdoc('numpy.core.umath', 'nextafter', """ - Return the next representable floating-point value after x1 in the direction - of x2 element-wise. + Return the next floating-point value after x1 towards x2, element-wise. Parameters ---------- @@ -2923,7 +2935,7 @@ add_newdoc('numpy.core.umath', 'spacing', should not be any representable number between ``x + spacing(x)`` and x for any finite x. - Spacing of +- inf and nan is nan. + Spacing of +- inf and NaN is NaN. Examples -------- @@ -2952,17 +2964,17 @@ add_newdoc('numpy.core.umath', 'sin', Notes ----- - The sine is one of the fundamental functions of trigonometry - (the mathematical study of triangles). Consider a circle of radius - 1 centered on the origin. A ray comes in from the :math:`+x` axis, - makes an angle at the origin (measured counter-clockwise from that - axis), and departs from the origin. The :math:`y` coordinate of - the outgoing ray's intersection with the unit circle is the sine - of that angle. It ranges from -1 for :math:`x=3\\pi / 2` to - +1 for :math:`\\pi / 2.` The function has zeroes where the angle is - a multiple of :math:`\\pi`. Sines of angles between :math:`\\pi` and - :math:`2\\pi` are negative. The numerous properties of the sine and - related functions are included in any standard trigonometry text. + The sine is one of the fundamental functions of trigonometry (the + mathematical study of triangles). Consider a circle of radius 1 + centered on the origin. A ray comes in from the :math:`+x` axis, makes + an angle at the origin (measured counter-clockwise from that axis), and + departs from the origin. The :math:`y` coordinate of the outgoing + ray's intersection with the unit circle is the sine of that angle. It + ranges from -1 for :math:`x=3\\pi / 2` to +1 for :math:`\\pi / 2.` The + function has zeroes where the angle is a multiple of :math:`\\pi`. + Sines of angles between :math:`\\pi` and :math:`2\\pi` are negative. + The numerous properties of the sine and related functions are included + in any standard trigonometry text. Examples -------- @@ -3076,8 +3088,8 @@ add_newdoc('numpy.core.umath', 'sqrt', ----- *sqrt* has--consistent with common convention--as its branch cut the real "interval" [`-inf`, 0), and is continuous from above on it. - (A branch cut is a curve in the complex plane across which a given - complex function fails to be continuous.) + A branch cut is a curve in the complex plane across which a given + complex function fails to be continuous. Examples -------- @@ -3210,8 +3222,7 @@ add_newdoc('numpy.core.umath', 'tanh', """ Compute hyperbolic tangent element-wise. - Equivalent to ``np.sinh(x)/np.cosh(x)`` or - ``-1j * np.tan(1j*x)``. + Equivalent to ``np.sinh(x)/np.cosh(x)`` or ``-1j * np.tan(1j*x)``. Parameters ---------- @@ -3285,10 +3296,10 @@ add_newdoc('numpy.core.umath', 'true_divide', Notes ----- - The floor division operator ``//`` was added in Python 2.2 making ``//`` - and ``/`` equivalent operators. The default floor division operation of - ``/`` can be replaced by true division with - ``from __future__ import division``. + The floor division operator ``//`` was added in Python 2.2 making + ``//`` and ``/`` equivalent operators. The default floor division + operation of ``/`` can be replaced by true division with ``from + __future__ import division``. In Python 3.0, ``//`` is the floor division operator and ``/`` the true division operator. The ``true_divide(x1, x2)`` function is @@ -3312,3 +3323,97 @@ add_newdoc('numpy.core.umath', 'true_divide', array([0, 0, 0, 0, 1]) """) + +# This doc is not currently used, but has been converted to a C string +# that can be found in numpy/core/src/umath/umathmodule.c where the +# frexp ufunc is constructed. +add_newdoc('numpy.core.umath', 'frexp', + """ + Decompose the elements of x into mantissa and twos exponent. + + Returns (`mantissa`, `exponent`), where `x = mantissa * 2**exponent``. + The mantissa is lies in the open interval(-1, 1), while the twos + exponent is a signed integer. + + Parameters + ---------- + x : array_like + Array of numbers to be decomposed. + out1: ndarray, optional + Output array for the mantissa. Must have the same shape as `x`. + out2: ndarray, optional + Output array for the exponent. Must have the same shape as `x`. + + Returns + ------- + (mantissa, exponent) : tuple of ndarrays, (float, int) + `mantissa` is a float array with values between -1 and 1. + `exponent` is an int array which represents the exponent of 2. + + See Also + -------- + ldexp : Compute ``y = x1 * 2**x2``, the inverse of `frexp`. + + Notes + ----- + Complex dtypes are not supported, they will raise a TypeError. + + Examples + -------- + >>> x = np.arange(9) + >>> y1, y2 = np.frexp(x) + >>> y1 + array([ 0. , 0.5 , 0.5 , 0.75 , 0.5 , 0.625, 0.75 , 0.875, + 0.5 ]) + >>> y2 + array([0, 1, 2, 2, 3, 3, 3, 3, 4]) + >>> y1 * 2**y2 + array([ 0., 1., 2., 3., 4., 5., 6., 7., 8.]) + + """) + +# This doc is not currently used, but has been converted to a C string +# that can be found in numpy/core/src/umath/umathmodule.c where the +# ldexp ufunc is constructed. +add_newdoc('numpy.core.umath', 'ldexp', + """ + Returns x1 * 2**x2, element-wise. + + The mantissas `x1` and twos exponents `x2` are used to construct + floating point numbers ``x1 * 2**x2``. + + Parameters + ---------- + x1 : array_like + Array of multipliers. + x2 : array_like, int + Array of twos exponents. + out : ndarray, optional + Output array for the result. + + Returns + ------- + y : ndarray or scalar + The result of ``x1 * 2**x2``. + + See Also + -------- + frexp : Return (y1, y2) from ``x = y1 * 2**y2``, inverse to `ldexp`. + + Notes + ----- + Complex dtypes are not supported, they will raise a TypeError. + + `ldexp` is useful as the inverse of `frexp`, if used by itself it is + more clear to simply use the expression ``x1 * 2**x2``. + + Examples + -------- + >>> np.ldexp(5, np.arange(4)) + array([ 5., 10., 20., 40.], dtype=float32) + + >>> x = np.arange(6) + >>> np.ldexp(*np.frexp(x)) + array([ 0., 1., 2., 3., 4., 5.]) + + """) diff --git a/numpy/core/include/numpy/npy_common.h b/numpy/core/include/numpy/npy_common.h index 9d6171357..c257f216d 100644 --- a/numpy/core/include/numpy/npy_common.h +++ b/numpy/core/include/numpy/npy_common.h @@ -57,8 +57,16 @@ #endif /* 64 bit file position support, also on win-amd64. Ticket #1660 */ -#if defined(_MSC_VER) && defined(_WIN64) && (_MSC_VER > 1400) +#if defined(_MSC_VER) && defined(_WIN64) && (_MSC_VER > 1400) || \ + defined(__MINGW32__) || defined(__MINGW64__) #include <io.h> + +/* mingw based on 3.4.5 has lseek but not ftell/fseek */ +#if defined(__MINGW32__) || defined(__MINGW64__) +extern int __cdecl _fseeki64(FILE *, long long, int); +extern long long __cdecl _ftelli64(FILE *); +#endif + #define npy_fseek _fseeki64 #define npy_ftell _ftelli64 #define npy_lseek _lseeki64 diff --git a/numpy/core/src/multiarray/number.c b/numpy/core/src/multiarray/number.c index a00f6729c..926db27e8 100644 --- a/numpy/core/src/multiarray/number.c +++ b/numpy/core/src/multiarray/number.c @@ -391,32 +391,41 @@ is_scalar_with_conversion(PyObject *o2, double* out_exponent) *out_exponent = PyFloat_AsDouble(o2); return NPY_FLOAT_SCALAR; } - if ((PyArray_IsZeroDim(o2) && - ((PyArray_ISINTEGER((PyArrayObject *)o2) || - (optimize_fpexps && PyArray_ISFLOAT((PyArrayObject *)o2))))) || - PyArray_IsScalar(o2, Integer) || - (optimize_fpexps && PyArray_IsScalar(o2, Floating))) { - temp = Py_TYPE(o2)->tp_as_number->nb_float(o2); - if (temp != NULL) { + if (PyArray_Check(o2)) { + if ((PyArray_NDIM(o2) == 0) && + ((PyArray_ISINTEGER((PyArrayObject *)o2) || + (optimize_fpexps && PyArray_ISFLOAT((PyArrayObject *)o2))))) { + temp = Py_TYPE(o2)->tp_as_number->nb_float(o2); + if (temp == NULL) { + return NPY_NOSCALAR; + } *out_exponent = PyFloat_AsDouble(o2); Py_DECREF(temp); - if (PyArray_IsZeroDim(o2)) { - if (PyArray_ISINTEGER((PyArrayObject *)o2)) { - return NPY_INTPOS_SCALAR; - } - else { /* ISFLOAT */ - return NPY_FLOAT_SCALAR; - } + if (PyArray_ISINTEGER((PyArrayObject *)o2)) { + return NPY_INTPOS_SCALAR; } - else if (PyArray_IsScalar(o2, Integer)) { - return NPY_INTPOS_SCALAR; - } - else { /* IsScalar(o2, Floating) */ + else { /* ISFLOAT */ return NPY_FLOAT_SCALAR; } } } - if (PyIndex_Check(o2)) { + else if (PyArray_IsScalar(o2, Integer) || + (optimize_fpexps && PyArray_IsScalar(o2, Floating))) { + temp = Py_TYPE(o2)->tp_as_number->nb_float(o2); + if (temp == NULL) { + return NPY_NOSCALAR; + } + *out_exponent = PyFloat_AsDouble(o2); + Py_DECREF(temp); + + if (PyArray_IsScalar(o2, Integer)) { + return NPY_INTPOS_SCALAR; + } + else { /* IsScalar(o2, Floating) */ + return NPY_FLOAT_SCALAR; + } + } + else if (PyIndex_Check(o2)) { PyObject* value = PyNumber_Index(o2); Py_ssize_t val; if (value==NULL) { diff --git a/numpy/core/src/multiarray/scalartypes.c.src b/numpy/core/src/multiarray/scalartypes.c.src index 69600de39..dbc65724d 100644 --- a/numpy/core/src/multiarray/scalartypes.c.src +++ b/numpy/core/src/multiarray/scalartypes.c.src @@ -2456,10 +2456,13 @@ object_arrtype_dealloc(PyObject *v) /* We are inheriting from a Python type as well so \ give it first dibs on conversion */ \ sup = (PyTypeObject *)PyTuple_GET_ITEM(type->tp_bases, num); \ - robj = sup->tp_new(type, args, kwds); \ - if (robj != NULL) goto finish; \ - if (PyTuple_GET_SIZE(args)!=1) return NULL; \ - PyErr_Clear(); \ + /* Prevent recursion */ \ + if (thisfunc != sup->tp_new) { \ + robj = sup->tp_new(type, args, kwds); \ + if (robj != NULL) goto finish; \ + if (PyTuple_GET_SIZE(args)!=1) return NULL; \ + PyErr_Clear(); \ + } \ /* now do default conversion */ \ } @@ -2495,6 +2498,9 @@ static PyObject * PyObject *robj; PyArrayObject *arr; PyArray_Descr *typecode = NULL; +#if (@work@ != 0) || (@default@ == 1) + void *thisfunc = (void *)@name@_arrtype_new; +#endif #if !(@default@ == 2) int itemsize; void *dest, *src; diff --git a/numpy/core/src/umath/loops.c.src b/numpy/core/src/umath/loops.c.src index 43419780e..0fa03f343 100644 --- a/numpy/core/src/umath/loops.c.src +++ b/numpy/core/src/umath/loops.c.src @@ -1692,9 +1692,11 @@ NPY_NO_EXPORT void NPY_NO_EXPORT void @TYPE@_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { - UNARY_LOOP { - const @type@ in1 = *(@type@ *)ip1; - *((@type@ *)op1) = -in1; + if (!run_unary_simd_negative_@TYPE@(args, dimensions, steps)) { + UNARY_LOOP { + const @type@ in1 = *(@type@ *)ip1; + *((@type@ *)op1) = -in1; + } } } diff --git a/numpy/core/src/umath/simd.inc.src b/numpy/core/src/umath/simd.inc.src index bb894f561..554fc199a 100644 --- a/numpy/core/src/umath/simd.inc.src +++ b/numpy/core/src/umath/simd.inc.src @@ -133,10 +133,10 @@ static const npy_int32 fanout_4[] = { */ /**begin repeat1 - * #func = sqrt, absolute, minimum, maximum# - * #check = IS_BLOCKABLE_UNARY, IS_BLOCKABLE_UNARY, IS_BLOCKABLE_REDUCE, IS_BLOCKABLE_REDUCE# - * #name = unary, unary, unary_reduce, unary_reduce# - * #minmax = 0, 0, 1, 1# + * #func = sqrt, absolute, negative, minimum, maximum# + * #check = IS_BLOCKABLE_UNARY*3, IS_BLOCKABLE_REDUCE*2 # + * #name = unary*3, unary_reduce*2# + * #minmax = 0*3, 1*2# */ #if @vector@ && defined NPY_HAVE_SSE2_INTRINSICS @@ -621,41 +621,56 @@ sse2_sqrt_@TYPE@(@type@ * op, @type@ * ip, const npy_intp n) } +static NPY_INLINE +@type@ scalar_abs_@type@(@type@ v) +{ + /* add 0 to clear -0.0 */ + return (v > 0 ? v: -v) + 0; +} + +static NPY_INLINE +@type@ scalar_neg_@type@(@type@ v) +{ + return -v; +} + +/**begin repeat1 + * #kind = absolute, negative# + * #VOP = andnot, xor# + * #scalar = scalar_abs, scalar_neg# + **/ static void -sse2_absolute_@TYPE@(@type@ * op, @type@ * ip, const npy_intp n) +sse2_@kind@_@TYPE@(@type@ * op, @type@ * ip, const npy_intp n) { /* * get 0x7FFFFFFF mask (everything but signbit set) - * float & ~mask will remove the sign + * float & ~mask will remove the sign, float ^ mask flips the sign * this is equivalent to how the compiler implements fabs on amd64 */ const @vtype@ mask = @vpre@_set1_@vsuf@(-0.@c@); /* align output to 16 bytes */ LOOP_BLOCK_ALIGN_VAR(op, @type@, 16) { - const @type@ tmp = ip[i] > 0 ? ip[i]: -ip[i]; - /* add 0 to clear -0.0 */ - op[i] = tmp + 0; + op[i] = @scalar@_@type@(ip[i]); } assert(n < (16 / sizeof(@type@)) || npy_is_aligned(&op[i], 16)); if (npy_is_aligned(&ip[i], 16)) { LOOP_BLOCKED(@type@, 16) { @vtype@ a = @vpre@_load_@vsuf@(&ip[i]); - @vpre@_store_@vsuf@(&op[i], @vpre@_andnot_@vsuf@(mask, a)); + @vpre@_store_@vsuf@(&op[i], @vpre@_@VOP@_@vsuf@(mask, a)); } } else { LOOP_BLOCKED(@type@, 16) { @vtype@ a = @vpre@_loadu_@vsuf@(&ip[i]); - @vpre@_store_@vsuf@(&op[i], @vpre@_andnot_@vsuf@(mask, a)); + @vpre@_store_@vsuf@(&op[i], @vpre@_@VOP@_@vsuf@(mask, a)); } } LOOP_BLOCKED_END { - const @type@ tmp = ip[i] > 0 ? ip[i]: -ip[i]; - /* add 0 to clear -0.0 */ - op[i] = tmp + 0; + op[i] = @scalar@_@type@(ip[i]); } } +/**end repeat1**/ /**begin repeat1 diff --git a/numpy/core/src/umath/umathmodule.c b/numpy/core/src/umath/umathmodule.c index f395d5096..b1fc2f7be 100644 --- a/numpy/core/src/umath/umathmodule.c +++ b/numpy/core/src/umath/umathmodule.c @@ -251,6 +251,50 @@ static PyUFuncGenericFunction ldexp_functions[] = { #endif }; +static const char frdoc[] = + " Decompose the elements of x into mantissa and twos exponent.\n" + "\n" + " Returns (`mantissa`, `exponent`), where `x = mantissa * 2**exponent``.\n" + " The mantissa is lies in the open interval(-1, 1), while the twos\n" + " exponent is a signed integer.\n" + "\n" + " Parameters\n" + " ----------\n" + " x : array_like\n" + " Array of numbers to be decomposed.\n" + " out1: ndarray, optional\n" + " Output array for the mantissa. Must have the same shape as `x`.\n" + " out2: ndarray, optional\n" + " Output array for the exponent. Must have the same shape as `x`.\n" + "\n" + " Returns\n" + " -------\n" + " (mantissa, exponent) : tuple of ndarrays, (float, int)\n" + " `mantissa` is a float array with values between -1 and 1.\n" + " `exponent` is an int array which represents the exponent of 2.\n" + "\n" + " See Also\n" + " --------\n" + " ldexp : Compute ``y = x1 * 2**x2``, the inverse of `frexp`.\n" + "\n" + " Notes\n" + " -----\n" + " Complex dtypes are not supported, they will raise a TypeError.\n" + "\n" + " Examples\n" + " --------\n" + " >>> x = np.arange(9)\n" + " >>> y1, y2 = np.frexp(x)\n" + " >>> y1\n" + " array([ 0. , 0.5 , 0.5 , 0.75 , 0.5 , 0.625, 0.75 , 0.875,\n" + " 0.5 ])\n" + " >>> y2\n" + " array([0, 1, 2, 2, 3, 3, 3, 3, 4])\n" + " >>> y1 * 2**y2\n" + " array([ 0., 1., 2., 3., 4., 5., 6., 7., 8.])\n" + "\n"; + + static char ldexp_signatures[] = { #ifdef HAVE_LDEXPF NPY_HALF, NPY_INT, NPY_HALF, @@ -266,6 +310,48 @@ static char ldexp_signatures[] = { #endif }; +static const char lddoc[] = + " Returns x1 * 2**x2, element-wise.\n" + "\n" + " The mantissas `x1` and twos exponents `x2` are used to construct\n" + " floating point numbers ``x1 * 2**x2``.\n" + "\n" + " Parameters\n" + " ----------\n" + " x1 : array_like\n" + " Array of multipliers.\n" + " x2 : array_like, int\n" + " Array of twos exponents.\n" + " out : ndarray, optional\n" + " Output array for the result.\n" + "\n" + " Returns\n" + " -------\n" + " y : ndarray or scalar\n" + " The result of ``x1 * 2**x2``.\n" + "\n" + " See Also\n" + " --------\n" + " frexp : Return (y1, y2) from ``x = y1 * 2**y2``, inverse to `ldexp`.\n" + "\n" + " Notes\n" + " -----\n" + " Complex dtypes are not supported, they will raise a TypeError.\n" + "\n" + " `ldexp` is useful as the inverse of `frexp`, if used by itself it is\n" + " more clear to simply use the expression ``x1 * 2**x2``.\n" + "\n" + " Examples\n" + " --------\n" + " >>> np.ldexp(5, np.arange(4))\n" + " array([ 5., 10., 20., 40.], dtype=float32)\n" + "\n" + " >>> x = np.arange(6)\n" + " >>> np.ldexp(*np.frexp(x))\n" + " array([ 0., 1., 2., 3., 4., 5.])\n" + "\n"; + + static void InitOtherOperators(PyObject *dictionary) { PyObject *f; @@ -274,16 +360,14 @@ InitOtherOperators(PyObject *dictionary) { num = sizeof(frexp_functions) / sizeof(frexp_functions[0]); f = PyUFunc_FromFuncAndData(frexp_functions, blank3_data, frexp_signatures, num, - 1, 2, PyUFunc_None, "frexp", - "Split the number, x, into a normalized"\ - " fraction (y1) and exponent (y2)",0); + 1, 2, PyUFunc_None, "frexp", frdoc, 0); PyDict_SetItemString(dictionary, "frexp", f); Py_DECREF(f); num = sizeof(ldexp_functions) / sizeof(ldexp_functions[0]); - f = PyUFunc_FromFuncAndData(ldexp_functions, blank6_data, ldexp_signatures, num, - 2, 1, PyUFunc_None, "ldexp", - "Compute y = x1 * 2**x2.",0); + f = PyUFunc_FromFuncAndData(ldexp_functions, blank6_data, + ldexp_signatures, num, + 2, 1, PyUFunc_None, "ldexp", lddoc, 0); PyDict_SetItemString(dictionary, "ldexp", f); Py_DECREF(f); diff --git a/numpy/core/tests/test_scalarinherit.py b/numpy/core/tests/test_scalarinherit.py new file mode 100644 index 000000000..6f394196c --- /dev/null +++ b/numpy/core/tests/test_scalarinherit.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +""" Test printing of scalar types. + +""" + +import numpy as np +from numpy.testing import TestCase, run_module_suite + + +class A(object): pass +class B(A, np.float64): pass + +class C(B): pass +class D(C, B): pass + +class B0(np.float64, A): pass +class C0(B0): pass + +class TestInherit(TestCase): + def test_init(self): + x = B(1.0) + assert str(x) == '1.0' + y = C(2.0) + assert str(y) == '2.0' + z = D(3.0) + assert str(z) == '3.0' + def test_init2(self): + x = B0(1.0) + assert str(x) == '1.0' + y = C0(2.0) + assert str(y) == '2.0' + +if __name__ == "__main__": + run_module_suite() diff --git a/numpy/core/tests/test_umath.py b/numpy/core/tests/test_umath.py index 6db95e9a6..8f816169e 100644 --- a/numpy/core/tests/test_umath.py +++ b/numpy/core/tests/test_umath.py @@ -175,6 +175,11 @@ class TestPower(TestCase): x = np.array([1, 2, 3], np.int16) assert_((x**2.00001).dtype is (x**2.0).dtype) + # Check that the fast path ignores 1-element not 0-d arrays + res = x ** np.array([[[2]]]) + assert_equal(res.shape, (1, 1, 3)) + + class TestLog2(TestCase): def test_log2_values(self) : x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] @@ -693,8 +698,8 @@ class TestMinMax(TestCase): assert_equal(inp.min(), -1e10, err_msg=msg) -class TestAbsolute(TestCase): - def test_abs_blocked(self): +class TestAbsoluteNegative(TestCase): + def test_abs_neg_blocked(self): # simd tests on abs, test all alignments for vz + 2 * (vs - 1) + 1 for dt, sz in [(np.float32, 11), (np.float64, 5)]: for out, inp, msg in _gen_alignment_data(dtype=dt, type='unary', @@ -704,6 +709,10 @@ class TestAbsolute(TestCase): assert_equal(out, tgt, err_msg=msg) self.assertTrue((out >= 0).all()) + tgt = [-1*(i) for i in inp] + np.negative(inp, out=out) + assert_equal(out, tgt, err_msg=msg) + # will throw invalid flag depending on compiler optimizations with np.errstate(invalid='ignore'): for v in [np.nan, -np.inf, np.inf]: @@ -716,6 +725,10 @@ class TestAbsolute(TestCase): np.abs(inp, out=out) assert_array_equal(out, d, err_msg=msg) + assert_array_equal(-inp, -1*inp, err_msg=msg) + np.negative(inp, out=out) + assert_array_equal(out, -1*inp, err_msg=msg) + class TestSpecialMethods(TestCase): def test_wrap(self): @@ -900,9 +913,9 @@ class TestSpecialMethods(TestCase): assert_equal(res1[4], (a, b)) assert_equal(res0[5], {}) assert_equal(res1[5], {}) - + def test_ufunc_override_mro(self): - + # Some multi arg functions for testing. def tres_mul(a, b, c): return a * b * c @@ -929,7 +942,7 @@ class TestSpecialMethods(TestCase): class C(object): def __numpy_ufunc__(self, func, method, pos, inputs, **kwargs): return NotImplemented - + class CSub(object): def __numpy_ufunc__(self, func, method, pos, inputs, **kwargs): return NotImplemented @@ -961,7 +974,7 @@ class TestSpecialMethods(TestCase): assert_equal(three_mul_ufunc(a, 1, 2), "A") assert_equal(three_mul_ufunc(1, a, 2), "A") assert_equal(three_mul_ufunc(1, 2, a), "A") - + assert_equal(three_mul_ufunc(a, a, 6), "A") assert_equal(three_mul_ufunc(a, 2, a), "A") assert_equal(three_mul_ufunc(a, 2, b), "A") diff --git a/numpy/distutils/system_info.py b/numpy/distutils/system_info.py index 5ed12db6e..daf416ded 100644 --- a/numpy/distutils/system_info.py +++ b/numpy/distutils/system_info.py @@ -703,7 +703,7 @@ class system_info: else: found_libs = self._lib_list(lib_dirs, libs, exts) found_dirs = [lib_dirs] - if len(found_libs) == len(libs): + if len(found_libs) > 0 and len(found_libs) == len(libs): info = {'libraries': found_libs, 'library_dirs': found_dirs} # Now, check for optional libraries if is_sequence(lib_dirs): @@ -1565,7 +1565,9 @@ class openblas_info(blas_info): def calc_info(self): lib_dirs = self.get_lib_dirs() - openblas_libs = self.get_libs('openblas_libs', self._lib_names) + openblas_libs = self.get_libs('libraries', self._lib_names) + if openblas_libs == self._lib_names: # backward compat with 1.8.0 + openblas_libs = self.get_libs('openblas_libs', self._lib_names) info = self.check_libs(lib_dirs, openblas_libs, []) if info is None: return diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index d9e9554b3..62ced0509 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -373,10 +373,10 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None): if not np.isinf(mindiff): decimal = int(-log10(mindiff)) + 6 # Find which points are on the rightmost edge. - on_edge = where(around(sample[:, i], decimal) == - around(edges[i][-1], decimal))[0] + not_smaller_than_edge = (sample[:, i] >= edges[i][-1]) + on_edge = (around(sample[:, i], decimal) == around(edges[i][-1], decimal)) # Shift these points one bin to the left. - Ncount[i][on_edge] -= 1 + Ncount[i][where(on_edge & not_smaller_than_edge)[0]] -= 1 # Flattened histogram matrix (1D) # Reshape is used so that overlarge arrays @@ -1811,9 +1811,11 @@ def cov(m, y=None, rowvar=1, bias=0, ddof=None): "ddof must be integer") # Handles complex arrays too + m = np.asarray(m) if y is None: dtype = np.result_type(m, np.float64) else: + y = np.asarray(y) dtype = np.result_type(m, y, np.float64) X = array(m, ndmin=2, dtype=dtype) diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py index af259cfef..2310b9be2 100644 --- a/numpy/lib/npyio.py +++ b/numpy/lib/npyio.py @@ -285,21 +285,23 @@ def load(file, mmap_mode=None): Parameters ---------- file : file-like object or string - The file to read. It must support ``seek()`` and ``read()`` methods. - If the filename extension is ``.gz``, the file is first decompressed. + The file to read. Compressed files with the filename extension + ``.gz`` are acceptable. File-like objects must support the + ``seek()`` and ``read()`` methods. Pickled files require that the + file-like object support the ``readline()`` method as well. mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional - If not None, then memory-map the file, using the given mode - (see `numpy.memmap` for a detailed description of the modes). - A memory-mapped array is kept on disk. However, it can be accessed - and sliced like any ndarray. Memory mapping is especially useful for - accessing small fragments of large files without reading the entire - file into memory. + If not None, then memory-map the file, using the given mode (see + `numpy.memmap` for a detailed description of the modes). A + memory-mapped array is kept on disk. However, it can be accessed + and sliced like any ndarray. Memory mapping is especially useful + for accessing small fragments of large files without reading the + entire file into memory. Returns ------- result : array, tuple, dict, etc. - Data stored in the file. For ``.npz`` files, the returned instance of - NpzFile class must be closed to avoid leaking file descriptors. + Data stored in the file. For ``.npz`` files, the returned instance + of NpzFile class must be closed to avoid leaking file descriptors. Raises ------ @@ -308,7 +310,7 @@ def load(file, mmap_mode=None): See Also -------- - save, savez, loadtxt + save, savez, savez_compressed, loadtxt memmap : Create a memory-map to an array stored in a file on disk. Notes @@ -319,13 +321,14 @@ def load(file, mmap_mode=None): - If the file is a ``.npz`` file, then a dictionary-like object is returned, containing ``{filename: array}`` key-value pairs, one for each file in the archive. - - If the file is a ``.npz`` file, the returned value supports the context - manager protocol in a similar fashion to the open function:: + - If the file is a ``.npz`` file, the returned value supports the + context manager protocol in a similar fashion to the open function:: with load('foo.npz') as data: a = data['a'] - The underlying file descriptor is closed when exiting the 'with' block. + The underlying file descriptor is closed when exiting the 'with' + block. Examples -------- @@ -549,6 +552,7 @@ def savez_compressed(file, *args, **kwds): See Also -------- numpy.savez : Save several arrays into an uncompressed ``.npz`` file format + numpy.load : Load the files created by savez_compressed. """ _savez(file, args, kwds, True) @@ -668,6 +672,7 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, The returned array will have at least `ndmin` dimensions. Otherwise mono-dimensional axes will be squeezed. Legal values: 0 (default), 1 or 2. + .. versionadded:: 1.6.0 Returns @@ -911,14 +916,17 @@ def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', .. versionadded:: 1.5.0 header : str, optional String that will be written at the beginning of the file. + .. versionadded:: 1.7.0 footer : str, optional String that will be written at the end of the file. + .. versionadded:: 1.7.0 comments : str, optional String that will be prepended to the ``header`` and ``footer`` strings, to mark them as comments. Default: '# ', as expected by e.g. ``numpy.loadtxt``. + .. versionadded:: 1.7.0 Character separating lines. diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index 953292550..3e102cf6a 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -1155,6 +1155,30 @@ class TestHistogramdd(TestCase): h, e = np.histogramdd(x, bins=[3, [-np.inf, 3, np.inf]]) assert_allclose(h, expected) + def test_rightmost_binedge(self): + """Test event very close to rightmost binedge. + See Github issue #4266""" + x = [0.9999999995] + bins = [[0.,0.5,1.0]] + hist, _ = histogramdd(x, bins=bins) + assert_(hist[0] == 0.0) + assert_(hist[1] == 1.) + x = [1.0] + bins = [[0.,0.5,1.0]] + hist, _ = histogramdd(x, bins=bins) + assert_(hist[0] == 0.0) + assert_(hist[1] == 1.) + x = [1.0000000001] + bins = [[0.,0.5,1.0]] + hist, _ = histogramdd(x, bins=bins) + assert_(hist[0] == 0.0) + assert_(hist[1] == 1.) + x = [1.0001] + bins = [[0.,0.5,1.0]] + hist, _ = histogramdd(x, bins=bins) + assert_(hist[0] == 0.0) + assert_(hist[1] == 0.0) + class TestUnique(TestCase): def test_simple(self): @@ -1204,6 +1228,10 @@ class TestCorrCoef(TestCase): [0.66318558, 0.88157256, 0.71483595, -0.51366032, 1., 0.98317823], [0.51532523, 0.78052386, 0.83053601, -0.66173113, 0.98317823, 1.]]) + def test_non_array(self): + assert_almost_equal(np.corrcoef([0, 1, 0], [1, 0, 1]), + [[1., -1.], [-1., 1.]]) + def test_simple(self): assert_almost_equal(corrcoef(self.A), self.res1) assert_almost_equal(corrcoef(self.A, self.B), self.res2) diff --git a/numpy/random/mtrand/mtrand.pyx b/numpy/random/mtrand/mtrand.pyx index 27689a9e1..4761c6907 100644 --- a/numpy/random/mtrand/mtrand.pyx +++ b/numpy/random/mtrand/mtrand.pyx @@ -984,7 +984,7 @@ cdef class RandomState: >>> np.random.choice(5, 3, replace=False) array([3,1,0]) - >>> #This is equivalent to np.random.shuffle(np.arange(5))[:3] + >>> #This is equivalent to np.random.permutation(np.arange(5))[:3] Generate a non-uniform random sample from np.arange(5) of size 3 without replacement: diff --git a/numpy/testing/utils.py b/numpy/testing/utils.py index 97908c7e8..4905898d2 100644 --- a/numpy/testing/utils.py +++ b/numpy/testing/utils.py @@ -1156,6 +1156,8 @@ def assert_allclose(actual, desired, rtol=1e-7, atol=0, It compares the difference between `actual` and `desired` to ``atol + rtol * abs(desired)``. + .. versionadded:: 1.5.0 + Parameters ---------- actual : array_like @@ -1465,6 +1467,7 @@ class WarningManager(object): self._module.filters = self._filters self._module.showwarning = self._showwarning + def assert_warns(warning_class, func, *args, **kw): """ Fail unless the given callable throws the specified warning. @@ -1474,6 +1477,8 @@ def assert_warns(warning_class, func, *args, **kw): If a different type of warning is thrown, it will not be caught, and the test case will be deemed to have suffered an error. + .. versionadded:: 1.4.0 + Parameters ---------- warning_class : class @@ -1505,6 +1510,8 @@ def assert_no_warnings(func, *args, **kw): """ Fail if the given callable produces any warnings. + .. versionadded:: 1.7.0 + Parameters ---------- func : callable |