jeudi 2 juillet 2020

Numpy array equality boolean

The following two approaches should yield an identical result, but it seems they do not:

Approach 1:

#Generate an array with 12 annual fractions corresponding to each month
ann_frac = np.arange(1,13,1).reshape([12,1])
ann_frac[:,0]/12

Output:

array([0.08333333, 0.16666667, 0.25      , 0.33333333, 0.41666667,
       0.5       , 0.58333333, 0.66666667, 0.75      , 0.83333333,
       0.91666667, 1.        ])

Approach 2:

i = np.arange(1,13,1)
ann_frac2 = (i/12).reshape([12,1])

Output:

array([[0.08333333],
       [0.16666667],
       [0.25      ],
       [0.33333333],
       [0.41666667],
       [0.5       ],
       [0.58333333],
       [0.66666667],
       [0.75      ],
       [0.83333333],
       [0.91666667],
       [1.        ]])

Comparing approaches:

ann_frac2==ann_frac

Output:

array([[False],
       [False],
       [False],
       [False],
       [False],
       [False],
       [False],
       [False],
       [False],
       [False],
       [False],
       [False]])

A bit strange it seems. Any explanation? Obviously, if one just wants to compare numbers in two different arrays for equlity, the example above demonstrates that even though the numbers can be identical, the way the numbers were created and stored can produce an unexpected behaviour.




Aucun commentaire:

Enregistrer un commentaire