title: Arduino: float function returns inf
body: <p>I have a function (shown below) that I need some advice on. The function returns the slope of a line which is fit (via the least squares method) to n data points. To give you a context, my project is a barometric pressure based altimeter which uses this function to determine velocity based on the n most recent altitude-time pairs. These altitude-time pairs are stored in 2 global arrays(<code>times[]</code> and <code>alts[]</code>).</p>
  
  <p>My problem is not that this method doesn't work. It usually does. But sometimes I will run the altimeter and this function will return the value <code>'inf'</code> interspersed with a bunch of other wrong values (I have also seen 'NaN' but that is more rare). There are a few areas of suspicion I have at this point but I would like a fresh perspective. Here is some further contextual information that may or may not be of use:</p>
  
  <ul>
  <li>I am using interrupts for a quadrature encoder</li>
  <li>The <code>times[]</code> array is of type <code>unsigned long</code></li>
  <li>The <code>alts[]</code> array is of type <code>float</code></li>
  <li><code>n</code> is a <code>const int</code>, in this case <code>n = 9</code></li>
  <li><p>On the ATMEGA328 a <code>double</code> is the same as a <code>float</code>.. <a href="https://www.arduino.cc/en/Reference/Double" rel="nofollow">Arduino-double</a></p>
  
  <pre><code>float velF() { // uses the last n data points, fits a line to them, 
                 // and uses the slope of that line as the velocity at that moment
       float sumTY = 0, sumT = 0, sumY = 0, sumT2 = 0;
       for (int i = 0; i &lt; n; i++) {
           sumTY += (float)times[i] * alts[i] / 1000;
           sumT += (float)times[i] / 1000;
           sumY += alts[i];
           sumT2 += (float)times[i] * times[i] / 1000000;
       }
       return (n*sumTY - sumT*sumY) / (n*sumT2 - sumT*sumT);
  }
  </code></pre></li>
  </ul>
  
  <p>Any help or advice would be greatly appreciated!</p>