python - ldexp 和 frexp 在 python 中如何工作?

标签 python floating-point ieee-754 exponent mantissa

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/

相关文章:

java - 在java中截断一个 float 和一个 double

c++ - 为什么 float 变量通过以一种奇怪的方式在点后切割数字来保存值?

rounding - IEEE 754舍入为正无穷大

python - 在同一个 Django 管理页面中添加外键相关实体

python - 切片 numpy 数组

python - 如何让Qtextedit变成文本且不可选择?

python - Gensim LDA 多核 Python 脚本运行速度太慢

java - 为什么 Oracle 声称 java.util.Random.nextFloat() 生成 2^24 种可能性而不是 2^23 种?

python - 在Python 3中进行精确的浮点除法

c - 为什么 MSVS 不优化 +0?