Efficient implementation of natural logarithm (ln) and exponentiation

后端 未结 8 2370
借酒劲吻你
借酒劲吻你 2020-12-15 09:18

I\'m looking for implementation of log() and exp() functions provided in C library . I\'m working with 8 bit microcontro

相关标签:
8条回答
  • 2020-12-15 10:00

    The Taylor series for e^x converges extremely quickly, and you can tune your implementation to the precision that you need. (http://en.wikipedia.org/wiki/Taylor_series)

    The Taylor series for log is not as nice...

    0 讨论(0)
  • 2020-12-15 10:02

    Necromancing.
    I had to implement logarithms on rational numbers.

    This is how I did it:

    Occording to Wikipedia, there is the Halley-Newton approximation method

    which can be used for very-high precision.

    Using Newton's method, the iteration simplifies to (implementation), which has cubic convergence to ln(x), which is way better than what the Taylor-Series offers.

    // Using Newton's method, the iteration simplifies to (implementation) 
    // which has cubic convergence to ln(x).
    public static double ln(double x, double epsilon)
    {
        double yn = x - 1.0d; // using the first term of the taylor series as initial-value
        double yn1 = yn;
    
        do
        {
            yn = yn1;
            yn1 = yn + 2 * (x - System.Math.Exp(yn)) / (x + System.Math.Exp(yn));
        } while (System.Math.Abs(yn - yn1) > epsilon);
    
        return yn1;
    }
    

    This is not C, but C#, but I'm sure anybody capable to program in C will be able to deduce the C-Code from that.

    Forthermore, since

    logn(x) = ln(x)/ln(n).

    You have therefore just implemented logN as well.

    public static double log(double x, double n, double epsilon)
    {
        return ln(x, epsilon) / ln(n, epsilon);
    }
    

    where epsilon (error) is the minimum precision.

    Now as to speed, you're probably better of using the ln-cast-in-hardware, but as I said, I used this as a base to implement logarithms on a rational numbers class working with arbitrary precision.

    Arbitrary precision might be more important than speed, under certain circumstances.

    Then, use the logarithmic identities for rational numbers:
    logB(x/y) = logB(x) - logB(y)

    0 讨论(0)
提交回复
热议问题