How to write a log base 10 function in c++?

4.3k views Asked by At

I know that it may seem a duplicate question, but I could not find my answer in previous questions. I mean how to write a log base 10 function by simple loops and not using built in log function in c++.

3

There are 3 answers

0
giusti On BEST ANSWER

The easiest way is to calculate the natural logarithm (ln) with a Taylor series. Once you have found the natural logarithm, just divide it by ln(10) and you get the base-10 log.

The Taylor series is quite simple to implement in C. If z is the number for which you are seeking the log, you just have to loop a few iterations multiplying an accumulator by (z-1) each time. To a limit, the more iterations you run, the more accurate your result will be. Check it a few times against the libC log10() version until you are happy with the precision.

This is a "numeric approach". There are other numeric solutions to finding the logarithm of a number which can give more accurate results. Some of them can be found in that Wikipedia link I gave you.

0
Paul Evans On

You'll get faster convergence with Newton's Method. Use something like this (hand written not compiled or tested uses f(r) = 2**r - x to compute log2(x) ):

double next(double r, double x) {
    static double one_over_ln2 = 1.4426950408889634;
    return r - one_over_ln2 * (1 - x / (1 << static_cast<int>(r)));

double log2(double x) {
    static double epsilon = 0.000000001; // change this to change accuracy
    double r = x / 2;. // better first guesses converge faster
    double r2 = next(r, x);
    double delta = r - r2;
    while (delta * delta > epsilon) { 
        r = r2;
        r2 = next(r, x);
        delta = r - r2
    }
    return r2;
}

double log10(double x) {
    static double log2_10 = log2(10);
    return log2(x) / log2_10;
}
3
Scott Hunter On

Assuming by "log base 10" you mean "the number of times n can be divided by 10 before resulting in a value < 10":

log = 0;
// Assume n has initial value N
while ( n >= 10 ) {
    // Invariant: N = n * 10^log
    n /= 10;
    log += 1;
}