Search code examples
pythonpython-3.xlogarithm

Does the base for logarithmic calculations in Python influence the speed?


I have to use a lot of logarithmic calculations in one program. In terms of the logarithmic base, the procedure is not specific. I was wondering, if any base n (2? 10? e?) is faster in the Python 3.5 math module than others, because maybe under the hood all other bases a are transformed into log_a(x) = log_n(x)/log_n(a). Or does the choice of the base not influence the speed of the calculation, because all bases are implemented in the same way using a C library?


Solution

  • In CPython, math.log is base independent, but platform dependent. From the C source for the math module, on lines 1940-1961, the code for math.log is shown.

    math_log_impl(PyObject *module, PyObject *x, int group_right_1,
              PyObject *base)
    /*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
    
    {
        PyObject *num, *den;
        PyObject *ans;
    
        num = loghelper(x, m_log, "log"); // uses stdlib log
        if (num == NULL || base == NULL)
            return num;
    
        den = loghelper(base, m_log, "log"); // uses stdlib log
        if (den == NULL) {
            Py_DECREF(num);
            return NULL;
        }
    
        ans = PyNumber_TrueDivide(num, den);
        Py_DECREF(num);
        Py_DECREF(den);
        return ans;
    }
    

    This, no matter what, calculates the natural log of the number and base, so unless the C log function has a special check for e, it will run at the same speed.

    This source also explains the other answer's log2 and log10 being faster than log. They are implemented using the standard library log2 and log10 functions respectively, which will be faster. These functions, however, are defined differently depending on the platform.

    Note: I am not very familiar with C so I may be wrong here.