Python 3 中 math.log2(x) 的时间复杂度是多少?
What is the time complexity of math.log2(x) in Python 3?
正如标题所说,我想知道math.log2(x)
的时间复杂度是多少。我知道可以用 C 语言以 O(1) 的复杂度编写这样的函数,但我在 Python.
中找不到有关此函数实现的任何信息
在Python的CPython实现中,Pythonlog2被实现为下面的C函数,再加上C中处理错误报告和特殊处理整数但最终甚至在整数中的一层如果是下面的代码执行对数。
逻辑基本上是使用标准的 C log2 函数(如果可用的话),否则根据 log 计算 log2。在任何情况下它都是 O(1),但由于所有层的检查和消毒,它具有相对较高的常数因子。
/*
log2: log to base 2.
Uses an algorithm that should:
(a) produce exact results for powers of 2, and
(b) give a monotonic log2 (for positive finite floats),
assuming that the system log is monotonic.
*/
static double
m_log2(double x)
{
if (!Py_IS_FINITE(x)) {
if (Py_IS_NAN(x))
return x; /* log2(nan) = nan */
else if (x > 0.0)
return x; /* log2(+inf) = +inf */
else {
errno = EDOM;
return Py_NAN; /* log2(-inf) = nan, invalid-operation */
}
}
if (x > 0.0) {
#ifdef HAVE_LOG2
return log2(x);
#else
double m;
int e;
m = frexp(x, &e);
/* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
* x is just greater than 1.0: in that case e is 1, log(m) is negative,
* and we get significant cancellation error from the addition of
* log(m) / log(2) to e. The slight rewrite of the expression below
* avoids this problem.
*/
if (x >= 1.0) {
return log(2.0 * m) / log(2.0) + (e - 1);
}
else {
return log(m) / log(2.0) + e;
}
#endif
}
else if (x == 0.0) {
errno = EDOM;
return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
}
else {
errno = EDOM;
return Py_NAN; /* log2(-inf) = nan, invalid-operation */
}
}
正如标题所说,我想知道math.log2(x)
的时间复杂度是多少。我知道可以用 C 语言以 O(1) 的复杂度编写这样的函数,但我在 Python.
在Python的CPython实现中,Pythonlog2被实现为下面的C函数,再加上C中处理错误报告和特殊处理整数但最终甚至在整数中的一层如果是下面的代码执行对数。
逻辑基本上是使用标准的 C log2 函数(如果可用的话),否则根据 log 计算 log2。在任何情况下它都是 O(1),但由于所有层的检查和消毒,它具有相对较高的常数因子。
/*
log2: log to base 2.
Uses an algorithm that should:
(a) produce exact results for powers of 2, and
(b) give a monotonic log2 (for positive finite floats),
assuming that the system log is monotonic.
*/
static double
m_log2(double x)
{
if (!Py_IS_FINITE(x)) {
if (Py_IS_NAN(x))
return x; /* log2(nan) = nan */
else if (x > 0.0)
return x; /* log2(+inf) = +inf */
else {
errno = EDOM;
return Py_NAN; /* log2(-inf) = nan, invalid-operation */
}
}
if (x > 0.0) {
#ifdef HAVE_LOG2
return log2(x);
#else
double m;
int e;
m = frexp(x, &e);
/* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
* x is just greater than 1.0: in that case e is 1, log(m) is negative,
* and we get significant cancellation error from the addition of
* log(m) / log(2) to e. The slight rewrite of the expression below
* avoids this problem.
*/
if (x >= 1.0) {
return log(2.0 * m) / log(2.0) + (e - 1);
}
else {
return log(m) / log(2.0) + e;
}
#endif
}
else if (x == 0.0) {
errno = EDOM;
return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
}
else {
errno = EDOM;
return Py_NAN; /* log2(-inf) = nan, invalid-operation */
}
}