Compil3
Compil3

Reputation: 137

Using Heron's formula to calculate square root in C

I have implemented this function:

double heron(double a)
{
    double x = (a + 1) / 2;
    while (x * x - a > 0.000001) {
        x = 0.5 * (x + a / x);
    }
    return x;
}

This function is working as intended, however I would wish to improve it. It's supposed to use and endless while loop to check if something similar to x * x is a. a is the number the user should input.

So far I have no working function using that method...This is my miserably failed attempt:

double heron(double a)
{
    double x = (a + 1) / 2;
    while (x * x != a) {
        x = 0.5 * (x + a / x);
    }
    return x;
}

This is my first post so if there is anything unclear or something I should add please let me know.

Failed attempt number 2:

double heron(double a)
{
    double x = (a + 1) / 2;
    while (1) {
        if (x * x == a){
            break;
        } else {
            x = 0.5 * (x + a / x);
        }
    }
    return x;
}

Heron's formula

Upvotes: 4

Views: 3748

Answers (1)

chux
chux

Reputation: 154130

It's supposed to use and endless while loop to check if something similar to x * x is a

Problems:

Slow convergence

When the initial x is quite wrong, the improved |x - sqrt(a)| error may still be only half as big. Given the wide range of double, the may take hundreds of iterations to get close.

Ref: Heron's formula.

For a novel 1st estimation method: Fast inverse square root.

Overflow

x * x in x * x != a is prone to overflow. x != a/x affords a like test without that range problem. Should overflow occur, x may get "infected" with "infinity" or "not-a-number" and fail to achieve convergence.

Oscillations

Once x is "close" to sqrt(a) (within a factor of 2) , the error convergence is quadratic - the number of bits "right" doubles each iteration. This continues until x == a/x or, due to peculiarities of double math, x will endlessly oscillate between two values as will the quotient.

Getting in this oscillation causes OP's loop to not terminate


Putting this together, with a test harness, demonstrates adequate convergence.

#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>

double rand_finite_double(void) {
  union {
    double d;
    unsigned char uc[sizeof(double)];
  } u;
  do {
    for (unsigned i = 0; i < sizeof u.uc; i++) {
      u.uc[i] = (unsigned char) rand();
    }
  } while (!isfinite(u.d));
  return u.d;
}

double sqrt_heron(double a) {
  double x = (a + 1) / 2;
  double x_previous = -1.0;
  for (int i = 0; i < 1000; i++) {
    double quotient = a / x;
    if (x == quotient || x == x_previous) {
      if (x == quotient) {
        return x;
      }
      return ((x + x_previous) / 2);
    }
    x_previous = x;
    x = 0.5 * (x + quotient);
  }
  // As this code is (should) never be reached, the `for(i)`
  // loop "safety" net code is not needed.
  assert(0);
}

double test_heron(double xx) {
  double x0 = sqrt(xx);
  double x1 = sqrt_heron(xx);
  if (x0 != x1) {
    double delta = fabs(x1 - x0);
    double err = delta / x0;
    static double emax = 0.0;
    if (err > emax) {
      emax = err;
      printf("    %-24.17e %-24.17e %-24.17e %-24.17e\n", xx, x0, x1, err);
      fflush(stdout);
    }
  }
  return 0;
}

int main(void) {
  for (int i = 0; i < 100000000; i++) {
    test_heron(fabs(rand_finite_double()));
  }
  return 0;
}

Improvements

  • sqrt_heron(0.0) works.

  • Change code for a better initial guess.


double sqrt_heron(double a) {
  if (a > 0.0 && a <= DBL_MAX) {
    // Better initial guess - halve the exponent of `a`
    // Could possible use bit inspection if `double` format known.  
    int expo;
    double significand = frexp(a, &expo);
    double x = ldexp(significand, expo / 2);

    double x_previous = -1.0;
    for (int i = 0; i < 8; i++) {  // Notice limit moved from 1000 down to < 10
      double quotient = a / x;
      if (x == quotient) {
        return x;
      }
      if (x == x_previous) {
        return (0.5 * (x + x_previous));
      }
      x_previous = x;
      x = 0.5 * (x + quotient);
    }
    assert(0);
  }
  if (a >= 0.0) return a;
  assert(0);  // invalid argument.
}

Upvotes: 5

Related Questions