Search code examples
cmathlogarithm

Hand-coded log function won't find base-10 logs over 10


As an assignment I'm coding a log function using the hi-lo method to find the answer, but what I have doesn't work for numbers greater than 10 and I can't figure out why

int main() {
  double n, nq, x, y;
  printf("Enter the number you wish to take to the base 10 logarithm:\n");
  scanf("%lf", &x);
  double hi = 1;
  double lo = 0;
  double qlo = 1;
  double qhi = 10;

  for(int i = 0; i <= 1000; i++) {
    n = ((lo + hi)/2);
    nq = sqrt(qlo * qhi);
    if(nq > x) {
      hi = n;
      qhi = nq;
    } else {
      lo = n;
      qlo = nq;
    }
  }
  y = n;

  printf("the logarithm is equal to %lf\n", y);
  printf("%lf\n", log10(x)); // to check result
}

Solution

  • Enter the number you wish to take to the base 10 logarithm:
    1234.5678
    50 iterations found 3.091514945509
    

    See changes below...

    #define  _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    #include <math.h>
    
    int main()
    {
      double x, y;
      printf("Enter the number you wish to take to the base 10 logarithm:\n");
      scanf("%lf", &x);
      double hi = 1;
      double lo = 0;
      double qlo = 1;
      double qhi = 10;
    
      /*if (x <= 0) handle exception log undefined for input <= 0*/
    
      double tmp = 0;
      while (x > 10)
      {
        tmp++;
        x /= 10;
      }
    
      int i;
      double n = 0, nprev = -1;
      for (i = 0; i <= 1000 && fabs(n - nprev) > 1.0E-15; i++) 
      {
            nprev = n;
        n = ((lo + hi) / 2);
        double nq = sqrt(qlo * qhi);
        if (nq > x) 
        {
          hi = n;
          qhi = nq;
        }
        else 
        {
          lo = n;
          qlo = nq;
        }
      }
      y = tmp + n;
      printf("%2d iterations found %.12f",i,y);
    }