Is the base for logarithmic computing in Python affect speed?

I need to use a lot of logarithmic calculations in one program. In terms of a 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 the others, because perhaps, under the hood, all the other bases a converted to log_a(x) = log_n(x)/log_n(a) . Or does the choice of database not affect the speed of calculation, because all the bases are implemented in the same way using the C library?

+5
source share
2 answers

In CPython, math.log is database independent, but platform dependent. From source C for the math module , lines 1940-1961 display the code for math.log .

 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, regardless of whether it computes the natural log of numbers and bases, therefore, if the C log function does not have a special check for e , it will work at the same speed.

This source also explains a different answer log2 and log10 faster than log . They are implemented using standard library functions log2 and log10 respectively, which will be faster. However, these functions are defined differently depending on the platform.

Note. I am not very familiar with C, so I could be wrong.

+4
source

Interest Ask. I did a "good old" field test (CPython 3.6.2 on Linux, x86_64, i7-3740QM CPU - the Python interpreter compiled with all the optimizations available for this CPU is included).

 >>> math.log10(3) 0.47712125471966244 >>> math.log(3, 10) 0.47712125471966244 >>> timeit.timeit('math.log(3, 10)', setup = 'import math') 0.2496643289923668 >>> timeit.timeit('math.log10(3)', setup = 'import math') 0.14756392200069968 

Log10 is clearly faster than log (n, 10).

 >>> math.log2(3.0) 1.584962500721156 >>> math.log(3.0, 2.0) 1.5849625007211563 >>> timeit.timeit('math.log2(3.0)', setup = 'import math') 0.16744944200036116 >>> timeit.timeit('math.log(3.0, 2.0)', setup = 'import math') 0.22228705599263776 

Log2 is also clearly faster than log (n, 2). Btw, in any case, floats and ints are equally fast.

With numpy image is different. It doesn’t matter what you do:

 >>> timeit.timeit('numpy.log(numpy.arange(1, 10))', setup = 'import numpy') 2.725074506000965 >>> timeit.timeit('numpy.log10(numpy.arange(1, 10))', setup = 'import numpy') 2.613872367001022 >>> timeit.timeit('numpy.log2(numpy.arange(1, 10))', setup = 'import numpy') 2.58251854799164 
+2
source

Source: https://habr.com/ru/post/1274161/


All Articles