Eyad Bereh
Eyad Bereh

Reputation: 1726

Getting incorrect results from a function that calculates the natural logarithm

I'm making a JavaScript function that calculates the natural logarithm for the passed number using Taylor series, but I'm getting incorrect results.
I know there's a built-in method in the Math object to perform this task, but the function I've been working on has a threshold.

function ln(num,threshold) {
    "use strict";
    var i;
    var result=0;
    if (num<=0) {
        result="Error:Cannot Calculate The Natural Logarithm For A Negative Number";
    }
    else {
        for (i=1;i<=threshold;i++) {
            result+=Math.pow(-1,i-1)*Math.pow(num-1,i)/i;
        }
        result = result.toFixed(20);
    }
    return result;
}

ln(3,17); //output is 5038.54220028337658732198

Upvotes: 1

Views: 100

Answers (1)

Mathew Berg
Mathew Berg

Reputation: 28750

You're not using the taylor series correctly. If you read the wikipedia page it specifies the following:

"The series converges to the natural logarithm (shifted by 1) whenever -1 < x < 1 ."

So you're using 3, which doesn't fall within that range so that's why it's not converging.

https://en.wikipedia.org/wiki/Natural_logarithm#Derivative.2C_Taylor_series https://en.wikipedia.org/wiki/Natural_logarithm#/media/File:LogTay.svg https://en.wikipedia.org/wiki/Mercator_series

And indeed running ln(2, 17) spits out a far more appropriate number.

Upvotes: 4

Related Questions