Extend vector ops to boolean operators?

bearophile bearophileHUGS at lycos.com
Tue Mar 6 20:03:34 PST 2012


James Miller:

> What? I'm assuming you mean that you expect an array of `bool`s?

Right. Vector operations like a[]<b[] are meant to return an array of bools. To see how this is useful you probably must think in terms of vector-style programming. In NumPy the use of arrays of booleans is common:

>>> from numpy import *
>>> a = array([3,6,8,9])
>>> a == 6
array([False,  True, False, False], dtype=bool)
>>> a >= 7
array([False, False,  True,  True], dtype=bool)
>>> a < 5
array([ True, False, False, False], dtype=bool)
>>> # count all the even numbers
>>> sum( (a%2) == 0 )
2
>>> b = array([2,6,7,10])
>>> a == b
array([False,  True, False, False], dtype=bool)
>>> a < b
array([False, False, False,  True], dtype=bool)


They are sometimes used as masks, it's useful if you have a Vector type that supports multi-index syntax:

i = scipy.array([0,1,2,1]) # array of indices for the first axis
j = scipy.array([1,2,3,4]) # array of indices for the second axis
a[i,j] # return array([a[0,1], a[1,2], a[2,3], a[1,4]])
b = scipy.array([True, False, True, False])
a[b] # return array([a[0], a[2]]) since only b[0] and b[2] are True


Using the new CPU AVX registers you are able to perform a loop and work on the items of an array in parallel until all the booleans of an array are false. See this, expecially Listing 5:

http://software.intel.com/en-us/articles/introduction-to-intel-advanced-vector-extensions/

http://www.cs.uaf.edu/2011/spring/cs641/lecture/04_12_AVX.html

Vector comparisons have a natural hardware implementataion with AVX/AVX2 instructions like _mm256_cmp_ps.

Bye,
bearophile


More information about the Digitalmars-d mailing list