/* Float object implementation */ /* XXX There should be overflow checks here, but it's hard to check for any kind of float exception without losing portability. */ #include "Python.h" #include <ctype.h> #if !defined(__STDC__)extern double fmod(double, double);extern double pow(double, double);#endif /* Special free list -- see comments for same code in intobject.c. */#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject)) struct _floatblock { struct _floatblock *next; PyFloatObject objects[N_FLOATOBJECTS];}; typedef struct _floatblock PyFloatBlock; static PyFloatBlock *block_list = NULL;static PyFloatObject *free_list = NULL; static PyFloatObject *fill_free_list(void){ PyFloatObject *p, *q; /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */ p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock)); if (p == NULL) return (PyFloatObject *) PyErr_NoMemory(); ((PyFloatBlock *)p)->next = block_list; block_list = (PyFloatBlock *)p; p = &((PyFloatBlock *)p)->objects[0]; q = p + N_FLOATOBJECTS; while (--q > p) q->ob_type = (struct _typeobject *)(q-1); q->ob_type = NULL; return p + N_FLOATOBJECTS - 1;} PyObject *PyFloat_FromDouble(double fval){ register PyFloatObject *op; if (free_list == NULL) { if ((free_list = fill_free_list()) == NULL) return NULL; } /* Inline PyObject_New */ op = free_list; free_list = (PyFloatObject *)op->ob_type; PyObject_INIT(op, &PyFloat_Type); op->ob_fval = fval; return (PyObject *) op;} /**************************************************************************RED_FLAG 22-Sep-2000 timPyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG, 1. If v was a regular string, *pend was set to point to its terminating null byte. That's useless (the caller can find that without any help from this function!). 2. If v was a Unicode string, or an object convertible to a character buffer, *pend was set to point into stack trash (the auto temp vector holding the character buffer). That was downright dangerous. Since we can't change the interface of a public API function, pend isstill supported but now *officially* useless: if pend is not NULL,*pend is set to NULL.**************************************************************************/PyObject *PyFloat_FromString(PyObject *v, char **pend){ const char *s, *last, *end; double x; char buffer[256]; /* for errors */#ifdef Py_USING_UNICODE char s_buffer[256]; /* for objects convertible to a char buffer */#endif Py_ssize_t len; if (pend) *pend = NULL; if (PyString_Check(v)) { s = PyString_AS_STRING(v); len = PyString_GET_SIZE(v); }#ifdef Py_USING_UNICODE else if (PyUnicode_Check(v)) { if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) { PyErr_SetString(PyExc_ValueError, "Unicode float() literal too long to convert"); return NULL; } if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v), PyUnicode_GET_SIZE(v), s_buffer, NULL)) return NULL; s = s_buffer; len = strlen(s); }#endif else if (PyObject_AsCharBuffer(v, &s, &len)) { PyErr_SetString(PyExc_TypeError, "float() argument must be a string or a number"); return NULL; } last = s + len; while (*s && isspace(Py_CHARMASK(*s))) s++; if (*s == '\0') { PyErr_SetString(PyExc_ValueError, "empty string for float()"); return NULL; } /* We don't care about overflow or underflow. If the platform supports * them, infinities and signed zeroes (on underflow) are fine. * However, strtod can return 0 for denormalized numbers, where atof * does not. So (alas!) we special-case a zero result. Note that * whether strtod sets errno on underflow is not defined, so we can't * key off errno. */ PyFPE_START_PROTECT("strtod", return NULL) x = PyOS_ascii_strtod(s, (char **)&end); PyFPE_END_PROTECT(x) errno = 0; /* Believe it or not, Solaris 2.6 can move end *beyond* the null byte at the end of the string, when the input is inf(inity). */ if (end > last) end = last; if (end == s) { PyOS_snprintf(buffer, sizeof(buffer), "invalid literal for float(): %.200s", s); PyErr_SetString(PyExc_ValueError, buffer); return NULL; } /* Since end != s, the platform made *some* kind of sense out of the input. Trust it. */ while (*end && isspace(Py_CHARMASK(*end))) end++; if (*end != '\0') { PyOS_snprintf(buffer, sizeof(buffer), "invalid literal for float(): %.200s", s); PyErr_SetString(PyExc_ValueError, buffer); return NULL; } else if (end != last) { PyErr_SetString(PyExc_ValueError, "null byte in argument for float()"); return NULL; } if (x == 0.0) { /* See above -- may have been strtod being anal about denorms. */ PyFPE_START_PROTECT("atof", return NULL) x = PyOS_ascii_atof(s); PyFPE_END_PROTECT(x) errno = 0; /* whether atof ever set errno is undefined */ } return PyFloat_FromDouble(x);} static voidfloat_dealloc(PyFloatObject *op){ if (PyFloat_CheckExact(op)) { op->ob_type = (struct _typeobject *)free_list; free_list = op; } else op->ob_type->tp_free((PyObject *)op);} doublePyFloat_AsDouble(PyObject *op){ PyNumberMethods *nb; PyFloatObject *fo; double val; if (op && PyFloat_Check(op)) return PyFloat_AS_DOUBLE((PyFloatObject*) op); if (op == NULL) { PyErr_BadArgument(); return -1; } if ((nb = op->ob_type->tp_as_number) == NULL || nb->nb_float == NULL) { PyErr_SetString(PyExc_TypeError, "a float is required"); return -1; } fo = (PyFloatObject*) (*nb->nb_float) (op); if (fo == NULL) return -1; if (!PyFloat_Check(fo)) { PyErr_SetString(PyExc_TypeError, "nb_float should return float object"); return -1; } val = PyFloat_AS_DOUBLE(fo); Py_DECREF(fo); return val;} /* Methods */ static voidformat_float(char *buf, size_t buflen, PyFloatObject *v, int precision){ register char *cp; char format[32]; /* Subroutine for float_repr and float_print. We want float numbers to be recognizable as such, i.e., they should contain a decimal point or an exponent. However, %g may print the number as an integer; in such cases, we append ".0" to the string. */ assert(PyFloat_Check(v)); PyOS_snprintf(format, 32, "%%.%ig", precision); PyOS_ascii_formatd(buf, buflen, format, v->ob_fval); cp = buf; if (*cp == '-') cp++; for (; *cp != '\0'; cp++) { /* Any non-digit means it's not an integer; this takes care of NAN and INF as well. */ if (!isdigit(Py_CHARMASK(*cp))) break; } if (*cp == '\0') { *cp++ = '.'; *cp++ = '0'; *cp++ = '\0'; }} /* XXX PyFloat_AsStringEx should not be a public API function (for one XXX thing, its signature passes a buffer without a length; for another, XXX it isn't useful outside this file).*/voidPyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision){ format_float(buf, 100, v, precision);} /* Macro and helper that convert PyObject obj to a C double and store the value in dbl; this replaces the functionality of the coercion slot function. If conversion to double raises an exception, obj is set to NULL, and the function invoking this macro returns NULL. If obj is not of float, int or long type, Py_NotImplemented is incref'ed, stored in obj, and returned from the function invoking this macro.*/#define CONVERT_TO_DOUBLE(obj, dbl) \ if (PyFloat_Check(obj)) \ dbl = PyFloat_AS_DOUBLE(obj); \ else if (convert_to_double(&(obj), &(dbl)) < 0) \ return obj; static intconvert_to_double(PyObject **v, double *dbl){ register PyObject *obj = *v; if (PyInt_Check(obj)) { *dbl = (double)PyInt_AS_LONG(obj); } else if (PyLong_Check(obj)) { *dbl = PyLong_AsDouble(obj); if (*dbl == -1.0 && PyErr_Occurred()) { *v = NULL; return -1; } } else { Py_INCREF(Py_NotImplemented); *v = Py_NotImplemented; return -1; } return 0;} /* Precisions used by repr() and str(), respectively. The repr() precision (17 significant decimal digits) is the minimal number that is guaranteed to have enough precision so that if the number is read back in the exact same binary value is recreated. This is true for IEEE floating point by design, and also happens to work for all other modern hardware. The str() precision is chosen so that in most cases, the rounding noise created by various operations is suppressed, while giving plenty of precision for practical use. */ #define PREC_REPR 17#define PREC_STR 12 /* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated: XXX they pass a char buffer without passing a length.*/voidPyFloat_AsString(char *buf, PyFloatObject *v){ format_float(buf, 100, v, PREC_STR);} voidPyFloat_AsReprString(char *buf, PyFloatObject *v){ format_float(buf, 100, v, PREC_REPR);} /* ARGSUSED */static intfloat_print(PyFloatObject *v, FILE *fp, int flags){ char buf[100]; format_float(buf, sizeof(buf), v, (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR); fputs(buf, fp); return 0;} static PyObject *float_repr(PyFloatObject *v){ char buf[100]; format_float(buf, sizeof(buf), v, PREC_REPR); return PyString_FromString(buf);} static PyObject *float_str(PyFloatObject *v){ char buf[100]; format_float(buf, sizeof(buf), v, PREC_STR); return PyString_FromString(buf);} /* Comparison is pretty much a nightmare. When comparing float to float, * we do it as straightforwardly (and long-windedly) as conceivable, so * that, e.g., Python x == y delivers the same result as the platform * C x == y when x and/or y is a NaN. * When mixing float with an integer type, there's no good *uniform* approach. * Converting the double to an integer obviously doesn't work, since we * may lose info from fractional bits. Converting the integer to a double * also has two failure modes: (1) a long int may trigger overflow (too * large to fit in the dynamic range of a C double); (2) even a C long may have * more bits than fit in a C double (e.g., on a a 64-bit box long may have * 63 bits of precision, but a C double probably has only 53), and then * we can falsely claim equality when low-order integer bits are lost by * coercion to double. So this part is painful too. */ static PyObject*float_richcompare(PyObject *v, PyObject *w, int op){ double i, j; int r = 0; assert(PyFloat_Check(v)); i = PyFloat_AS_DOUBLE(v); /* Switch on the type of w. Set i and j to doubles to be compared, * and op to the richcomp to use. */ if (PyFloat_Check(w)) j = PyFloat_AS_DOUBLE(w); else if (!Py_IS_FINITE(i)) { if (PyInt_Check(w) || PyLong_Check(w)) /* If i is an infinity, its magnitude exceeds any * finite integer, so it doesn't matter which int we * compare i with. If i is a NaN, similarly. */ j = 0.0; else goto Unimplemented; } else if (PyInt_Check(w)) { long jj = PyInt_AS_LONG(w); /* In the worst realistic case I can imagine, C double is a * Cray single with 48 bits of precision, and long has 64 * bits. */#if SIZEOF_LONG > 6 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj); if (abs >> 48) { /* Needs more than 48 bits. Make it take the * PyLong path. */ PyObject *result; PyObject *ww = PyLong_FromLong(jj); if (ww == NULL) return NULL; result = float_richcompare(v, ww, op); Py_DECREF(ww); return result; }#endif j = (double)jj; assert((long)j == jj); } else if (PyLong_Check(w)) { int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1; int wsign = _PyLong_Sign(w); size_t nbits; int exponent; if (vsign != wsign) { /* Magnitudes are irrelevant -- the signs alone * determine the outcome. */ i = (double)vsign; j = (double)wsign; goto Compare; } /* The signs are the same. */ /* Convert w to a double if it fits. In particular, 0 fits. */ nbits = _PyLong_NumBits(w); if (nbits == (size_t)-1 && PyErr_Occurred()) { /* This long is so large that size_t isn't big enough * to hold the # of bits. Replace with little doubles * that give the same outcome -- w is so large that * its magnitude must exceed the magnitude of any * finite float. */ PyErr_Clear(); i = (double)vsign; assert(wsign != 0); j = wsign * 2.0; goto Compare; } if (nbits <= 48) { j = PyLong_AsDouble(w); /* It's impossible that <= 48 bits overflowed. */ assert(j != -1.0 || ! PyErr_Occurred()); goto Compare; } assert(wsign != 0); /* else nbits was 0 */ assert(vsign != 0); /* if vsign were 0, then since wsign is * not 0, we would have taken the * vsign != wsign branch at the start */ /* We want to work with non-negative numbers. */ if (vsign < 0) { /* "Multiply both sides" by -1; this also swaps the * comparator. */ i = -i; op = _Py_SwappedOp[op]; } assert(i > 0.0); (void) frexp(i, &exponent); /* exponent is the # of bits in v before the radix point; * we know that nbits (the # of bits in w) > 48 at this point */ if (exponent < 0 || (size_t)exponent < nbits) { i = 1.0; j = 2.0; goto Compare; } if ((size_t)exponent > nbits) { i = 2.0; j = 1.0; goto Compare; } /* v and w have the same number of bits before the radix * point. Construct two longs that have the same comparison * outcome. */ { double fracpart; double intpart; PyObject *result = NULL; PyObject *one = NULL; PyObject *vv = NULL; PyObject *ww = w; if (wsign < 0) { ww = PyNumber_Negative(w);Lines 1–500 of 1748. Load more
/* Float object implementation */ /* XXX There should be overflow checks here, but it's hard to check for any kind of float exception without losing portability. */ #include "Python.h" #include <ctype.h> #if !defined(__STDC__) extern double fmod(double, double); extern double pow(double, double); #endif /* Special free list -- see comments for same code in intobject.c. */ #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */ #define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */ #define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject)) struct _floatblock { struct _floatblock *next; PyFloatObject objects[N_FLOATOBJECTS]; }; typedef struct _floatblock PyFloatBlock; static PyFloatBlock *block_list = NULL; static PyFloatObject *free_list = NULL; static PyFloatObject * fill_free_list(void) { PyFloatObject *p, *q; /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */ p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock)); if (p == NULL) return (PyFloatObject *) PyErr_NoMemory(); ((PyFloatBlock *)p)->next = block_list; block_list = (PyFloatBlock *)p; p = &((PyFloatBlock *)p)->objects[0]; q = p + N_FLOATOBJECTS; while (--q > p) q->ob_type = (struct _typeobject *)(q-1); q->ob_type = NULL; return p + N_FLOATOBJECTS - 1; } PyObject * PyFloat_FromDouble(double fval) { register PyFloatObject *op; if (free_list == NULL) { if ((free_list = fill_free_list()) == NULL) return NULL; } /* Inline PyObject_New */ op = free_list; free_list = (PyFloatObject *)op->ob_type; PyObject_INIT(op, &PyFloat_Type); op->ob_fval = fval; return (PyObject *) op; } /************************************************************************** RED_FLAG 22-Sep-2000 tim PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG, 1. If v was a regular string, *pend was set to point to its terminating null byte. That's useless (the caller can find that without any help from this function!). 2. If v was a Unicode string, or an object convertible to a character buffer, *pend was set to point into stack trash (the auto temp vector holding the character buffer). That was downright dangerous. Since we can't change the interface of a public API function, pend is still supported but now *officially* useless: if pend is not NULL, *pend is set to NULL. **************************************************************************/ PyObject * PyFloat_FromString(PyObject *v, char **pend) { const char *s, *last, *end; double x; char buffer[256]; /* for errors */ #ifdef Py_USING_UNICODE char s_buffer[256]; /* for objects convertible to a char buffer */ #endif Py_ssize_t len; if (pend) *pend = NULL; if (PyString_Check(v)) { s = PyString_AS_STRING(v); len = PyString_GET_SIZE(v); } #ifdef Py_USING_UNICODE else if (PyUnicode_Check(v)) { if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) { PyErr_SetString(PyExc_ValueError, "Unicode float() literal too long to convert"); return NULL; } if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v), PyUnicode_GET_SIZE(v), s_buffer, NULL)) return NULL; s = s_buffer; len = strlen(s); } #endif else if (PyObject_AsCharBuffer(v, &s, &len)) { PyErr_SetString(PyExc_TypeError, "float() argument must be a string or a number"); return NULL; } last = s + len; while (*s && isspace(Py_CHARMASK(*s))) s++; if (*s == '\0') { PyErr_SetString(PyExc_ValueError, "empty string for float()"); return NULL; } /* We don't care about overflow or underflow. If the platform supports * them, infinities and signed zeroes (on underflow) are fine. * However, strtod can return 0 for denormalized numbers, where atof * does not. So (alas!) we special-case a zero result. Note that * whether strtod sets errno on underflow is not defined, so we can't * key off errno. */ PyFPE_START_PROTECT("strtod", return NULL) x = PyOS_ascii_strtod(s, (char **)&end); PyFPE_END_PROTECT(x) errno = 0; /* Believe it or not, Solaris 2.6 can move end *beyond* the null byte at the end of the string, when the input is inf(inity). */ if (end > last) end = last; if (end == s) { PyOS_snprintf(buffer, sizeof(buffer), "invalid literal for float(): %.200s", s); PyErr_SetString(PyExc_ValueError, buffer); return NULL; } /* Since end != s, the platform made *some* kind of sense out of the input. Trust it. */ while (*end && isspace(Py_CHARMASK(*end))) end++; if (*end != '\0') { PyOS_snprintf(buffer, sizeof(buffer), "invalid literal for float(): %.200s", s); PyErr_SetString(PyExc_ValueError, buffer); return NULL; } else if (end != last) { PyErr_SetString(PyExc_ValueError, "null byte in argument for float()"); return NULL; } if (x == 0.0) { /* See above -- may have been strtod being anal about denorms. */ PyFPE_START_PROTECT("atof", return NULL) x = PyOS_ascii_atof(s); PyFPE_END_PROTECT(x) errno = 0; /* whether atof ever set errno is undefined */ } return PyFloat_FromDouble(x); } static void float_dealloc(PyFloatObject *op) { if (PyFloat_CheckExact(op)) { op->ob_type = (struct _typeobject *)free_list; free_list = op; } else op->ob_type->tp_free((PyObject *)op); } double PyFloat_AsDouble(PyObject *op) { PyNumberMethods *nb; PyFloatObject *fo; double val; if (op && PyFloat_Check(op)) return PyFloat_AS_DOUBLE((PyFloatObject*) op); if (op == NULL) { PyErr_BadArgument(); return -1; } if ((nb = op->ob_type->tp_as_number) == NULL || nb->nb_float == NULL) { PyErr_SetString(PyExc_TypeError, "a float is required"); return -1; } fo = (PyFloatObject*) (*nb->nb_float) (op); if (fo == NULL) return -1; if (!PyFloat_Check(fo)) { PyErr_SetString(PyExc_TypeError, "nb_float should return float object"); return -1; } val = PyFloat_AS_DOUBLE(fo); Py_DECREF(fo); return val; } /* Methods */ static void format_float(char *buf, size_t buflen, PyFloatObject *v, int precision) { register char *cp; char format[32]; /* Subroutine for float_repr and float_print. We want float numbers to be recognizable as such, i.e., they should contain a decimal point or an exponent. However, %g may print the number as an integer; in such cases, we append ".0" to the string. */ assert(PyFloat_Check(v)); PyOS_snprintf(format, 32, "%%.%ig", precision); PyOS_ascii_formatd(buf, buflen, format, v->ob_fval); cp = buf; if (*cp == '-') cp++; for (; *cp != '\0'; cp++) { /* Any non-digit means it's not an integer; this takes care of NAN and INF as well. */ if (!isdigit(Py_CHARMASK(*cp))) break; } if (*cp == '\0') { *cp++ = '.'; *cp++ = '0'; *cp++ = '\0'; } } /* XXX PyFloat_AsStringEx should not be a public API function (for one XXX thing, its signature passes a buffer without a length; for another, XXX it isn't useful outside this file). */ void PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision) { format_float(buf, 100, v, precision); } /* Macro and helper that convert PyObject obj to a C double and store the value in dbl; this replaces the functionality of the coercion slot function. If conversion to double raises an exception, obj is set to NULL, and the function invoking this macro returns NULL. If obj is not of float, int or long type, Py_NotImplemented is incref'ed, stored in obj, and returned from the function invoking this macro. */ #define CONVERT_TO_DOUBLE(obj, dbl) \ if (PyFloat_Check(obj)) \ dbl = PyFloat_AS_DOUBLE(obj); \ else if (convert_to_double(&(obj), &(dbl)) < 0) \ return obj; static int convert_to_double(PyObject **v, double *dbl) { register PyObject *obj = *v; if (PyInt_Check(obj)) { *dbl = (double)PyInt_AS_LONG(obj); } else if (PyLong_Check(obj)) { *dbl = PyLong_AsDouble(obj); if (*dbl == -1.0 && PyErr_Occurred()) { *v = NULL; return -1; } } else { Py_INCREF(Py_NotImplemented); *v = Py_NotImplemented; return -1; } return 0; } /* Precisions used by repr() and str(), respectively. The repr() precision (17 significant decimal digits) is the minimal number that is guaranteed to have enough precision so that if the number is read back in the exact same binary value is recreated. This is true for IEEE floating point by design, and also happens to work for all other modern hardware. The str() precision is chosen so that in most cases, the rounding noise created by various operations is suppressed, while giving plenty of precision for practical use. */ #define PREC_REPR 17 #define PREC_STR 12 /* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated: XXX they pass a char buffer without passing a length. */ void PyFloat_AsString(char *buf, PyFloatObject *v) { format_float(buf, 100, v, PREC_STR); } void PyFloat_AsReprString(char *buf, PyFloatObject *v) { format_float(buf, 100, v, PREC_REPR); } /* ARGSUSED */ static int float_print(PyFloatObject *v, FILE *fp, int flags) { char buf[100]; format_float(buf, sizeof(buf), v, (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR); fputs(buf, fp); return 0; } static PyObject * float_repr(PyFloatObject *v) { char buf[100]; format_float(buf, sizeof(buf), v, PREC_REPR); return PyString_FromString(buf); } static PyObject * float_str(PyFloatObject *v) { char buf[100]; format_float(buf, sizeof(buf), v, PREC_STR); return PyString_FromString(buf); } /* Comparison is pretty much a nightmare. When comparing float to float, * we do it as straightforwardly (and long-windedly) as conceivable, so * that, e.g., Python x == y delivers the same result as the platform * C x == y when x and/or y is a NaN. * When mixing float with an integer type, there's no good *uniform* approach. * Converting the double to an integer obviously doesn't work, since we * may lose info from fractional bits. Converting the integer to a double * also has two failure modes: (1) a long int may trigger overflow (too * large to fit in the dynamic range of a C double); (2) even a C long may have * more bits than fit in a C double (e.g., on a a 64-bit box long may have * 63 bits of precision, but a C double probably has only 53), and then * we can falsely claim equality when low-order integer bits are lost by * coercion to double. So this part is painful too. */ static PyObject* float_richcompare(PyObject *v, PyObject *w, int op) { double i, j; int r = 0; assert(PyFloat_Check(v)); i = PyFloat_AS_DOUBLE(v); /* Switch on the type of w. Set i and j to doubles to be compared, * and op to the richcomp to use. */ if (PyFloat_Check(w)) j = PyFloat_AS_DOUBLE(w); else if (!Py_IS_FINITE(i)) { if (PyInt_Check(w) || PyLong_Check(w)) /* If i is an infinity, its magnitude exceeds any * finite integer, so it doesn't matter which int we * compare i with. If i is a NaN, similarly. */ j = 0.0; else goto Unimplemented; } else if (PyInt_Check(w)) { long jj = PyInt_AS_LONG(w); /* In the worst realistic case I can imagine, C double is a * Cray single with 48 bits of precision, and long has 64 * bits. */ #if SIZEOF_LONG > 6 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj); if (abs >> 48) { /* Needs more than 48 bits. Make it take the * PyLong path. */ PyObject *result; PyObject *ww = PyLong_FromLong(jj); if (ww == NULL) return NULL; result = float_richcompare(v, ww, op); Py_DECREF(ww); return result; } #endif j = (double)jj; assert((long)j == jj); } else if (PyLong_Check(w)) { int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1; int wsign = _PyLong_Sign(w); size_t nbits; int exponent; if (vsign != wsign) { /* Magnitudes are irrelevant -- the signs alone * determine the outcome. */ i = (double)vsign; j = (double)wsign; goto Compare; } /* The signs are the same. */ /* Convert w to a double if it fits. In particular, 0 fits. */ nbits = _PyLong_NumBits(w); if (nbits == (size_t)-1 && PyErr_Occurred()) { /* This long is so large that size_t isn't big enough * to hold the # of bits. Replace with little doubles * that give the same outcome -- w is so large that * its magnitude must exceed the magnitude of any * finite float. */ PyErr_Clear(); i = (double)vsign; assert(wsign != 0); j = wsign * 2.0; goto Compare; } if (nbits <= 48) { j = PyLong_AsDouble(w); /* It's impossible that <= 48 bits overflowed. */ assert(j != -1.0 || ! PyErr_Occurred()); goto Compare; } assert(wsign != 0); /* else nbits was 0 */ assert(vsign != 0); /* if vsign were 0, then since wsign is * not 0, we would have taken the * vsign != wsign branch at the start */ /* We want to work with non-negative numbers. */ if (vsign < 0) { /* "Multiply both sides" by -1; this also swaps the * comparator. */ i = -i; op = _Py_SwappedOp[op]; } assert(i > 0.0); (void) frexp(i, &exponent); /* exponent is the # of bits in v before the radix point; * we know that nbits (the # of bits in w) > 48 at this point */ if (exponent < 0 || (size_t)exponent < nbits) { i = 1.0; j = 2.0; goto Compare; } if ((size_t)exponent > nbits) { i = 2.0; j = 1.0; goto Compare; } /* v and w have the same number of bits before the radix * point. Construct two longs that have the same comparison * outcome. */ { double fracpart; double intpart; PyObject *result = NULL; PyObject *one = NULL; PyObject *vv = NULL; PyObject *ww = w; if (wsign < 0) { ww = PyNumber_Negative(w);