2

I need to write two functions in C language to calculate natural log and to calculate exponent which will be executed in embedded system (Microcontroller). I am not going to use any library function rather I need to write those function by using core C instruction.

GetNet
  • 29
  • 1
  • 3

4 Answers4

1

The computation of logarithms are possible using division and multiplication in C :

static double native_log_computation(const double n) {
    // Basic logarithm computation.
    static const double euler = 2.7182818284590452354 ;
    unsigned a = 0, d;
    double b, c, e, f;
    if (n > 0) {
        for (c = n < 1 ? 1 / n : n; (c /= euler) > 1; ++a);
        c = 1 / (c * euler - 1), c = c + c + 1, f = c * c, b = 0;
        for (d = 1, c /= 2; e = b, b += 1 / (d * c), b - e/* > 0.0000001 */;)
            d += 2, c *= f;
    } else b = (n == 0) / 0.;
    return n < 1 ? -(a + b) : a + b;
}

static inline double native_ln(const double n) {
    //  Returns the natural logarithm (base e) of N.
    return native_log_computation(n) ;
}

static inline double native_log_base(const double n, const double base) {
    //  Returns the logarithm (base b) of N.
    return native_log_computation(n) / native_log_computation(base) ;
}
Michel
  • 259
  • 2
  • 3
1

You'll have to learn/use some calculus in order to do this:

http://en.wikipedia.org/wiki/Natural_logarithm#Derivative.2C_Taylor_series

Not very difficult to implement (unless you know ranges, I would say use a Maclaurin series, which, if memory serves correctly, should work well), but, little mistakes lead to big problems.

Dhaivat Pandya
  • 6,499
  • 4
  • 29
  • 43
1

I would agree with Dhaivat that approximation via Taylor or Maclaurin series is the way to go should you need to implement natural logarithm yourself for an embedded system.

As to exponentiation, you might want to look here: The most efficient way to implement an integer based power function pow(int, int)

Good luck,

Community
  • 1
  • 1
0

The two usual solutions are Taylor series and lookup tables.

Choosing one over the other depends on two main aspects:

  • maximum speed: lookup table wins
  • minimum memory: Taylor serie wins

It is also guided by other aspects that impact the first two ones:

  • range of input values
  • precision

If precision can be loose, you may consider using a trick with floating point values: the exponent part of a value x actually is an approximation of log2(x). Switching to/from log2() and ln() is easy if you know ln(2).

mouviciel
  • 66,855
  • 13
  • 106
  • 140