title: SSE: reciprocal if not zero
body: <p>How can I take the reciprocal (inverse) of floats with SSE instructions, but <strong>only for non-zero</strong> values?</p>
  
  <p><em>Background bellow:</em></p>
  
  <p>I want to normalize an array of vectors so that each dimension has the same average. In C this can be coded as:</p>
  
  <pre><code>float vectors[num * dim]; // input data
  
  // step 1. compute the sum on each dimension
  float norm[dim];
  memset(norm, 0, dim * sizeof(float));
  for(int i = 0; i &lt; num; i++) for(int j = 0; j &lt; dims; j++)
      norm[j] += vectors[i * dims + j];
  // step 2. convert sums to reciprocal of average
  for(int j = 0; j &lt; dims; j++) if(norm[j]) norm[j] = float(num) / norm[j];
  // step 3. normalize the data
  for(int i = 0; i &lt; num; i++) for(int j = 0; j &lt; dims; j++)
      vectors[i * dims + j] *= norm[j];
  </code></pre>
  
  <p>Now for performance reasons, I want to do this using SSE intinsics. Setp 1 et step 3 are easy, but I'm stuck at step 2. I don't seem to find any code sample or obvious SSE instruction to take the recirpocal of a value <strong>if</strong> it is not zero.
  For the division, _mm_rcp_ps does the trick, and maybe combine it with a conditional move, but how to get a mask indicating which component is zero?</p>
  
  <p>I don't need the code to the algorithm described above, just the "inverse if not zero" function:</p>
  
  <pre><code>__m128 rcp_nz_ps(__m128 input) {
      // ????
  }
  </code></pre>
  
  <p>Thanks!</p>