Search code examples
pythonarraysnumpyceil

Applying math.ceil to an array in python


What is the proper way to apply math.ceil to an entire array? See the following Python code:

    index = np.zeros(len(any_array))
    index2 = [random.random() for x in xrange(len(any_array))
    ##indexfinal=math.ceil(index2)  <-?

And I want to return the ceiling value of every element within the array. Documentation states that math.ceil returns the ceiling for any input x, but what is the best method of applying this ceiling function to every element contained within the array?


Solution

  • Use the numpy.ceil() function instead. The Numpy package offers vectorized versions of most of the standard math functions.

    In [29]: import numpy as np
    In [30]: a = np.arange(2, 3, 0.1)
    In [31]: a
    Out[31]: array([ 2. ,  2.1,  2.2,  2.3,  2.4,  2.5,  2.6,  2.7,  2.8,  2.9])
    
    In [32]: np.ceil(a)
    Out[32]: array([ 2.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.])
    

    This technique should work on arbitrary ndarray objects:

    In [53]: a2 = np.indices((3,3)) * 0.9
    
    In [54]: a2
    Out[54]:
    array([[[ 0. ,  0. ,  0. ],
            [ 0.9,  0.9,  0.9],
            [ 1.8,  1.8,  1.8]],
    
           [[ 0. ,  0.9,  1.8],
            [ 0. ,  0.9,  1.8],
            [ 0. ,  0.9,  1.8]]])
    
    In [55]: np.ceil(a2)
    Out[55]:
    array([[[ 0.,  0.,  0.],
            [ 1.,  1.,  1.],
            [ 2.,  2.,  2.]],
    
           [[ 0.,  1.,  2.],
            [ 0.,  1.,  2.],
            [ 0.,  1.,  2.]]])