ufunc)¶A universal function (orufunc for short) is a function thatoperates onndarrays in an element-by-element fashion,supportingarray broadcasting,typecasting, and several other standard features. Thatis, a ufunc is a “vectorized” wrapper for a function thattakes a fixed number of specific inputs and produces a fixed number ofspecific outputs.
In NumPy, universal functions are instances of thenumpy.ufunc class. Many of the built-in functions areimplemented in compiled C code. The basic ufuncs operate on scalars, butthere is also a generalized kind for which the basic elements are sub-arrays(vectors, matrices, etc.), and broadcasting is done over other dimensions.One can also produce customufunc instances using thefrompyfunc factory function.
Each universal function takes array inputs and produces array outputsby performing the core function element-wise on the inputs (where anelement is generally a scalar, but can be a vector or higher-ordersub-array for generalized ufuncs). Standardbroadcasting rules are applied so that inputs not sharing exactly thesame shapes can still be usefully operated on. Broadcasting can beunderstood by four rules:
ndim smaller than theinput array of largestndim, have 1’sprepended to their shapes.Broadcasting is used throughout NumPy to decide how to handledisparately shaped arrays; for example, all arithmetic operations (+,-,*, …) betweenndarrays broadcast thearrays before operation.
A set of arrays is called “broadcastable” to the same shape ifthe above rules produce a valid result,i.e., one of the followingis true:
Example
Ifa.shape is (5,1),b.shape is (1,6),c.shape is (6,)andd.shape is () so thatd is a scalar, thena,b,c,andd are all broadcastable to dimension (5,6); and
a[:,0] is broadcast to the othercolumns,b[0,:] is broadcastto the other rows,c[:] is broadcast to every row, and finally,The output of the ufunc (and its methods) is not necessarily anndarray, if all input arguments are notndarrays.Indeed, if any input defines an__array_ufunc__ method,control will be passed completely to that function, i.e., the ufunc isoverridden.
If none of the inputs overrides the ufunc, thenall output arrays will be passed to the__array_prepare__ and__array_wrap__ methods of the input (besidesndarrays, and scalars) that defines itand hasthe highest__array_priority__ of any other input to theuniversal function. The default__array_priority__ of thendarray is 0.0, and the default__array_priority__ of a subtypeis 1.0. Matrices have__array_priority__ equal to 10.0.
All ufuncs can also take output arguments. If necessary, output willbe cast to the data-type(s) of the provided output array(s). If a classwith an__array__ method is used for the output, results will bewritten to the object returned by__array__. Then, if the classalso has an__array_prepare__ method, it is called so metadatamay be determined based on the context of the ufunc (the contextconsisting of the ufunc itself, the arguments passed to the ufunc, andthe ufunc domain.) The array object returned by__array_prepare__ is passed to the ufunc for computation.Finally, if the class also has an__array_wrap__ method, the returnedndarray result will be passed to that method just beforepassing control back to the caller.
Internally, buffers are used for misaligned data, swapped data, anddata that has to be converted from one data type to another. The sizeof internal buffers is settable on a per-thread basis. There canbe up to2 (n_{\mathrm{inputs}} + n_{\mathrm{outputs}})buffers of the specified size created to handle the data from all theinputs and outputs of a ufunc. The default size of a buffer is10,000 elements. Whenever buffer-based calculation would be needed,but all input arrays are smaller than the buffer size, thosemisbehaved or incorrectly-typed arrays will be copied before thecalculation proceeds. Adjusting the size of the buffer may thereforealter the speed at which ufunc calculations of various sorts arecompleted. A simple interface for setting this variable is accessibleusing the function
setbufsize(size) | Set the size of the buffer used in ufuncs. |
Universal functions can trip special floating-point status registersin your hardware (such as divide-by-zero). If available on yourplatform, these registers will be regularly checked duringcalculation. Error handling is controlled on a per-thread basis,and can be configured using the functions
seterr([all, divide, over, under, invalid]) | Set how floating-point errors are handled. |
seterrcall(func) | Set the floating-point error callback function or log object. |
Note
In NumPy 1.6.0, a type promotion API was created to encapsulate themechanism for determining output types. See the functionsresult_type,promote_types, andmin_scalar_type for more details.
At the core of every ufunc is a one-dimensional strided loop thatimplements the actual function for a specific type combination. When aufunc is created, it is given a static list of inner loops and acorresponding list of type signatures over which the ufunc operates.The ufunc machinery uses this list to determine which inner loop touse for a particular case. You can inspect the.types attribute for a particular ufunc to see which typecombinations have a defined inner loop and which output type theyproduce (character codes are usedin said output for brevity).
Casting must be done on one or more of the inputs whenever the ufuncdoes not have a core loop implementation for the input types provided.If an implementation for the input types cannot be found, then thealgorithm searches for an implementation with a type signature towhich all of the inputs can be cast “safely.” The first one it findsin its internal list of loops is selected and performed, after allnecessary type casting. Recall that internal copies during ufuncs (evenfor casting) are limited to the size of an internal buffer (which is usersettable).
Note
Universal functions in NumPy are flexible enough to have mixed typesignatures. Thus, for example, a universal function could be definedthat works with floating-point and integer values. Seeldexpfor an example.
By the above description, the casting rules are essentiallyimplemented by the question of when a data type can be cast “safely”to another data type. The answer to this question can be determined inPython with a function call:can_cast(fromtype,totype). The Figure below shows the results of this call forthe 24 internally supported types on the author’s 64-bit system. Youcan generate this table for your system with the code given in the Figure.
Figure
Code segment showing the “can cast safely” table for a 32-bit system.
>>>defprint_table(ntypes):...print'X',...forcharinntypes:printchar,...print...forrowinntypes:...printrow,...forcolinntypes:...printint(np.can_cast(row,col)),...print>>>print_table(np.typecodes['All'])X ? b h i l q p B H I L Q P e f d g F D G S U V O M m? 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1b 0 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0h 0 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0i 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 0l 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 0q 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 0p 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 0B 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0H 0 0 0 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 0I 0 0 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 0 1 1 1 1 1 1 0 0L 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 0 1 1 1 1 1 1 0 0Q 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 0 1 1 1 1 1 1 0 0P 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 0 1 1 1 1 1 1 0 0e 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0f 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0d 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 0g 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 1 1 1 0 0F 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0D 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0G 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0S 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0U 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0V 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0O 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0M 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0m 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
You should note that, while included in the table for completeness,the ‘S’, ‘U’, and ‘V’ types cannot be operated on by ufuncs. Also,note that on a 32-bit system the integer types may have differentsizes, resulting in a slightly altered table.
Mixed scalar-array operations use a different set of casting rulesthat ensure that a scalar cannot “upcast” an array unless the scalar isof a fundamentally different kind of data (i.e., under a differenthierarchy in the data-type hierarchy) than the array. This ruleenables you to use scalar constants in your code (which, as Pythontypes, are interpreted accordingly in ufuncs) without worrying aboutwhether the precision of the scalar constant will cause upcasting onyour large (small precision) array.
Classes (including ndarray subclasses) can override how ufuncs act onthem by defining certain special methods. For details, seeStandard array subclasses.
ufunc¶All ufuncs take optional keyword arguments. Most of these representadvanced usage and will not typically be used.
out
New in version 1.6.
The first output can be provided as either a positional or a keywordparameter. Keyword ‘out’ arguments are incompatible with positionalones.
New in version 1.10.
The ‘out’ keyword argument is expected to be a tuple with one entry peroutput (which can beNone for arrays to be allocated by the ufunc).For ufuncs with a single output, passing a single array (instead of atuple holding a single array) is also valid.
Passing a single array in the ‘out’ keyword argument to a ufunc withmultiple outputs is deprecated, and will raise a warning in numpy 1.10,and an error in a future release.
If ‘out’ is None (the default), a uninitialized return array is created.The output array is then filled with the results of the ufunc in the placesthat the broadcast ‘where’ is True. If ‘where’ is the scalar True (thedefault), then this corresponds to the entire output being filled.Note that outputs not explicitly filled are left with theiruninitialized values.
where
New in version 1.7.
Accepts a boolean array which is broadcast together with the operands.Values of True indicate to calculate the ufunc at that position, valuesof False indicate to leave the value in the output alone. This argumentcannot be used for generalized ufuncs as those take non-scalar input.
Note that if an uninitialized return array is created, values of Falsewill leave those valuesuninitialized.
axes
New in version 1.15.
A list of tuples with indices of axes a generalized ufunc should operateon. For instance, for a signature of
(i,j),(j,k)->(i,k)appropriatefor matrix multiplication, the base elements are two-dimensional matricesand these are taken to be stored in the two last axes of each argument.The corresponding axes keyword would be[(-2,-1),(-2,-1),(-2,-1)].For simplicity, for generalized ufuncs that operate on 1-dimensional arrays(vectors), a single integer is accepted instead of a single-element tuple,and for generalized ufuncs for which all outputs are scalars, the outputtuples can be omitted.
axis
New in version 1.15.
A single axis over which a generalized ufunc should operate. This is ashort-cut for ufuncs that operate over a single, shared core dimension,equivalent to passing in
axeswith entries of(axis,)for eachsingle-core-dimension argument and()for all others. For instance,for a signature(i),(i)->(), it is equivalent to passing inaxes=[(axis,),(axis,),()].
keepdims
New in version 1.15.
If this is set toTrue, axes which are reduced over will be left in theresult as a dimension with size one, so that the result will broadcastcorrectly against the inputs. This option can only be used for generalizedufuncs that operate on inputs that all have the same number of coredimensions and with outputs that have no core dimensions , i.e., withsignatures like
(i),(i)->()or(m,m)->(). If used, the location ofthe dimensions in the output can be controlled withaxesandaxis.
casting
New in version 1.6.
May be ‘no’, ‘equiv’, ‘safe’, ‘same_kind’, or ‘unsafe’.See
can_castfor explanations of the parameter values.Provides a policy for what kind of casting is permitted. For compatibilitywith previous versions of NumPy, this defaults to ‘unsafe’ for numpy < 1.7.In numpy 1.7 a transition to ‘same_kind’ was begun where ufuncs produce aDeprecationWarning for calls which are allowed under the ‘unsafe’rules, but not under the ‘same_kind’ rules. From numpy 1.10 andonwards, the default is ‘same_kind’.
order
New in version 1.6.
Specifies the calculation iteration order/memory layout of the output array.Defaults to ‘K’. ‘C’ means the output should be C-contiguous, ‘F’ meansF-contiguous, ‘A’ means F-contiguous if the inputs are F-contiguous andnot also not C-contiguous, C-contiguous otherwise, and ‘K’ means to matchthe element ordering of the inputs as closely as possible.
dtype
New in version 1.6.
Overrides the dtype of the calculation and output arrays. Similar tosignature.
subok
New in version 1.6.
Defaults to true. If set to false, the output will always be a strictarray, not a subtype.
signature
Either a data-type, a tuple of data-types, or a special signaturestring indicating the input and output types of a ufunc. This argumentallows you to provide a specific signature for the 1-d loop to usein the underlying calculation. If the loop specified does not existfor the ufunc, then a TypeError is raised. Normally, a suitable loop isfound automatically by comparing the input types with what isavailable and searching for a loop with data-types to which all inputscan be cast safely. This keyword argument lets you bypass thatsearch and choose a particular loop. A list of available signatures isprovided by thetypes attribute of the ufunc object. For backwardscompatibility this argument can also be provided assig, althoughthe long form is preferred. Note that this should not be confused withthe generalized ufuncsignature that isstored in thesignature attribute of the of the ufunc object.
extobj
a list of length 1, 2, or 3 specifying the ufunc buffer-size, theerror mode integer, and the error call-back function. Normally, thesevalues are looked up in a thread-specific dictionary. Passing themhere circumvents that look up and uses the low-level specificationprovided for the error mode. This may be useful, for example, as anoptimization for calculations requiring many ufunc calls on small arraysin a loop.
There are some informational attributes that universal functionspossess. None of the attributes can be set.
| __doc__ | A docstring for each ufunc. The first part of the docstring isdynamically generated from the number of outputs, the name, andthe number of inputs. The second part of the docstring isprovided at creation time and stored with the ufunc. |
| __name__ | The name of the ufunc. |
ufunc.nin | The number of inputs. |
ufunc.nout | The number of outputs. |
ufunc.nargs | The number of arguments. |
ufunc.ntypes | The number of types. |
ufunc.types | Returns a list with types grouped input->output. |
ufunc.identity | The identity value. |
ufunc.signature | Definition of the core elements a generalized ufunc operates on. |
All ufuncs have four methods. However, these methods only make sense on scalarufuncs that take two input arguments and return one output argument.Attempting to call these methods on other ufuncs will cause aValueError. The reduce-like methods all take anaxis keyword, adtypekeyword, and anout keyword, and the arrays must all have dimension >= 1.Theaxis keyword specifies the axis of the array over which the reductionwill take place (with negative values counting backwards). Generally, it is aninteger, though forufunc.reduce, it can also be a tuple ofint toreduce over several axes at once, orNone, to reduce over all axes.Thedtype keyword allows you to manage a very common problem that ariseswhen naively usingufunc.reduce. Sometimes you mayhave an array of a certain data type and wish to add up all of itselements, but the result does not fit into the data type of thearray. This commonly happens if you have an array of single-byteintegers. Thedtype keyword allows you to alter the data type over whichthe reduction takes place (and therefore the type of the output). Thus,you can ensure that the output is a data type with precision large enoughto handle your output. The responsibility of altering the reduce type ismostly up to you. There is one exception: if nodtype is given for areduction on the “add” or “multiply” operations, then if the input type isan integer (or Boolean) data-type and smaller than the size of theint_ data type, it will be internally upcast to theint_(oruint) data-type. Finally, theout keyword allows you to providean output array (for single-output ufuncs, which are currently the only onessupported; for future extension, however, a tuple with a single argumentcan be passed in). Ifout is given, thedtype argument is ignored.
Ufuncs also have a fifth method that allows in place operations to beperformed using fancy indexing. No buffering is used on the dimensions wherefancy indexing is used, so the fancy index can list an item more than once andthe operation will be performed on the result of the previous operation forthat item.
ufunc.reduce(a[, axis, dtype, out, keepdims]) | Reducesa’s dimension by one, by applying ufunc along one axis. |
ufunc.accumulate(array[, axis, dtype, out]) | Accumulate the result of applying the operator to all elements. |
ufunc.reduceat(a, indices[, axis, dtype, out]) | Performs a (local) reduce with specified slices over a single axis. |
ufunc.outer(A, B, **kwargs) | Apply the ufuncop to all pairs (a, b) with a inA and b inB. |
ufunc.at(a, indices[, b]) | Performs unbuffered in place operation on operand ‘a’ for elements specified by ‘indices’. |
Warning
A reduce-like operation on an array with a data-type that has arange “too small” to handle the result will silently wrap. Oneshould usedtype to increase the size of the data-type over whichreduction takes place.
There are currently more than 60 universal functions defined innumpy on one or more types, covering a wide variety ofoperations. Some of these ufuncs are called automatically on arrayswhen the relevant infix notation is used (e.g.,add(a,b)is called internally whena+b is written anda orb is anndarray). Nevertheless, you may still want to use the ufunccall in order to use the optional output argument(s) to place theoutput(s) in an object (or objects) of your choice.
Recall that each ufunc operates element-by-element. Therefore, each scalarufunc will be described as if acting on a set of scalar inputs toreturn a set of scalar outputs.
Note
The ufunc still returns its output(s) even if you use the optionaloutput argument(s).
add(x1, x2, /[, out, where, casting, order, …]) | Add arguments element-wise. |
subtract(x1, x2, /[, out, where, casting, …]) | Subtract arguments, element-wise. |
multiply(x1, x2, /[, out, where, casting, …]) | Multiply arguments element-wise. |
divide(x1, x2, /[, out, where, casting, …]) | Returns a true division of the inputs, element-wise. |
logaddexp(x1, x2, /[, out, where, casting, …]) | Logarithm of the sum of exponentiations of the inputs. |
logaddexp2(x1, x2, /[, out, where, casting, …]) | Logarithm of the sum of exponentiations of the inputs in base-2. |
true_divide(x1, x2, /[, out, where, …]) | Returns a true division of the inputs, element-wise. |
floor_divide(x1, x2, /[, out, where, …]) | Return the largest integer smaller or equal to the division of the inputs. |
negative(x, /[, out, where, casting, order, …]) | Numerical negative, element-wise. |
positive(x, /[, out, where, casting, order, …]) | Numerical positive, element-wise. |
power(x1, x2, /[, out, where, casting, …]) | First array elements raised to powers from second array, element-wise. |
remainder(x1, x2, /[, out, where, casting, …]) | Return element-wise remainder of division. |
mod(x1, x2, /[, out, where, casting, order, …]) | Return element-wise remainder of division. |
fmod(x1, x2, /[, out, where, casting, …]) | Return the element-wise remainder of division. |
divmod(x1, x2[, out1, out2], / [[, out, …]) | Return element-wise quotient and remainder simultaneously. |
absolute(x, /[, out, where, casting, order, …]) | Calculate the absolute value element-wise. |
fabs(x, /[, out, where, casting, order, …]) | Compute the absolute values element-wise. |
rint(x, /[, out, where, casting, order, …]) | Round elements of the array to the nearest integer. |
sign(x, /[, out, where, casting, order, …]) | Returns an element-wise indication of the sign of a number. |
heaviside(x1, x2, /[, out, where, casting, …]) | Compute the Heaviside step function. |
conj(x, /[, out, where, casting, order, …]) | Return the complex conjugate, element-wise. |
exp(x, /[, out, where, casting, order, …]) | Calculate the exponential of all elements in the input array. |
exp2(x, /[, out, where, casting, order, …]) | Calculate2**p for allp in the input array. |
log(x, /[, out, where, casting, order, …]) | Natural logarithm, element-wise. |
log2(x, /[, out, where, casting, order, …]) | Base-2 logarithm ofx. |
log10(x, /[, out, where, casting, order, …]) | Return the base 10 logarithm of the input array, element-wise. |
expm1(x, /[, out, where, casting, order, …]) | Calculateexp(x)-1 for all elements in the array. |
log1p(x, /[, out, where, casting, order, …]) | Return the natural logarithm of one plus the input array, element-wise. |
sqrt(x, /[, out, where, casting, order, …]) | Return the non-negative square-root of an array, element-wise. |
square(x, /[, out, where, casting, order, …]) | Return the element-wise square of the input. |
cbrt(x, /[, out, where, casting, order, …]) | Return the cube-root of an array, element-wise. |
reciprocal(x, /[, out, where, casting, …]) | Return the reciprocal of the argument, element-wise. |
gcd(x1, x2, /[, out, where, casting, order, …]) | Returns the greatest common divisor of|x1| and|x2| |
lcm(x1, x2, /[, out, where, casting, order, …]) | Returns the lowest common multiple of|x1| and|x2| |
Tip
The optional output arguments can be used to help you save memoryfor large calculations. If your arrays are large, complicatedexpressions can take longer than absolutely necessary due to thecreation and (later) destruction of temporary calculationspaces. For example, the expressionG=a*b+c is equivalent tot1=A*B;G=T1+C;delt1. It will be more quickly executedasG=A*B;add(G,C,G) which is the same asG=A*B;G+=C.
All trigonometric functions use radians when an angle is called for.The ratio of degrees to radians is180^{\circ}/\pi.
sin(x, /[, out, where, casting, order, …]) | Trigonometric sine, element-wise. |
cos(x, /[, out, where, casting, order, …]) | Cosine element-wise. |
tan(x, /[, out, where, casting, order, …]) | Compute tangent element-wise. |
arcsin(x, /[, out, where, casting, order, …]) | Inverse sine, element-wise. |
arccos(x, /[, out, where, casting, order, …]) | Trigonometric inverse cosine, element-wise. |
arctan(x, /[, out, where, casting, order, …]) | Trigonometric inverse tangent, element-wise. |
arctan2(x1, x2, /[, out, where, casting, …]) | Element-wise arc tangent ofx1/x2 choosing the quadrant correctly. |
hypot(x1, x2, /[, out, where, casting, …]) | Given the “legs” of a right triangle, return its hypotenuse. |
sinh(x, /[, out, where, casting, order, …]) | Hyperbolic sine, element-wise. |
cosh(x, /[, out, where, casting, order, …]) | Hyperbolic cosine, element-wise. |
tanh(x, /[, out, where, casting, order, …]) | Compute hyperbolic tangent element-wise. |
arcsinh(x, /[, out, where, casting, order, …]) | Inverse hyperbolic sine element-wise. |
arccosh(x, /[, out, where, casting, order, …]) | Inverse hyperbolic cosine, element-wise. |
arctanh(x, /[, out, where, casting, order, …]) | Inverse hyperbolic tangent element-wise. |
deg2rad(x, /[, out, where, casting, order, …]) | Convert angles from degrees to radians. |
rad2deg(x, /[, out, where, casting, order, …]) | Convert angles from radians to degrees. |
These function all require integer arguments and they manipulate thebit-pattern of those arguments.
bitwise_and(x1, x2, /[, out, where, …]) | Compute the bit-wise AND of two arrays element-wise. |
bitwise_or(x1, x2, /[, out, where, casting, …]) | Compute the bit-wise OR of two arrays element-wise. |
bitwise_xor(x1, x2, /[, out, where, …]) | Compute the bit-wise XOR of two arrays element-wise. |
invert(x, /[, out, where, casting, order, …]) | Compute bit-wise inversion, or bit-wise NOT, element-wise. |
left_shift(x1, x2, /[, out, where, casting, …]) | Shift the bits of an integer to the left. |
right_shift(x1, x2, /[, out, where, …]) | Shift the bits of an integer to the right. |
greater(x1, x2, /[, out, where, casting, …]) | Return the truth value of (x1 > x2) element-wise. |
greater_equal(x1, x2, /[, out, where, …]) | Return the truth value of (x1 >= x2) element-wise. |
less(x1, x2, /[, out, where, casting, …]) | Return the truth value of (x1 < x2) element-wise. |
less_equal(x1, x2, /[, out, where, casting, …]) | Return the truth value of (x1 =< x2) element-wise. |
not_equal(x1, x2, /[, out, where, casting, …]) | Return (x1 != x2) element-wise. |
equal(x1, x2, /[, out, where, casting, …]) | Return (x1 == x2) element-wise. |
Warning
Do not use the Python keywordsand andor to combinelogical array expressions. These keywords will test the truthvalue of the entire array (not element-by-element as you mightexpect). Use the bitwise operators & and | instead.
logical_and(x1, x2, /[, out, where, …]) | Compute the truth value of x1 AND x2 element-wise. |
logical_or(x1, x2, /[, out, where, casting, …]) | Compute the truth value of x1 OR x2 element-wise. |
logical_xor(x1, x2, /[, out, where, …]) | Compute the truth value of x1 XOR x2, element-wise. |
logical_not(x, /[, out, where, casting, …]) | Compute the truth value of NOT x element-wise. |
Warning
The bit-wise operators & and | are the proper way to performelement-by-element array comparisons. Be sure you understand theoperator precedence:(a>2)&(a<5) is the proper syntax becausea>2&a<5 will result in an error due to the fact that2&ais evaluated first.
maximum(x1, x2, /[, out, where, casting, …]) | Element-wise maximum of array elements. |
Tip
The Python functionmax() will find the maximum over a one-dimensionalarray, but it will do so using a slower sequence interface. The reducemethod of the maximum ufunc is much faster. Also, themax() methodwill not give answers you might expect for arrays with greater thanone dimension. The reduce method of minimum also allows you to computea total minimum over an array.
minimum(x1, x2, /[, out, where, casting, …]) | Element-wise minimum of array elements. |
Warning
the behavior ofmaximum(a,b) is different than that ofmax(a,b).As a ufunc,maximum(a,b) performs an element-by-element comparisonofa andb and chooses each element of the result according to whichelement in the two arrays is larger. In contrast,max(a,b) treatsthe objectsa andb as a whole, looks at the (total) truth value ofa>b and uses it to return eithera orb (as a whole). A similardifference exists betweenminimum(a,b) andmin(a,b).
fmax(x1, x2, /[, out, where, casting, …]) | Element-wise maximum of array elements. |
fmin(x1, x2, /[, out, where, casting, …]) | Element-wise minimum of array elements. |
Recall that all of these functions work element-by-element over anarray, returning an array output. The description details only asingle operation.
isfinite(x, /[, out, where, casting, order, …]) | Test element-wise for finiteness (not infinity or not Not a Number). |
isinf(x, /[, out, where, casting, order, …]) | Test element-wise for positive or negative infinity. |
isnan(x, /[, out, where, casting, order, …]) | Test element-wise for NaN and return result as a boolean array. |
isnat(x, /[, out, where, casting, order, …]) | Test element-wise for NaT (not a time) and return result as a boolean array. |
fabs(x, /[, out, where, casting, order, …]) | Compute the absolute values element-wise. |
signbit(x, /[, out, where, casting, order, …]) | Returns element-wise True where signbit is set (less than zero). |
copysign(x1, x2, /[, out, where, casting, …]) | Change the sign of x1 to that of x2, element-wise. |
nextafter(x1, x2, /[, out, where, casting, …]) | Return the next floating-point value after x1 towards x2, element-wise. |
spacing(x, /[, out, where, casting, order, …]) | Return the distance between x and the nearest adjacent number. |
modf(x[, out1, out2], / [[, out, where, …]) | Return the fractional and integral parts of an array, element-wise. |
ldexp(x1, x2, /[, out, where, casting, …]) | Returns x1 * 2**x2, element-wise. |
frexp(x[, out1, out2], / [[, out, where, …]) | Decompose the elements of x into mantissa and twos exponent. |
fmod(x1, x2, /[, out, where, casting, …]) | Return the element-wise remainder of division. |
floor(x, /[, out, where, casting, order, …]) | Return the floor of the input, element-wise. |
ceil(x, /[, out, where, casting, order, …]) | Return the ceiling of the input, element-wise. |
trunc(x, /[, out, where, casting, order, …]) | Return the truncated value of the input, element-wise. |