AlliedModders

AlliedModders (https://forums.alliedmods.net/index.php)
-   Scripting Help (https://forums.alliedmods.net/forumdisplay.php?f=11)
-   -   Natural logarithm function (https://forums.alliedmods.net/showthread.php?t=317081)

St1L 06-25-2019 09:56

Natural logarithm function
 
Is there a way to calculate ln() other than explicitly setting a base to an approximate e value?
I've found only this (and no LN_N given there).
Also I found this string in floatlog AMXX API Reference: "Defaults to 10, or the natural logarithm". What is "or"? When it is natural?

HamletEagle 06-25-2019 11:20

Re: Natural logarithm function
 
PHP Code:

Float:naturalLogarithm(xFloat:tolerancemaxIters)
{
    new 
Float:ratio floatdiv(float(1), float(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.0float(currentTerm)) * floatpower(ratiofloat(currentTerm));
        
        
currentTerm currentTerm 2;
    }

    
sum sum 2;

    return 
sum;


and you can use it like this:
PHP Code:

server_print("%f"naturalLogarithm(300.0000000011000)) 

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.

St1L 06-25-2019 15:07

Re: Natural logarithm function
 
Thank you.
Can I change x to Float? I guess this will work the same?
Code:
new Float:ratio = floatdiv(x - 1.0, x + 1.0)
What about floats in general? Do we have them supported (arithmetics) or must use float* functions for everything? I noticed that sometimes I'm getting some insane results. We certainly can't use operators for int and float. But can we use it for floats without probability of huge computation failure?
And mostly I asked about some native function. Natural logarithms should be easier for computers to calculate than ones with different base. So AMXX API Reference is wrong and we have no native ln?


All times are GMT -4. The time now is 17:19.

Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.