diff options
author | Raymond Hettinger <python@rcn.com> | 2008-06-22 11:39:13 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2008-06-22 11:39:13 (GMT) |
commit | d11a44312f2e80a9c4979063ce94233f924dcc5b (patch) | |
tree | 0b3e22010b4d0850aa80d32dcdb4ac3929dcbe03 /Objects/floatobject.c | |
parent | dd811a4da785119089344f6de5735264f0ca5ec6 (diff) | |
download | cpython-d11a44312f2e80a9c4979063ce94233f924dcc5b.zip cpython-d11a44312f2e80a9c4979063ce94233f924dcc5b.tar.gz cpython-d11a44312f2e80a9c4979063ce94233f924dcc5b.tar.bz2 |
Merge 64438: hex/oct/bin can show floats exactly.
Diffstat (limited to 'Objects/floatobject.c')
-rw-r--r-- | Objects/floatobject.c | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/Objects/floatobject.c b/Objects/floatobject.c index db1c99f..2465fa9 100644 --- a/Objects/floatobject.c +++ b/Objects/floatobject.c @@ -1113,6 +1113,36 @@ PyDoc_STRVAR(float_as_integer_ratio_doc, ">>> (-.25).as_integer_ratio()\n" "(-1, 4)"); +PyObject * +_float_to_base(PyObject *v, int base) +{ + PyObject *mant, *conv, *result; + double x, fr; + int i, exp; + + if (!PyFloat_Check(v)) { + PyErr_BadInternalCall(); + return NULL; + } + CONVERT_TO_DOUBLE(v, x); + if (!Py_IS_FINITE(x)) + return PyObject_Repr(v); + fr = frexp(x, &exp); + for (i=0; i<300 && fr != floor(fr) ; i++) { + fr *= 2.0; + exp--; + } + mant = PyLong_FromDouble(floor(fr)); + if (mant == NULL) + return NULL; + conv = PyNumber_ToBase(mant, base); + Py_DECREF(mant); + if (conv == NULL) + return NULL; + result = PyUnicode_FromFormat("%U * 2.0 ** %d", conv, exp); + Py_DECREF(conv); + return result; +} static PyObject * float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds); |