15

From the NumPy docs for ceil , the numpy.ceil function takes two arguments, the second being out. The docs don't say what this out parameter does but I assume you can set the output type this function returns, but I cannot get it to work:

In [107]: np.ceil(5.5, 'int')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-107-c05bcf9f1522> in <module>()
----> 1 np.ceil(5.5, 'int')

TypeError: return arrays must be of ArrayType

In [108]: np.ceil(5.5, 'int64')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-108-0937d09b0433> in <module>()
----> 1 np.ceil(5.5, 'int64')

TypeError: return arrays must be of ArrayType

Is it possible to use this argument to make np.ceil return an integer?

Thanks.

0

3 Answers 3

12

out is the output array (which must have the same shape as the input).

If you construct it to be of the desired dtype, that'll be the dtype you get:

>>> arr = np.array([5.5, -7.2])
>>> out = np.empty_like(arr, dtype=np.int64)
>>> np.ceil(arr, out)
array([ 6, -7], dtype=int64)
>>> out
array([ 6, -7], dtype=int64)
10

np.ceil is one of the ufuncs. The general documentation for this category is:

op(X, out=None)
Apply op to X elementwise

Parameters
----------
X : array_like
    Input array.
out : array_like
    An array to store the output. Must be the same shape as `X`.

Returns
-------
r : array_like
    `r` will have the same shape as `X`; if out is provided, `r`
    will be equal to out.

out and r are different ways of getting the function output. The simplest is to just let the function return the value. But sometimes you may want give it the array out which it will fill. Controlling the dtype is one reason to use out. Another is to conserve memory by 'reusing' an array that already exists.

The array returned by np.ceil can also be cast to your desired type, e.g. np.ceil(x).astype('int').

3

You don't specify return type. Try This

np.int64(np.ceil(5.5))
np.int(np.ceil(5.5))
np.int(np.ceil(-7.2))
2
  • this results in 5.0 while OP's ceil will return 6.0
    – alko
    Nov 18, 2013 at 7:03
  • This results in 6, 6and -7 respectively. Mar 11, 2016 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.