Python: why do functions in math module accept Decimal objects as arguments? -
bizzarely, every function python's math module seems work fine decimal objects. example: frexp, exp, cos.
when type print(math.frexp(decimal.decimal('2341.12412'))), python prints correct answer, (0.57156... , 12), , doesn't throw exceptions.
i assume math module written in low-level c, relying heavily possible on hardware math operations efficiency. so... why work decimal objects?
did put type check math functions, , switch different implementation if argument decimal? didn't see mentioned in docs. decimal automatically being converted float, doesn't make sense, either.
yeah, i'm confused.
well looking @ math module.c got this:
static pyobject * math_frexp(pyobject *self, pyobject *arg) { int i; double x = pyfloat_asdouble(arg); if (x == -1.0 && pyerr_occurred()) return null; /* deal special cases directly, sidestep platform differences */ if (py_is_nan(x) || py_is_infinity(x) || !x) { = 0; } else { pyfpe_start_protect("in math_frexp", return 0); x = frexp(x, &i); pyfpe_end_protect(x); } return py_buildvalue("(di)", x, i); } looking @ code, in fact use float (pyfloat_asdouble)
again same thing 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() accepts integral values"); return null; } lx = pylong_fromdouble(dx); if (lx == null) return null; x = pylong_aslong(lx); py_decref(lx); .........................................................
Comments
Post a Comment