代码之家  ›  专栏  ›  技术社区  ›  Thomas Ahle

ldexp和frexp如何在python中工作?

  •  2
  • Thomas Ahle  · 技术社区  · 16 年前

    python frexp和ldexp函数将浮点数拆分为尾数和指数。 有人知道这个过程是否公开了实际的float结构,或者它是否需要python执行昂贵的对数调用?

    3 回复  |  直到 13 年前
        1
  •  1
  •   Nick Craig-Wood    16 年前

    至于速度,这里有一个快速比较

    $ python -m timeit -c 'from math import frexp' 'frexp(1.1)'
    100000 loops, best of 3: 3.7 usec per loop
    
    $ python -m timeit -c 'from math import log' 'log(1.1)'
    100000 loops, best of 3: 3.7 usec per loop
    
    $ python -m timeit -c 'from math import ldexp' 'ldexp(1.1,2)'
    100000 loops, best of 3: 3.5 usec per loop
    

    所以,在python中,在 frexp , log ldexp 就速度而言。但不确定这会告诉您有关实现的任何信息!

        2
  •  5
  •   u0b34a0f6ae    16 年前

    python 2.6的math.frexp直接调用底层的C库frexp。我们必须假设C库只是直接使用浮点表示的部分,而不是计算是否可用(IEEE754)。

    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.");
    
        3
  •  1
  •   tzot    16 年前

    这是一个很容易回答的问题:

    $ python
    >>> import math
    >>> help(math.frexp)
    Help on built-in function frexp in module math:
    

    注意到 内置的 .在C区。

    >>> import urllib
    >>> help(urllib.urlopen)
    Help on function urlopen in module urllib:
    

    内置的 在这里。它在蟒蛇里。

    推荐文章