Python:为什么math模块中的函数接受Decimal对象作为参数?

Rya*_*hen 8 python math decimal

Bizzarely,Python的数学模块中的每个函数似乎都适用于Decimal对象.例如:frexp,exp,cos.

当我输入时print(math.frexp(decimal.Decimal('2341.12412'))),Python打印正确的答案,这是(0.57156... , 12),并且不会抛出任何异常.

我假设数学模块将用低级C编写,尽可能地依赖硬件数学运算来提高效率.那么......为什么它适用于Decimal对象?

他们是否对数学函数进行了类型检查,如果参数是Decimal,则切换到不同的实现?我没有看到文档中提到的任何内容.它也可能是Decimal自动转换为浮点数,但这也没有任何意义.

是的,我很困惑.

eng*_*ree 7

好好看math module.c我得到了这个:

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);
}
Run Code Online (Sandbox Code Playgroud)

看一下代码,实际上确实使用了float(PyFloat_AsDouble)

同样的事情exp,

static PyObject *
math_factorial(PyObject *self, PyObject *arg)
{
    long x;
    PyObject *result, *odd_part, *two_valuation;

    if (PyFloat_Check(arg)) {
        PyObject *lx;
        double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
        if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
            PyErr_SetString(PyExc_ValueError,
                            "factorial() only accepts integral values");
            return NULL;
        }
        lx = PyLong_FromDouble(dx);
        if (lx == NULL)
            return NULL;
        x = PyLong_AsLong(lx);
        Py_DECREF(lx);
.........................................................
Run Code Online (Sandbox Code Playgroud)