4

I'm observing very odd behavior of the function array_equal from NumPy. I'm sure I'm missing a very simple detail.

What I'm trying to accomplish is a unit test.

The facts is, I have array 1:

In[21]: bounds['lowerBound']

Out[21]: array([ 1. ,  1.2,  1.8])

And I have array 2:

In[22]: res['lowerBound']

Out[22]: array([ 1. ,  1.2,  1.8])

And just in case I did check their shapes:

In[26]: bounds['lowerBound'].shape
Out[26]: (3,)
In[28]: res['lowerBound'].shape
Out[28]: (3,)

Also the dtypes:

In[30]: res['lowerBound'].dtype
Out[30]: dtype('float64')
In[31]: bounds['lowerBound'].dtype
Out[31]: dtype('float64')

and still when I try to verify if they are the same:

In[29]:  np.array_equal(bounds['lowerBound'],res['lowerBound'])
Out[29]: False

How can that be ?

thanks in advance !

EDIT: The code used to generate the data is:

bounds={'lowerBound':np.array([1.,1.2,1.8]), 'upperBound':np.array([10.,12.,18.])}

And the res dictionary is generated by the following function:

def generateAdjustedBounds(self,universeMktCap,lowerBound,upperBound):
    lb=np.zeros(len(universeMktCap))
    ub=np.zeros(len(universeMktCap))
    lb[0]=lowerBound
    ub[0]=upperBound

    for dat in range(1,len(lb)):
        lb[dat]=lb[dat-1]*universeMktCap[dat]/universeMktCap[dat-1]
        ub[dat]=ub[dat-1]*universeMktCap[dat]/universeMktCap[dat-1]

    Bounds={'lowerBound':np.array(lb),'upperBound':np.array(ub)}

    return Bounds
Pedro Braz
  • 2,261
  • 3
  • 25
  • 48

1 Answers1

8

Because your elements are floats, you should probably use allclose() instead.

http://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html

Chad Kennedy
  • 1,716
  • 13
  • 16
  • It works ! thanks ! when is it advisable to use array_equal though ? – Pedro Braz Sep 21 '15 at 13:29
  • 1
    Use array_equal when your array contains integers. – Chad Kennedy Sep 21 '15 at 13:33
  • This occurs because any two floats that should represent the same number often don't, when small rounding errors are introduced in mathematically equivalent calculations. [Here are some examples.](https://stackoverflow.com/questions/249467/what-is-a-simple-example-of-floating-point-rounding-error) – Kyle Oct 09 '17 at 21:20