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)
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.