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
3
  • 1
    What are the dtypes here, can you post code to create your arrays Commented Sep 21, 2015 at 13:22
  • it is quite extensive. But I'll check for dtypes. I'm quite new to python... give me a sec ! thanks ! Commented Sep 21, 2015 at 13:23
  • Use np.set_printoptions(precision=16) to see the difference between the values. Commented Sep 21, 2015 at 13:37

1 Answer 1

8

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

It works ! thanks ! when is it advisable to use array_equal though ?
Use array_equal when your array contains integers.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.