I'm experimenting with different implementations of the Newton method for calculating square roots. One important decision is when to terminate the algorithm.
Obviously it won't do to use the absolute difference between y*y
and x
where y
is the current estimate of the square root of x
, because for large values of x
it may not be possible to represent its square root with enough precision.
So I'm supposed to use a relative criteria. Naively I would have used something like this:
static int sqrt_good_enough(float x, float y) {
return fabsf(y*y - x) / x < EPS;
}
And this appears to work very well. But recently I have started reading Kernighan and Plauger's The Elements of Programming Style and they give a Fortran program for the same algorithm in chapter 1, whose termination criteria, translated in C, would be:
static int sqrt_good_enough(float x, float y) {
return fabsf(x/y - y) < EPS * y;
}
Both are mathematically equivalent, but is there a reason for preferring one form over the other?