python frexp 和 ldexp 函数将 float 拆分为尾数和指数。 有人知道这个过程是否暴露了实际的浮点结构,或者它是否需要 python 来进行昂贵的对数调用?
最佳答案
Python 2.6 的 math.frexp 只是直接调用底层 C 库 frexp。我们必须假设 C 库只是直接使用浮点表示的部分,而不是计算是否可用 (IEEE 754)。
static PyObject *
math_frexp(PyObject *self, PyObject *arg)
{
int i;
double x = PyFloat_AsDouble(arg);
if (x == -1.0 && PyErr_Occurred())
return NULL;
/* deal with special cases directly, to sidestep platform
differences */
if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
i = 0;
}
else {
PyFPE_START_PROTECT("in math_frexp", return 0);
x = frexp(x, &i);
PyFPE_END_PROTECT(x);
}
return Py_BuildValue("(di)", x, i);
}
PyDoc_STRVAR(math_frexp_doc,
"frexp(x)\n"
"\n"
"Return the mantissa and exponent of x, as pair (m, e).\n"
"m is a float and e is an int, such that x = m * 2.**e.\n"
"If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.");
关于python - ldexp 和 frexp 在 python 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1834825/