ToI calculations

I was debugging the flash version, when I noticed how the ToI solver works. It's a root finder for a 1 dimensional function.

It has a speed up in it for interpolating the current line rather than bisecting it, and alternates between to two as the code shows:
Code:
// Use a mix of the secant rule and bisection.
float32 x;
if (rootIterCount & 1)
{
   // Secant rule to improve convergence.
   x = x1 + (target - f1) * (x2 - x1) / (f2 - f1);
}
else
{
   // Bisection to guarantee progress.
   x = 0.5f * (x1 + x2);
}

(x is the choice for the next point on the curve to evaluate)

This is clever, but the problem is I realized when stepping through that though the secant rule gives a better estimate, it is usually consistently off in one direction (depending on the curvature, I guess). But if that first guess is not quite accurate enough to break out of the loop immediately, then in effect it sets (say) x1 to be very near the answer. Then future loops will barely have any effect on x1, while x2 will move closer by bisection. But that's only every other iterations, so it's net slower than raw bisection.

Better would be a scheme that doesn't have a consistency issue. Like:
Code:
// Use a mix of the secant rule and bisection.
float32 x;
if (rootIterCount & 1)
{
   // Secant rule to improve convergence.
   if (rootIterCount & 2)
   {
      x = x1 + (target - f1) * (x2 - x1) / (f2 - f1) * 0.99;
   }
   else
   {
      x = x2 + (target - f2) * (x2 - x1) / (f2 - f1) * 0.99;
   }
}
else
{
   // Bisection to guarantee progress.
   x = 0.5f * (x1 + x2);
}


That way, in the case the secant method is not very accurate, I've changed the position of x fractionally, which will have no meaningful effect (as we weren't accurate in the first place!). But if the secant method is accurate to 1% of the interval, we can be sure that alternate guesses from it will be on either side of the target, so we can expect the interval to shrink at least 98% from those two secant methods.


I suppose there's literature to be read for root finding, but as the current code strikes me as a de-optimization, so I thought I'd mention it.
That seems like a worthwhile optimization.

I spent a fair amount of time testing the root finder. I found that it did quite well in practice. Have you encountered cases where it is iterating excessively?
Nope. I did observe the described behaviour while stepping (in AS3), but I didn't make any performance measurements. It might well be that the main benefit of the secant method is that can take the early exit so often that adding a deliberate bias will be worse. But in that case, it might be better to do 1 secant, followed by many bisection.

Testing trumps theory, so I guess we'll just leave it.
BTW, you can view my root finder as a simplification of Brent's Method: http://en.wikipedia.org/wiki/Brent's_method

Original thread: https://box2d.org/forum/viewtopic.php?t=3823