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.

aga
  • 27,954
  • 13
  • 86
  • 121
mchangun
  • 9,814
  • 18
  • 71
  • 101

3 Answers3

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)
NPE
  • 486,780
  • 108
  • 951
  • 1,012
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').

hpaulj
  • 221,503
  • 14
  • 230
  • 353
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))
Syed Habib M
  • 1,757
  • 1
  • 17
  • 30