2

I am trying to make a method that finds an approximation of the natural log of a variable using a Taylor Series.

I am aware of the Math.log(a) method and do not wish to use it here.

The problem is that for numbers greater than 2 the result returned is NaN. This is only true when outer for loop is set to execute a large number of times. For example n < 10 gives a result, but not an accurate one. However, the more the outer for loop runs, the more accurate the result will be.

Taylor Series for finding ln(x) (essentially what I'm trying to write in java code) Taylor Series for finding <code>ln(x)</code>

public static double nat_log(double x) {
  double result = 0.0;
  for (int n = 1; n < 10000; n++) {
    double a = x - 1;
    int b = 1;
    for (int j = 1; j < n; j++) {
      a *= (x - 1);
      b *= -1;
    }
    result += b * a / n;
  }
    return result;
  }

My logic is that at some point a becomes too large and gets read as a NaN, thus throwing the rest of the code off. So I tried a version using a while loop and the Double.isNaN(double) method to check if a ever became NaN. The result was an infinite loop.

public static double nat_log(double x) {
  double result = 0.0;
  double a = x - 1;
  int count = 1;
  while (Double.isNaN(a) == false) {
     a = x - 1;
     int b = -1;
     for (int j = 0; j < count; j++) {
       a *= (x - 1);
       b *= -1;
     }
     result += b * (a / count);
     count++;
   }
 }

At this point i'm really stuck and not sure exactly where the problem lies, maybe I'm just trying to do something without the proper tools.

  • I'm not clear on whether you already knew this or not, but this Taylor series will not converge if x > 2. See https://en.wikipedia.org/wiki/Taylor_series#List_of_Maclaurin_series_of_some_common_functions – ajb Apr 13 '16 at 04:47
  • 2
    Also, I don't think you're really getting `NaN`. If you keep multiplying numbers and they get too large, eventually you'll get "infinity", which is different from `NaN`. That would explain the infinite loop. You might want to change your second algorithm to check `Double.isInfinite()` to verify this for yourself. – ajb Apr 13 '16 at 04:49
  • 1
    If you really want an algorithm that works for x > 2, I think your best bet is to divide it by _e_ repeatedly until it becomes < 2, and count the number of times you divide. If the count is `N`, then add `N` to the result of the Taylor series. – ajb Apr 13 '16 at 04:51

1 Answers1

-1

Your while loop becomes an infinate loop when count overflows