python中保留几位小数进行四舍五入的round函数自身的源代码是什么?

2025-02-24 22:40:31
推荐回答(2个)
回答1:

它是内置函数。build-in,应该是C语言的。用的应该是 c的library

在python2.73.源码中
有这样一句。pymath.h:extern double round(double);
在pymath.c中定义如下:

#ifndef HAVE_ROUND
double
round(double x)
{
double absx, y;
absx = fabs(x);
y = floor(absx);
if (absx - y >= 0.5)
y += 1.0;
return copysign(y, x);
}

回答2:

#ifndef HAVE_COPYSIGN
double
copysign(double x, double y)
{
    /* use atan2 to distinguish -0. from 0. */
    if (y > 0. || (y == 0. && atan2(y, -1.) > 0.)) {
        return fabs(x);
    } else {
        return -fabs(x);
    }
}
#endif /* HAVE_COPYSIGN */

#ifndef HAVE_ROUND
double
round(double x)
{
    double absx, y;
    absx = fabs(x);
    y = floor(absx);
    if (absx - y >= 0.5)
    y += 1.0;
    return copysign(y, x);
}
#endif /* HAVE_ROUND */