How to calculate natural logarithm
#1

How to calculate natural logarithm

Hi! I need some help. I'd like to ask some help in mathematics. I'd like to write a function in a programming language to calculate the natural logarithm of x (the logarithm of x to base e, where the e is the Euler's number: 2 = 2.718281828...).

I tried Mercator series, but it failed, because it only work around 0.



Is there other equation to calculate logarithm what can I use? I found other function for complex logarithm, but I need real numbers.

Thanks,

Zuckerman
Reply
#2

Getting an explicit formula for the logarithm is impossible, as it is a transcendent function. This is why a lot of systems just calculate it by iterative measurements, like the root function. For this you would set some initial value x, then calculate e^x to see if the result is greater than the number you want to get the ln of, and add or sub a tibny bit to x according to the result. And this would be repeated until the difference is as small as you like. Of course compared to an explicit formula this takes AGES.

Edit: found a series in my notes that seems to converge quite fast. Its also mentioned on wikipedia:


As your computer got limited precision anyways you dont need to care about the R(x) part. Tested it in pawn and it needs max k=6 iterations to get a float with max precision. Here's my code, hope this helps:

pawn Код:
stock Float:guessLN(Float:x) {
    new Float:result = 0.0;
    for (new i = 0; i < 10; i++) { // can be optimized with (while (changed))
        result += (2.0 / (2.0 * i + 1.0)) * floatpower(((x - 1.0) / (x + 1.0)), 2.0 * i + 1.0);
        //printf("result: %f", result);
    }
    return result;
}
Reply
#3

THANKS THANKS!!

I tried it, and it works, thanks. The cycle's end (final value, at the top of the sigma) is k, what k means? The decimals of the floating point number? Other infinity series cycle's end is in the infinity. Plus, what is the R(x) function? Can I ignore this?

Thanks for your reply,

Zuckerman
Reply
#4

Oh there was some naming error in the series, should be like this:


n (or the k you asked for) has no special meaning here. Its just some value!=infinity so you can really calculate with it. If it was infinite the result would be 100% accurate, but for computers low limits are enough.
R(x) is some rest that defines the difference between the series and the real value of ln(x). As it cant be calculated you can simply igonre it, it is just used for theoretical needs. The higher you choose the n, the lower R(x) gets, so the more precise the result gets. So for n->infinity r(x) would be 0.
Reply
#5

Thanks a lot for your posts, this is a fantastic equation! Thanks.

Zuckerman
Reply


Forum Jump:


Users browsing this thread: 3 Guest(s)