PHP Code:
Float:naturalLogarithm(x, Float:tolerance, maxIters)
{
new Float:ratio = floatdiv(float(x - 1), float(x + 1))
new Float:sum = 0.0;
new Float:oldSum = 9999.0;
new currentTerm = 1;
while(floatabs(sum - oldSum) > tolerance && maxIters-- > 0)
{
oldSum = sum;
sum = sum + floatdiv(1.0, float(currentTerm)) * floatpower(ratio, float(currentTerm));
currentTerm = currentTerm + 2;
}
sum = sum * 2;
return sum;
}
and you can use it like this:
PHP Code:
server_print("%f", naturalLogarithm(30, 0.000000001, 1000))
x is the number you want to find the ln for.
tolerance gives the precision of the answer, lower tolerance, more precise answer, but the computation takes more time. What it says is: when the difference between the previous answer and the current answer is smaller than tolerance, the answer is good enough.
maxIters is there to put an upper bound, so the computation actually ends. When writing such algorithms, it is good practice to add an upper bound, because if the tolerance is really low we may never reach it(also depends on what series is expanded).
In this case, you see I went with really low tolerance and the computation was still fast. 0.0001 should be enough for most purposes.
For example, with 0.000001 4 decimals were precise, and with 0.000000001 6 decimals were precise. It's all about how precise you need to be and how you trade speed for precision.
__________________