[SciPy-user] "Approximately equal to" operator?
Martin Spacek
scipy at mspacek.mm.st
Wed Jun 7 23:20:22 CDT 2006
Hello,
I'm comparing two numpy 1d arrays of the same length. One has ints, the
other floats. From what I can tell, using == isn't very reliable when
mixing ints and floats. Sometimes 1.0 == 1, and sometimes it doesn't.
For example:
[mspacek]|71> arange(10, 13)
<71> array([10, 11, 12])
[mspacek]|72> arange(10, 13, 0.1)[[0, 10, 20]]
<72> array([ 10., 11., 12.])
[mspacek]|73> arange(10, 13, 0.1)[[0, 10, 20]] == arange(10,13)
<73> array([True, False, False], dtype=bool)
In this case, 10 == 10.0, but 11 != 11.0 and 12 != 12.0
I guess comparing ints to floats is a touchy thing, and depends on the
system's C libraries. Maybe minuscule errors accumulate when building up
a float array using arange(). Anyways, rounding and then converting the
float array into an int array doesn't seem very Pythonic. I've noticed
there's a numpy function allclose(), but this doesn't return a boolean
array, just a single True if all the elements are equal.
Is there a "~=" or "approximately equal to" operator that does an
elementwise comparison of two arrays, and given a certain tolerance,
returns a boolean array?
Cheers,
Martin
More information about the SciPy-user
mailing list