[Numpy-discussion] all elements equal

josef.pktd@gmai... josef.pktd@gmai...
Mon Mar 5 13:36:44 CST 2012


On Mon, Mar 5, 2012 at 2:33 PM, Olivier Delalleau <shish@keba.be> wrote:
> Le 5 mars 2012 14:29, Keith Goodman <kwgoodman@gmail.com> a écrit :
>
>> On Mon, Mar 5, 2012 at 11:24 AM, Neal Becker <ndbecker2@gmail.com> wrote:
>> > Keith Goodman wrote:
>> >
>> >> On Mon, Mar 5, 2012 at 11:14 AM, Neal Becker <ndbecker2@gmail.com>
>> >> wrote:
>> >>> What is a simple, efficient way to determine if all elements in an
>> >>> array (in
>> >>> my case, 1D) are equal?  How about close?
>> >>
>> >> For the exactly equal case, how about:
>> >>
>> >> I[1] a = np.array([1,1,1,1])
>> >> I[2] np.unique(a).size
>> >> O[2] 1    # All equal
>> >>
>> >> I[3] a = np.array([1,1,1,2])
>> >> I[4] np.unique(a).size
>> >> O[4] 2   # All not equal
>> >
>> > I considered this - just not sure if it's the most efficient
>>
>> Yeah, it is slow:
>>
>> I[1] a = np.ones(100000)
>> I[2] timeit np.unique(a).size
>> 1000 loops, best of 3: 1.56 ms per loop
>> I[3] timeit (a == a[0]).all()
>> 1000 loops, best of 3: 203 us per loop
>>
>> I think all() short-circuits for bool arrays:
>>
>> I[4] a[1] = 9
>> I[5] timeit (a == a[0]).all()
>> 10000 loops, best of 3: 89 us per loop
>>
>> You could avoid making the bool array by writing a function in cython.
>> It could grab the first array element and then return False as soon as
>> it finds an element that is not equal to it. And you could check for
>> closeness.
>>
>> Or:
>>
>> I[8] np.allclose(a, a[0])
>> O[8] False
>> I[9] a = np.ones(100000)
>> I[10] np.allclose(a, a[0])
>> O[10] True
>
>
> Looks like the following is even faster:
> np.max(a) == np.min(a)

How about numpy.ptp, to follow this line? I would expect it's single
pass, but wouldn't short circuit compared to cython of Keith

Josef


>
> -=- Olivier
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>


More information about the NumPy-Discussion mailing list