PageRenderTime 1424ms CodeModel.GetById 122ms app.highlight 1127ms RepoModel.GetById 101ms app.codeStats 2ms

/Objects/floatobject.c

http://unladen-swallow.googlecode.com/
C | 2547 lines | 1934 code | 270 blank | 343 comment | 482 complexity | 3c56b40dafafdd7f11a403fe9e719111 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1
   2/* Float object implementation */
   3
   4/* XXX There should be overflow checks here, but it's hard to check
   5   for any kind of float exception without losing portability. */
   6
   7#include "Python.h"
   8#include "structseq.h"
   9
  10#include <ctype.h>
  11#include <float.h>
  12
  13#undef MAX
  14#undef MIN
  15#define MAX(x, y) ((x) < (y) ? (y) : (x))
  16#define MIN(x, y) ((x) < (y) ? (x) : (y))
  17
  18#ifdef HAVE_IEEEFP_H
  19#include <ieeefp.h>
  20#endif
  21
  22#ifdef _OSF_SOURCE
  23/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
  24extern int finite(double);
  25#endif
  26
  27/* Special free list -- see comments for same code in intobject.c. */
  28#define BLOCK_SIZE	1000	/* 1K less typical malloc overhead */
  29#define BHEAD_SIZE	8	/* Enough for a 64-bit pointer */
  30#define N_FLOATOBJECTS	((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
  31
  32struct _floatblock {
  33	struct _floatblock *next;
  34	PyFloatObject objects[N_FLOATOBJECTS];
  35};
  36
  37typedef struct _floatblock PyFloatBlock;
  38
  39static PyFloatBlock *block_list = NULL;
  40static PyFloatObject *free_list = NULL;
  41
  42static PyFloatObject *
  43fill_free_list(void)
  44{
  45	PyFloatObject *p, *q;
  46	/* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
  47	p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
  48	if (p == NULL)
  49		return (PyFloatObject *) PyErr_NoMemory();
  50	((PyFloatBlock *)p)->next = block_list;
  51	block_list = (PyFloatBlock *)p;
  52	p = &((PyFloatBlock *)p)->objects[0];
  53	q = p + N_FLOATOBJECTS;
  54	while (--q > p)
  55		Py_TYPE(q) = (struct _typeobject *)(q-1);
  56	Py_TYPE(q) = NULL;
  57	return p + N_FLOATOBJECTS - 1;
  58}
  59
  60double
  61PyFloat_GetMax(void)
  62{
  63	return DBL_MAX;
  64}
  65
  66double
  67PyFloat_GetMin(void)
  68{
  69	return DBL_MIN;
  70}
  71
  72static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};
  73
  74PyDoc_STRVAR(floatinfo__doc__,
  75"sys.floatinfo\n\
  76\n\
  77A structseq holding information about the float type. It contains low level\n\
  78information about the precision and internal representation. Please study\n\
  79your system's :file:`float.h` for more information.");
  80
  81static PyStructSequence_Field floatinfo_fields[] = {
  82	{"max",		"DBL_MAX -- maximum representable finite float"},
  83	{"max_exp",	"DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
  84			"is representable"},
  85	{"max_10_exp",	"DBL_MAX_10_EXP -- maximum int e such that 10**e "
  86			"is representable"},
  87	{"min",		"DBL_MIN -- Minimum positive normalizer float"},
  88	{"min_exp",	"DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
  89			"is a normalized float"},
  90	{"min_10_exp",	"DBL_MIN_10_EXP -- minimum int e such that 10**e is "
  91			"a normalized"},
  92	{"dig",		"DBL_DIG -- digits"},
  93	{"mant_dig",	"DBL_MANT_DIG -- mantissa digits"},
  94	{"epsilon",	"DBL_EPSILON -- Difference between 1 and the next "
  95			"representable float"},
  96	{"radix",	"FLT_RADIX -- radix of exponent"},
  97	{"rounds",	"FLT_ROUNDS -- addition rounds"},
  98	{0}
  99};
 100
 101static PyStructSequence_Desc floatinfo_desc = {
 102	"sys.floatinfo",	/* name */
 103	floatinfo__doc__,	/* doc */
 104	floatinfo_fields,	/* fields */
 105	11
 106};
 107
 108PyObject *
 109PyFloat_GetInfo(void)
 110{
 111	PyObject* floatinfo;
 112	int pos = 0;
 113
 114	floatinfo = PyStructSequence_New(&FloatInfoType);
 115	if (floatinfo == NULL) {
 116		return NULL;
 117	}
 118
 119#define SetIntFlag(flag) \
 120	PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
 121#define SetDblFlag(flag) \
 122	PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
 123
 124	SetDblFlag(DBL_MAX);
 125	SetIntFlag(DBL_MAX_EXP);
 126	SetIntFlag(DBL_MAX_10_EXP);
 127	SetDblFlag(DBL_MIN);
 128	SetIntFlag(DBL_MIN_EXP);
 129	SetIntFlag(DBL_MIN_10_EXP);
 130	SetIntFlag(DBL_DIG);
 131	SetIntFlag(DBL_MANT_DIG);
 132	SetDblFlag(DBL_EPSILON);
 133	SetIntFlag(FLT_RADIX);
 134	SetIntFlag(FLT_ROUNDS);
 135#undef SetIntFlag
 136#undef SetDblFlag
 137	
 138	if (PyErr_Occurred()) {
 139		Py_CLEAR(floatinfo);
 140		return NULL;
 141	}
 142	return floatinfo;
 143}
 144
 145PyObject *
 146PyFloat_FromDouble(double fval)
 147{
 148	register PyFloatObject *op;
 149	if (free_list == NULL) {
 150		if ((free_list = fill_free_list()) == NULL)
 151			return NULL;
 152	}
 153	/* Inline PyObject_New */
 154	op = free_list;
 155	free_list = (PyFloatObject *)Py_TYPE(op);
 156	PyObject_INIT(op, &PyFloat_Type);
 157	op->ob_fval = fval;
 158	return (PyObject *) op;
 159}
 160
 161/**************************************************************************
 162RED_FLAG 22-Sep-2000 tim
 163PyFloat_FromString's pend argument is braindead.  Prior to this RED_FLAG,
 164
 1651.  If v was a regular string, *pend was set to point to its terminating
 166    null byte.  That's useless (the caller can find that without any
 167    help from this function!).
 168
 1692.  If v was a Unicode string, or an object convertible to a character
 170    buffer, *pend was set to point into stack trash (the auto temp
 171    vector holding the character buffer).  That was downright dangerous.
 172
 173Since we can't change the interface of a public API function, pend is
 174still supported but now *officially* useless:  if pend is not NULL,
 175*pend is set to NULL.
 176**************************************************************************/
 177PyObject *
 178PyFloat_FromString(PyObject *v, char **pend)
 179{
 180	const char *s, *last, *end, *sp;
 181	double x;
 182	char buffer[256]; /* for errors */
 183#ifdef Py_USING_UNICODE
 184	char s_buffer[256]; /* for objects convertible to a char buffer */
 185#endif
 186	Py_ssize_t len;
 187
 188	if (pend)
 189		*pend = NULL;
 190	if (PyString_Check(v)) {
 191		s = PyString_AS_STRING(v);
 192		len = PyString_GET_SIZE(v);
 193	}
 194#ifdef Py_USING_UNICODE
 195	else if (PyUnicode_Check(v)) {
 196		if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
 197			PyErr_SetString(PyExc_ValueError,
 198				"Unicode float() literal too long to convert");
 199			return NULL;
 200		}
 201		if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
 202					    PyUnicode_GET_SIZE(v),
 203					    s_buffer,
 204					    NULL))
 205			return NULL;
 206		s = s_buffer;
 207		len = strlen(s);
 208	}
 209#endif
 210	else if (PyObject_AsCharBuffer(v, &s, &len)) {
 211		PyErr_SetString(PyExc_TypeError,
 212				"float() argument must be a string or a number");
 213		return NULL;
 214	}
 215
 216	last = s + len;
 217	while (*s && isspace(Py_CHARMASK(*s)))
 218		s++;
 219	if (*s == '\0') {
 220		PyErr_SetString(PyExc_ValueError, "empty string for float()");
 221		return NULL;
 222	}
 223	sp = s;
 224	/* We don't care about overflow or underflow.  If the platform supports
 225	 * them, infinities and signed zeroes (on underflow) are fine.
 226	 * However, strtod can return 0 for denormalized numbers, where atof
 227	 * does not.  So (alas!) we special-case a zero result.  Note that
 228	 * whether strtod sets errno on underflow is not defined, so we can't
 229	 * key off errno.
 230         */
 231	PyFPE_START_PROTECT("strtod", return NULL)
 232	x = PyOS_ascii_strtod(s, (char **)&end);
 233	PyFPE_END_PROTECT(x)
 234	errno = 0;
 235	/* Believe it or not, Solaris 2.6 can move end *beyond* the null
 236	   byte at the end of the string, when the input is inf(inity). */
 237	if (end > last)
 238		end = last;
 239	/* Check for inf and nan. This is done late because it rarely happens. */
 240	if (end == s) {
 241		char *p = (char*)sp;
 242		int sign = 1;
 243
 244		if (*p == '-') {
 245			sign = -1;
 246			p++;
 247		}
 248		if (*p == '+') {
 249			p++;
 250		}
 251		if (PyOS_strnicmp(p, "inf", 4) == 0) {
 252			Py_RETURN_INF(sign);
 253		}
 254		if (PyOS_strnicmp(p, "infinity", 9) == 0) {
 255			Py_RETURN_INF(sign);
 256		}
 257#ifdef Py_NAN
 258		if(PyOS_strnicmp(p, "nan", 4) == 0) {
 259			Py_RETURN_NAN;
 260		}
 261#endif
 262		PyOS_snprintf(buffer, sizeof(buffer),
 263			      "invalid literal for float(): %.200s", s);
 264		PyErr_SetString(PyExc_ValueError, buffer);
 265		return NULL;
 266	}
 267	/* Since end != s, the platform made *some* kind of sense out
 268	   of the input.  Trust it. */
 269	while (*end && isspace(Py_CHARMASK(*end)))
 270		end++;
 271	if (*end != '\0') {
 272		PyOS_snprintf(buffer, sizeof(buffer),
 273			      "invalid literal for float(): %.200s", s);
 274		PyErr_SetString(PyExc_ValueError, buffer);
 275		return NULL;
 276	}
 277	else if (end != last) {
 278		PyErr_SetString(PyExc_ValueError,
 279				"null byte in argument for float()");
 280		return NULL;
 281	}
 282	if (x == 0.0) {
 283		/* See above -- may have been strtod being anal
 284		   about denorms. */
 285		PyFPE_START_PROTECT("atof", return NULL)
 286		x = PyOS_ascii_atof(s);
 287		PyFPE_END_PROTECT(x)
 288		errno = 0;    /* whether atof ever set errno is undefined */
 289	}
 290	return PyFloat_FromDouble(x);
 291}
 292
 293static void
 294float_dealloc(PyFloatObject *op)
 295{
 296	if (PyFloat_CheckExact(op)) {
 297		Py_TYPE(op) = (struct _typeobject *)free_list;
 298		free_list = op;
 299	}
 300	else
 301		Py_TYPE(op)->tp_free((PyObject *)op);
 302}
 303
 304double
 305PyFloat_AsDouble(PyObject *op)
 306{
 307	PyNumberMethods *nb;
 308	PyFloatObject *fo;
 309	double val;
 310
 311	if (op && PyFloat_Check(op))
 312		return PyFloat_AS_DOUBLE((PyFloatObject*) op);
 313
 314	if (op == NULL) {
 315		PyErr_BadArgument();
 316		return -1;
 317	}
 318
 319	if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
 320		PyErr_SetString(PyExc_TypeError, "a float is required");
 321		return -1;
 322	}
 323
 324	fo = (PyFloatObject*) (*nb->nb_float) (op);
 325	if (fo == NULL)
 326		return -1;
 327	if (!PyFloat_Check(fo)) {
 328		PyErr_SetString(PyExc_TypeError,
 329				"nb_float should return float object");
 330		return -1;
 331	}
 332
 333	val = PyFloat_AS_DOUBLE(fo);
 334	Py_DECREF(fo);
 335
 336	return val;
 337}
 338
 339/* Methods */
 340
 341static void
 342format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
 343{
 344	register char *cp;
 345	char format[32];
 346	int i;
 347
 348	/* Subroutine for float_repr and float_print.
 349	   We want float numbers to be recognizable as such,
 350	   i.e., they should contain a decimal point or an exponent.
 351	   However, %g may print the number as an integer;
 352	   in such cases, we append ".0" to the string. */
 353
 354	assert(PyFloat_Check(v));
 355	PyOS_snprintf(format, 32, "%%.%ig", precision);
 356	PyOS_ascii_formatd(buf, buflen, format, v->ob_fval);
 357	cp = buf;
 358	if (*cp == '-')
 359		cp++;
 360	for (; *cp != '\0'; cp++) {
 361		/* Any non-digit means it's not an integer;
 362		   this takes care of NAN and INF as well. */
 363		if (!isdigit(Py_CHARMASK(*cp)))
 364			break;
 365	}
 366	if (*cp == '\0') {
 367		*cp++ = '.';
 368		*cp++ = '0';
 369		*cp++ = '\0';
 370		return;
 371	}
 372	/* Checking the next three chars should be more than enough to
 373	 * detect inf or nan, even on Windows. We check for inf or nan
 374	 * at last because they are rare cases.
 375	 */
 376	for (i=0; *cp != '\0' && i<3; cp++, i++) {
 377		if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
 378			continue;
 379		/* found something that is neither a digit nor point
 380		 * it might be a NaN or INF
 381		 */
 382#ifdef Py_NAN
 383		if (Py_IS_NAN(v->ob_fval)) {
 384			strcpy(buf, "nan");
 385		}
 386                else
 387#endif
 388		if (Py_IS_INFINITY(v->ob_fval)) {
 389			cp = buf;
 390			if (*cp == '-')
 391				cp++;
 392			strcpy(cp, "inf");
 393		}
 394		break;
 395	}
 396
 397}
 398
 399/* XXX PyFloat_AsStringEx should not be a public API function (for one
 400   XXX thing, its signature passes a buffer without a length; for another,
 401   XXX it isn't useful outside this file).
 402*/
 403void
 404PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
 405{
 406	format_float(buf, 100, v, precision);
 407}
 408
 409/* Macro and helper that convert PyObject obj to a C double and store
 410   the value in dbl; this replaces the functionality of the coercion
 411   slot function.  If conversion to double raises an exception, obj is
 412   set to NULL, and the function invoking this macro returns NULL.  If
 413   obj is not of float, int or long type, Py_NotImplemented is incref'ed,
 414   stored in obj, and returned from the function invoking this macro.
 415*/
 416#define CONVERT_TO_DOUBLE(obj, dbl)			\
 417	if (PyFloat_Check(obj))				\
 418		dbl = PyFloat_AS_DOUBLE(obj);		\
 419	else if (convert_to_double(&(obj), &(dbl)) < 0)	\
 420		return obj;
 421
 422static int
 423convert_to_double(PyObject **v, double *dbl)
 424{
 425	register PyObject *obj = *v;
 426
 427	if (PyInt_Check(obj)) {
 428		*dbl = (double)PyInt_AS_LONG(obj);
 429	}
 430	else if (PyLong_Check(obj)) {
 431		*dbl = PyLong_AsDouble(obj);
 432		if (*dbl == -1.0 && PyErr_Occurred()) {
 433			*v = NULL;
 434			return -1;
 435		}
 436	}
 437	else {
 438		Py_INCREF(Py_NotImplemented);
 439		*v = Py_NotImplemented;
 440		return -1;
 441	}
 442	return 0;
 443}
 444
 445/* Precisions used by repr() and str(), respectively.
 446
 447   The repr() precision (17 significant decimal digits) is the minimal number
 448   that is guaranteed to have enough precision so that if the number is read
 449   back in the exact same binary value is recreated.  This is true for IEEE
 450   floating point by design, and also happens to work for all other modern
 451   hardware.
 452
 453   The str() precision is chosen so that in most cases, the rounding noise
 454   created by various operations is suppressed, while giving plenty of
 455   precision for practical use.
 456
 457*/
 458
 459#define PREC_REPR	17
 460#define PREC_STR	12
 461
 462/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
 463   XXX they pass a char buffer without passing a length.
 464*/
 465void
 466PyFloat_AsString(char *buf, PyFloatObject *v)
 467{
 468	format_float(buf, 100, v, PREC_STR);
 469}
 470
 471void
 472PyFloat_AsReprString(char *buf, PyFloatObject *v)
 473{
 474	format_float(buf, 100, v, PREC_REPR);
 475}
 476
 477/* ARGSUSED */
 478static int
 479float_print(PyFloatObject *v, FILE *fp, int flags)
 480{
 481	char buf[100];
 482	format_float(buf, sizeof(buf), v,
 483		     (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
 484	Py_BEGIN_ALLOW_THREADS
 485	fputs(buf, fp);
 486	Py_END_ALLOW_THREADS
 487	return 0;
 488}
 489
 490static PyObject *
 491float_repr(PyFloatObject *v)
 492{
 493	char buf[100];
 494	format_float(buf, sizeof(buf), v, PREC_REPR);
 495
 496	return PyString_FromString(buf);
 497}
 498
 499static PyObject *
 500float_str(PyFloatObject *v)
 501{
 502	char buf[100];
 503	format_float(buf, sizeof(buf), v, PREC_STR);
 504	return PyString_FromString(buf);
 505}
 506
 507/* Comparison is pretty much a nightmare.  When comparing float to float,
 508 * we do it as straightforwardly (and long-windedly) as conceivable, so
 509 * that, e.g., Python x == y delivers the same result as the platform
 510 * C x == y when x and/or y is a NaN.
 511 * When mixing float with an integer type, there's no good *uniform* approach.
 512 * Converting the double to an integer obviously doesn't work, since we
 513 * may lose info from fractional bits.  Converting the integer to a double
 514 * also has two failure modes:  (1) a long int may trigger overflow (too
 515 * large to fit in the dynamic range of a C double); (2) even a C long may have
 516 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
 517 * 63 bits of precision, but a C double probably has only 53), and then
 518 * we can falsely claim equality when low-order integer bits are lost by
 519 * coercion to double.  So this part is painful too.
 520 */
 521
 522static PyObject*
 523float_richcompare(PyObject *v, PyObject *w, int op)
 524{
 525	double i, j;
 526	int r = 0;
 527
 528	assert(PyFloat_Check(v));
 529	i = PyFloat_AS_DOUBLE(v);
 530
 531	/* Switch on the type of w.  Set i and j to doubles to be compared,
 532	 * and op to the richcomp to use.
 533	 */
 534	if (PyFloat_Check(w))
 535		j = PyFloat_AS_DOUBLE(w);
 536
 537	else if (!Py_IS_FINITE(i)) {
 538		if (PyInt_Check(w) || PyLong_Check(w))
 539			/* If i is an infinity, its magnitude exceeds any
 540			 * finite integer, so it doesn't matter which int we
 541			 * compare i with.  If i is a NaN, similarly.
 542			 */
 543			j = 0.0;
 544		else
 545			goto Unimplemented;
 546	}
 547
 548	else if (PyInt_Check(w)) {
 549		long jj = PyInt_AS_LONG(w);
 550		/* In the worst realistic case I can imagine, C double is a
 551		 * Cray single with 48 bits of precision, and long has 64
 552		 * bits.
 553		 */
 554#if SIZEOF_LONG > 6
 555		unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
 556		if (abs >> 48) {
 557			/* Needs more than 48 bits.  Make it take the
 558			 * PyLong path.
 559			 */
 560			PyObject *result;
 561			PyObject *ww = PyLong_FromLong(jj);
 562
 563			if (ww == NULL)
 564				return NULL;
 565			result = float_richcompare(v, ww, op);
 566			Py_DECREF(ww);
 567			return result;
 568		}
 569#endif
 570		j = (double)jj;
 571		assert((long)j == jj);
 572	}
 573
 574	else if (PyLong_Check(w)) {
 575		int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
 576		int wsign = _PyLong_Sign(w);
 577		size_t nbits;
 578		int exponent;
 579
 580		if (vsign != wsign) {
 581			/* Magnitudes are irrelevant -- the signs alone
 582			 * determine the outcome.
 583			 */
 584			i = (double)vsign;
 585			j = (double)wsign;
 586			goto Compare;
 587		}
 588		/* The signs are the same. */
 589		/* Convert w to a double if it fits.  In particular, 0 fits. */
 590		nbits = _PyLong_NumBits(w);
 591		if (nbits == (size_t)-1 && PyErr_Occurred()) {
 592			/* This long is so large that size_t isn't big enough
 593			 * to hold the # of bits.  Replace with little doubles
 594			 * that give the same outcome -- w is so large that
 595			 * its magnitude must exceed the magnitude of any
 596			 * finite float.
 597			 */
 598			PyErr_Clear();
 599			i = (double)vsign;
 600			assert(wsign != 0);
 601			j = wsign * 2.0;
 602			goto Compare;
 603		}
 604		if (nbits <= 48) {
 605			j = PyLong_AsDouble(w);
 606			/* It's impossible that <= 48 bits overflowed. */
 607			assert(j != -1.0 || ! PyErr_Occurred());
 608			goto Compare;
 609		}
 610		assert(wsign != 0); /* else nbits was 0 */
 611		assert(vsign != 0); /* if vsign were 0, then since wsign is
 612		                     * not 0, we would have taken the
 613		                     * vsign != wsign branch at the start */
 614		/* We want to work with non-negative numbers. */
 615		if (vsign < 0) {
 616			/* "Multiply both sides" by -1; this also swaps the
 617			 * comparator.
 618			 */
 619			i = -i;
 620			op = _Py_SwappedOp[op];
 621		}
 622		assert(i > 0.0);
 623		(void) frexp(i, &exponent);
 624		/* exponent is the # of bits in v before the radix point;
 625		 * we know that nbits (the # of bits in w) > 48 at this point
 626		 */
 627		if (exponent < 0 || (size_t)exponent < nbits) {
 628			i = 1.0;
 629			j = 2.0;
 630			goto Compare;
 631		}
 632		if ((size_t)exponent > nbits) {
 633			i = 2.0;
 634			j = 1.0;
 635			goto Compare;
 636		}
 637		/* v and w have the same number of bits before the radix
 638		 * point.  Construct two longs that have the same comparison
 639		 * outcome.
 640		 */
 641		{
 642			double fracpart;
 643			double intpart;
 644			PyObject *result = NULL;
 645			PyObject *one = NULL;
 646			PyObject *vv = NULL;
 647			PyObject *ww = w;
 648
 649			if (wsign < 0) {
 650				ww = PyNumber_Negative(w);
 651				if (ww == NULL)
 652					goto Error;
 653			}
 654			else
 655				Py_INCREF(ww);
 656
 657			fracpart = modf(i, &intpart);
 658			vv = PyLong_FromDouble(intpart);
 659			if (vv == NULL)
 660				goto Error;
 661
 662			if (fracpart != 0.0) {
 663				/* Shift left, and or a 1 bit into vv
 664				 * to represent the lost fraction.
 665				 */
 666				PyObject *temp;
 667
 668				one = PyInt_FromLong(1);
 669				if (one == NULL)
 670					goto Error;
 671
 672				temp = PyNumber_Lshift(ww, one);
 673				if (temp == NULL)
 674					goto Error;
 675				Py_DECREF(ww);
 676				ww = temp;
 677
 678				temp = PyNumber_Lshift(vv, one);
 679				if (temp == NULL)
 680					goto Error;
 681				Py_DECREF(vv);
 682				vv = temp;
 683
 684				temp = PyNumber_Or(vv, one);
 685				if (temp == NULL)
 686					goto Error;
 687				Py_DECREF(vv);
 688				vv = temp;
 689			}
 690
 691			r = PyObject_RichCompareBool(vv, ww, op);
 692			if (r < 0)
 693				goto Error;
 694			result = PyBool_FromLong(r);
 695 		 Error:
 696 		 	Py_XDECREF(vv);
 697 		 	Py_XDECREF(ww);
 698 		 	Py_XDECREF(one);
 699 		 	return result;
 700		}
 701	} /* else if (PyLong_Check(w)) */
 702
 703	else	/* w isn't float, int, or long */
 704		goto Unimplemented;
 705
 706 Compare:
 707	PyFPE_START_PROTECT("richcompare", return NULL)
 708	switch (op) {
 709	case Py_EQ:
 710		r = i == j;
 711		break;
 712	case Py_NE:
 713		r = i != j;
 714		break;
 715	case Py_LE:
 716		r = i <= j;
 717		break;
 718	case Py_GE:
 719		r = i >= j;
 720		break;
 721	case Py_LT:
 722		r = i < j;
 723		break;
 724	case Py_GT:
 725		r = i > j;
 726		break;
 727	}
 728	PyFPE_END_PROTECT(r)
 729	return PyBool_FromLong(r);
 730
 731 Unimplemented:
 732	Py_INCREF(Py_NotImplemented);
 733	return Py_NotImplemented;
 734}
 735
 736static long
 737float_hash(PyFloatObject *v)
 738{
 739	return _Py_HashDouble(v->ob_fval);
 740}
 741
 742static PyObject *
 743float_add(PyObject *v, PyObject *w)
 744{
 745	/* If you change this, also change llvm_inline_functions.c */
 746	double a,b;
 747	CONVERT_TO_DOUBLE(v, a);
 748	CONVERT_TO_DOUBLE(w, b);
 749	PyFPE_START_PROTECT("add", return 0)
 750	a = a + b;
 751	PyFPE_END_PROTECT(a)
 752	return PyFloat_FromDouble(a);
 753}
 754
 755static PyObject *
 756float_sub(PyObject *v, PyObject *w)
 757{
 758	/* If you change this, also change llvm_inline_functions.c */
 759	double a,b;
 760	CONVERT_TO_DOUBLE(v, a);
 761	CONVERT_TO_DOUBLE(w, b);
 762	PyFPE_START_PROTECT("subtract", return 0)
 763	a = a - b;
 764	PyFPE_END_PROTECT(a)
 765	return PyFloat_FromDouble(a);
 766}
 767
 768static PyObject *
 769float_mul(PyObject *v, PyObject *w)
 770{
 771	/* If you change this, also change llvm_inline_functions.c */
 772	double a,b;
 773	CONVERT_TO_DOUBLE(v, a);
 774	CONVERT_TO_DOUBLE(w, b);
 775	PyFPE_START_PROTECT("multiply", return 0)
 776	a = a * b;
 777	PyFPE_END_PROTECT(a)
 778	return PyFloat_FromDouble(a);
 779}
 780
 781static PyObject *
 782float_div(PyObject *v, PyObject *w)
 783{
 784	/* If you change this, also change llvm_inline_functions.c */
 785	double a,b;
 786	CONVERT_TO_DOUBLE(v, a);
 787	CONVERT_TO_DOUBLE(w, b);
 788#ifdef Py_NAN
 789	if (b == 0.0) {
 790		PyErr_SetString(PyExc_ZeroDivisionError,
 791				"float division");
 792		return NULL;
 793	}
 794#endif
 795	PyFPE_START_PROTECT("divide", return 0)
 796	a = a / b;
 797	PyFPE_END_PROTECT(a)
 798	return PyFloat_FromDouble(a);
 799}
 800
 801static PyObject *
 802float_classic_div(PyObject *v, PyObject *w)
 803{
 804	double a,b;
 805	CONVERT_TO_DOUBLE(v, a);
 806	CONVERT_TO_DOUBLE(w, b);
 807	if (Py_DivisionWarningFlag >= 2 &&
 808	    PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
 809		return NULL;
 810#ifdef Py_NAN
 811	if (b == 0.0) {
 812		PyErr_SetString(PyExc_ZeroDivisionError,
 813				"float division");
 814		return NULL;
 815	}
 816#endif
 817	PyFPE_START_PROTECT("divide", return 0)
 818	a = a / b;
 819	PyFPE_END_PROTECT(a)
 820	return PyFloat_FromDouble(a);
 821}
 822
 823static PyObject *
 824float_rem(PyObject *v, PyObject *w)
 825{
 826	double vx, wx;
 827	double mod;
 828	CONVERT_TO_DOUBLE(v, vx);
 829	CONVERT_TO_DOUBLE(w, wx);
 830#ifdef Py_NAN
 831	if (wx == 0.0) {
 832		PyErr_SetString(PyExc_ZeroDivisionError,
 833				"float modulo");
 834		return NULL;
 835	}
 836#endif
 837	PyFPE_START_PROTECT("modulo", return 0)
 838	mod = fmod(vx, wx);
 839	/* note: checking mod*wx < 0 is incorrect -- underflows to
 840	   0 if wx < sqrt(smallest nonzero double) */
 841	if (mod && ((wx < 0) != (mod < 0))) {
 842		mod += wx;
 843	}
 844	PyFPE_END_PROTECT(mod)
 845	return PyFloat_FromDouble(mod);
 846}
 847
 848static PyObject *
 849float_divmod(PyObject *v, PyObject *w)
 850{
 851	double vx, wx;
 852	double div, mod, floordiv;
 853 	CONVERT_TO_DOUBLE(v, vx);
 854 	CONVERT_TO_DOUBLE(w, wx);
 855	if (wx == 0.0) {
 856		PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
 857		return NULL;
 858	}
 859	PyFPE_START_PROTECT("divmod", return 0)
 860	mod = fmod(vx, wx);
 861	/* fmod is typically exact, so vx-mod is *mathematically* an
 862	   exact multiple of wx.  But this is fp arithmetic, and fp
 863	   vx - mod is an approximation; the result is that div may
 864	   not be an exact integral value after the division, although
 865	   it will always be very close to one.
 866	*/
 867	div = (vx - mod) / wx;
 868	if (mod) {
 869		/* ensure the remainder has the same sign as the denominator */
 870		if ((wx < 0) != (mod < 0)) {
 871			mod += wx;
 872			div -= 1.0;
 873		}
 874	}
 875	else {
 876		/* the remainder is zero, and in the presence of signed zeroes
 877		   fmod returns different results across platforms; ensure
 878		   it has the same sign as the denominator; we'd like to do
 879		   "mod = wx * 0.0", but that may get optimized away */
 880		mod *= mod;  /* hide "mod = +0" from optimizer */
 881		if (wx < 0.0)
 882			mod = -mod;
 883	}
 884	/* snap quotient to nearest integral value */
 885	if (div) {
 886		floordiv = floor(div);
 887		if (div - floordiv > 0.5)
 888			floordiv += 1.0;
 889	}
 890	else {
 891		/* div is zero - get the same sign as the true quotient */
 892		div *= div;	/* hide "div = +0" from optimizers */
 893		floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
 894	}
 895	PyFPE_END_PROTECT(floordiv)
 896	return Py_BuildValue("(dd)", floordiv, mod);
 897}
 898
 899static PyObject *
 900float_floor_div(PyObject *v, PyObject *w)
 901{
 902	PyObject *t, *r;
 903
 904	t = float_divmod(v, w);
 905	if (t == NULL || t == Py_NotImplemented)
 906		return t;
 907	assert(PyTuple_CheckExact(t));
 908	r = PyTuple_GET_ITEM(t, 0);
 909	Py_INCREF(r);
 910	Py_DECREF(t);
 911	return r;
 912}
 913
 914static PyObject *
 915float_pow(PyObject *v, PyObject *w, PyObject *z)
 916{
 917	double iv, iw, ix;
 918
 919	if ((PyObject *)z != Py_None) {
 920		PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
 921			"allowed unless all arguments are integers");
 922		return NULL;
 923	}
 924
 925	CONVERT_TO_DOUBLE(v, iv);
 926	CONVERT_TO_DOUBLE(w, iw);
 927
 928	/* Sort out special cases here instead of relying on pow() */
 929	if (iw == 0) { 		/* v**0 is 1, even 0**0 */
 930		return PyFloat_FromDouble(1.0);
 931	}
 932	if (iv == 0.0) {  /* 0**w is error if w<0, else 1 */
 933		if (iw < 0.0) {
 934			PyErr_SetString(PyExc_ZeroDivisionError,
 935					"0.0 cannot be raised to a negative power");
 936			return NULL;
 937		}
 938		return PyFloat_FromDouble(0.0);
 939	}
 940	if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
 941		return PyFloat_FromDouble(1.0);
 942	}
 943	if (iv < 0.0) {
 944		/* Whether this is an error is a mess, and bumps into libm
 945		 * bugs so we have to figure it out ourselves.
 946		 */
 947		if (iw != floor(iw)) {
 948			PyErr_SetString(PyExc_ValueError, "negative number "
 949				"cannot be raised to a fractional power");
 950			return NULL;
 951		}
 952		/* iw is an exact integer, albeit perhaps a very large one.
 953		 * -1 raised to an exact integer should never be exceptional.
 954		 * Alas, some libms (chiefly glibc as of early 2003) return
 955		 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
 956		 * happen to be representable in a *C* integer.  That's a
 957		 * bug; we let that slide in math.pow() (which currently
 958		 * reflects all platform accidents), but not for Python's **.
 959		 */
 960		 if (iv == -1.0 && Py_IS_FINITE(iw)) {
 961		 	/* Return 1 if iw is even, -1 if iw is odd; there's
 962		 	 * no guarantee that any C integral type is big
 963		 	 * enough to hold iw, so we have to check this
 964		 	 * indirectly.
 965		 	 */
 966		 	ix = floor(iw * 0.5) * 2.0;
 967			return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
 968		}
 969		/* Else iv != -1.0, and overflow or underflow are possible.
 970		 * Unless we're to write pow() ourselves, we have to trust
 971		 * the platform to do this correctly.
 972		 */
 973	}
 974	errno = 0;
 975	PyFPE_START_PROTECT("pow", return NULL)
 976	ix = pow(iv, iw);
 977	PyFPE_END_PROTECT(ix)
 978	Py_ADJUST_ERANGE1(ix);
 979	if (errno != 0) {
 980		/* We don't expect any errno value other than ERANGE, but
 981		 * the range of libm bugs appears unbounded.
 982		 */
 983		PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
 984						     PyExc_ValueError);
 985		return NULL;
 986	}
 987	return PyFloat_FromDouble(ix);
 988}
 989
 990static PyObject *
 991float_neg(PyFloatObject *v)
 992{
 993	return PyFloat_FromDouble(-v->ob_fval);
 994}
 995
 996static PyObject *
 997float_abs(PyFloatObject *v)
 998{
 999	return PyFloat_FromDouble(fabs(v->ob_fval));
1000}
1001
1002static int
1003float_nonzero(PyFloatObject *v)
1004{
1005	return v->ob_fval != 0.0;
1006}
1007
1008static int
1009float_coerce(PyObject **pv, PyObject **pw)
1010{
1011	if (PyInt_Check(*pw)) {
1012		long x = PyInt_AsLong(*pw);
1013		*pw = PyFloat_FromDouble((double)x);
1014		Py_INCREF(*pv);
1015		return 0;
1016	}
1017	else if (PyLong_Check(*pw)) {
1018		double x = PyLong_AsDouble(*pw);
1019		if (x == -1.0 && PyErr_Occurred())
1020			return -1;
1021		*pw = PyFloat_FromDouble(x);
1022		Py_INCREF(*pv);
1023		return 0;
1024	}
1025	else if (PyFloat_Check(*pw)) {
1026		Py_INCREF(*pv);
1027		Py_INCREF(*pw);
1028		return 0;
1029	}
1030	return 1; /* Can't do it */
1031}
1032
1033static PyObject *
1034float_is_integer(PyObject *v)
1035{
1036	double x = PyFloat_AsDouble(v);
1037	PyObject *o;
1038	
1039	if (x == -1.0 && PyErr_Occurred())
1040		return NULL;
1041	if (!Py_IS_FINITE(x))
1042		Py_RETURN_FALSE;
1043	errno = 0;
1044	PyFPE_START_PROTECT("is_integer", return NULL)
1045	o = (floor(x) == x) ? Py_True : Py_False;
1046	PyFPE_END_PROTECT(x)
1047	if (errno != 0) {
1048		PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1049						     PyExc_ValueError);
1050		return NULL;
1051	}
1052	Py_INCREF(o);
1053	return o;
1054}
1055
1056#if 0
1057static PyObject *
1058float_is_inf(PyObject *v)
1059{
1060	double x = PyFloat_AsDouble(v);
1061	if (x == -1.0 && PyErr_Occurred())
1062		return NULL;
1063	return PyBool_FromLong((long)Py_IS_INFINITY(x));
1064}
1065
1066static PyObject *
1067float_is_nan(PyObject *v)
1068{
1069	double x = PyFloat_AsDouble(v);
1070	if (x == -1.0 && PyErr_Occurred())
1071		return NULL;
1072	return PyBool_FromLong((long)Py_IS_NAN(x));
1073}
1074
1075static PyObject *
1076float_is_finite(PyObject *v)
1077{
1078	double x = PyFloat_AsDouble(v);
1079	if (x == -1.0 && PyErr_Occurred())
1080		return NULL;
1081	return PyBool_FromLong((long)Py_IS_FINITE(x));
1082}
1083#endif
1084
1085static PyObject *
1086float_trunc(PyObject *v)
1087{
1088	double x = PyFloat_AsDouble(v);
1089	double wholepart;	/* integral portion of x, rounded toward 0 */
1090
1091	(void)modf(x, &wholepart);
1092	/* Try to get out cheap if this fits in a Python int.  The attempt
1093	 * to cast to long must be protected, as C doesn't define what
1094	 * happens if the double is too big to fit in a long.  Some rare
1095	 * systems raise an exception then (RISCOS was mentioned as one,
1096	 * and someone using a non-default option on Sun also bumped into
1097	 * that).  Note that checking for >= and <= LONG_{MIN,MAX} would
1098	 * still be vulnerable:  if a long has more bits of precision than
1099	 * a double, casting MIN/MAX to double may yield an approximation,
1100	 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1101	 * yield true from the C expression wholepart<=LONG_MAX, despite
1102	 * that wholepart is actually greater than LONG_MAX.
1103	 */
1104	if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1105		const long aslong = (long)wholepart;
1106		return PyInt_FromLong(aslong);
1107	}
1108	return PyLong_FromDouble(wholepart);
1109}
1110
1111static PyObject *
1112float_long(PyObject *v)
1113{
1114	double x = PyFloat_AsDouble(v);
1115	return PyLong_FromDouble(x);
1116}
1117
1118static PyObject *
1119float_float(PyObject *v)
1120{
1121	if (PyFloat_CheckExact(v))
1122		Py_INCREF(v);
1123	else
1124		v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1125	return v;
1126}
1127
1128/* turn ASCII hex characters into integer values and vice versa */
1129
1130static char
1131char_from_hex(int x)
1132{
1133	assert(0 <= x && x < 16);
1134	return "0123456789abcdef"[x];
1135}
1136
1137static int
1138hex_from_char(char c) {
1139	int x;
1140	switch(c) {
1141	case '0':
1142		x = 0;
1143		break;
1144	case '1':
1145		x = 1;
1146		break;
1147	case '2':
1148		x = 2;
1149		break;
1150	case '3':
1151		x = 3;
1152		break;
1153	case '4':
1154		x = 4;
1155		break;
1156	case '5':
1157		x = 5;
1158		break;
1159	case '6':
1160		x = 6;
1161		break;
1162	case '7':
1163		x = 7;
1164		break;
1165	case '8':
1166		x = 8;
1167		break;
1168	case '9':
1169		x = 9;
1170		break;
1171	case 'a':
1172	case 'A':
1173		x = 10;
1174		break;
1175	case 'b':
1176	case 'B':
1177		x = 11;
1178		break;
1179	case 'c':
1180	case 'C':
1181		x = 12;
1182		break;
1183	case 'd':
1184	case 'D':
1185		x = 13;
1186		break;
1187	case 'e':
1188	case 'E':
1189		x = 14;
1190		break;
1191	case 'f':
1192	case 'F':
1193		x = 15;
1194		break;
1195	default:
1196		x = -1;
1197		break;
1198	}
1199	return x;
1200}
1201
1202/* convert a float to a hexadecimal string */
1203
1204/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1205   of the form 4k+1. */
1206#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1207
1208static PyObject *
1209float_hex(PyObject *v)
1210{
1211	double x, m;
1212	int e, shift, i, si, esign;
1213	/* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1214	   trailing NUL byte. */
1215	char s[(TOHEX_NBITS-1)/4+3];
1216
1217	CONVERT_TO_DOUBLE(v, x);
1218
1219	if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1220		return float_str((PyFloatObject *)v);
1221
1222	if (x == 0.0) {
1223		if(copysign(1.0, x) == -1.0)
1224			return PyString_FromString("-0x0.0p+0");
1225		else
1226			return PyString_FromString("0x0.0p+0");
1227	}
1228
1229	m = frexp(fabs(x), &e);
1230	shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1231	m = ldexp(m, shift);
1232	e -= shift;
1233
1234	si = 0;
1235	s[si] = char_from_hex((int)m);
1236	si++;
1237	m -= (int)m;
1238	s[si] = '.';
1239	si++;
1240	for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1241		m *= 16.0;
1242		s[si] = char_from_hex((int)m);
1243		si++;
1244		m -= (int)m;
1245	}
1246	s[si] = '\0';
1247
1248	if (e < 0) {
1249		esign = (int)'-';
1250		e = -e;
1251	}
1252	else
1253		esign = (int)'+';
1254
1255	if (x < 0.0)
1256		return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
1257	else
1258		return PyString_FromFormat("0x%sp%c%d", s, esign, e);
1259}
1260
1261PyDoc_STRVAR(float_hex_doc,
1262"float.hex() -> string\n\
1263\n\
1264Return a hexadecimal representation of a floating-point number.\n\
1265>>> (-0.1).hex()\n\
1266'-0x1.999999999999ap-4'\n\
1267>>> 3.14159.hex()\n\
1268'0x1.921f9f01b866ep+1'");
1269
1270/* Case-insensitive string match used for nan and inf detection. t should be
1271   lower-case and null-terminated.  Return a nonzero result if the first
1272   strlen(t) characters of s match t and 0 otherwise. */
1273
1274static int
1275case_insensitive_match(const char *s, const char *t)
1276{
1277	while(*t && tolower(*s) == *t) {
1278		s++;
1279		t++;
1280	}
1281	return *t ? 0 : 1;
1282}
1283
1284/* Convert a hexadecimal string to a float. */
1285
1286static PyObject *
1287float_fromhex(PyObject *cls, PyObject *arg)
1288{
1289	PyObject *result_as_float, *result;
1290	double x;
1291	long exp, top_exp, lsb, key_digit;
1292	char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1293	int half_eps, digit, round_up, sign=1;
1294	Py_ssize_t length, ndigits, fdigits, i;
1295
1296	/*
1297	 * For the sake of simplicity and correctness, we impose an artificial
1298	 * limit on ndigits, the total number of hex digits in the coefficient
1299	 * The limit is chosen to ensure that, writing exp for the exponent,
1300	 *
1301	 *   (1) if exp > LONG_MAX/2 then the value of the hex string is
1302	 *   guaranteed to overflow (provided it's nonzero)
1303	 *
1304	 *   (2) if exp < LONG_MIN/2 then the value of the hex string is
1305	 *   guaranteed to underflow to 0.
1306	 *
1307	 *   (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1308	 *   overflow in the calculation of exp and top_exp below.
1309	 *
1310	 * More specifically, ndigits is assumed to satisfy the following
1311	 * inequalities:
1312	 *
1313	 *   4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1314	 *   4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1315	 *
1316	 * If either of these inequalities is not satisfied, a ValueError is
1317	 * raised.  Otherwise, write x for the value of the hex string, and
1318	 * assume x is nonzero.  Then
1319	 *
1320	 *   2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1321	 *
1322	 * Now if exp > LONG_MAX/2 then:
1323	 *
1324	 *   exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1325	 *                    = DBL_MAX_EXP
1326	 *
1327	 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1328	 * double, so overflows.  If exp < LONG_MIN/2, then
1329	 *
1330	 *   exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1331	 *                      DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1332	 *                    = DBL_MIN_EXP - DBL_MANT_DIG - 1
1333	 *
1334	 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1335	 * when converted to a C double.
1336	 *
1337	 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1338	 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1339	 */
1340
1341	if (PyString_AsStringAndSize(arg, &s, &length))
1342		return NULL;
1343	s_end = s + length;
1344
1345	/********************
1346	 * Parse the string *
1347	 ********************/
1348
1349	/* leading whitespace and optional sign */
1350	while (*s && isspace(Py_CHARMASK(*s)))
1351		s++;
1352	if (*s == '-') {
1353		s++;
1354		sign = -1;
1355	}
1356	else if (*s == '+')
1357		s++;
1358
1359	/* infinities and nans */
1360	if (*s == 'i' || *s == 'I') {
1361		if (!case_insensitive_match(s+1, "nf"))
1362			goto parse_error;
1363		s += 3;
1364		x = Py_HUGE_VAL;
1365		if (case_insensitive_match(s, "inity"))
1366			s += 5;
1367		goto finished;
1368	}
1369	if (*s == 'n' || *s == 'N') {
1370		if (!case_insensitive_match(s+1, "an"))
1371			goto parse_error;
1372		s += 3;
1373		x = Py_NAN;
1374		goto finished;
1375	}
1376
1377	/* [0x] */
1378	s_store = s;
1379	if (*s == '0') {
1380		s++;
1381		if (tolower(*s) == (int)'x')
1382			s++;
1383		else
1384			s = s_store;
1385	}
1386
1387	/* coefficient: <integer> [. <fraction>] */
1388	coeff_start = s;
1389	while (hex_from_char(*s) >= 0)
1390		s++;
1391	s_store = s;
1392	if (*s == '.') {
1393		s++;
1394		while (hex_from_char(*s) >= 0)
1395			s++;
1396		coeff_end = s-1;
1397	}
1398	else
1399		coeff_end = s;
1400
1401	/* ndigits = total # of hex digits; fdigits = # after point */
1402	ndigits = coeff_end - coeff_start;
1403	fdigits = coeff_end - s_store;
1404	if (ndigits == 0)
1405		goto parse_error;
1406	if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1407			  LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1408		goto insane_length_error;
1409
1410	/* [p <exponent>] */
1411	if (tolower(*s) == (int)'p') {
1412		s++;
1413		exp_start = s;
1414		if (*s == '-' || *s == '+')
1415			s++;
1416		if (!('0' <= *s && *s <= '9'))
1417			goto parse_error;
1418		s++;
1419		while ('0' <= *s && *s <= '9')
1420			s++;
1421		exp = strtol(exp_start, NULL, 10);
1422	}
1423	else
1424		exp = 0;
1425
1426/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1427#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ?		\
1428				     coeff_end-(j) :			\
1429				     coeff_end-1-(j)))
1430
1431	/*******************************************
1432	 * Compute rounded value of the hex string *
1433	 *******************************************/
1434
1435	/* Discard leading zeros, and catch extreme overflow and underflow */
1436	while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1437		ndigits--;
1438	if (ndigits == 0 || exp < LONG_MIN/2) {
1439		x = 0.0;
1440		goto finished;
1441	}
1442	if (exp > LONG_MAX/2)
1443		goto overflow_error;
1444
1445	/* Adjust exponent for fractional part. */
1446	exp = exp - 4*((long)fdigits);
1447
1448	/* top_exp = 1 more than exponent of most sig. bit of coefficient */
1449	top_exp = exp + 4*((long)ndigits - 1);
1450	for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1451		top_exp++;
1452
1453	/* catch almost all nonextreme cases of overflow and underflow here */
1454	if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1455		x = 0.0;
1456		goto finished;
1457	}
1458	if (top_exp > DBL_MAX_EXP)
1459		goto overflow_error;
1460
1461	/* lsb = exponent of least significant bit of the *rounded* value.
1462	   This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1463	lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1464
1465	x = 0.0;
1466	if (exp >= lsb) {
1467		/* no rounding required */
1468		for (i = ndigits-1; i >= 0; i--)
1469			x = 16.0*x + HEX_DIGIT(i);
1470		x = ldexp(x, (int)(exp));
1471		goto finished;
1472	}
1473	/* rounding required.  key_digit is the index of the hex digit
1474	   containing the first bit to be rounded away. */
1475	half_eps = 1 << (int)((lsb - exp - 1) % 4);
1476	key_digit = (lsb - exp - 1) / 4;
1477	for (i = ndigits-1; i > key_digit; i--)
1478		x = 16.0*x + HEX_DIGIT(i);
1479	digit = HEX_DIGIT(key_digit);
1480	x = 16.0*x + (double)(digit & (16-2*half_eps));
1481
1482	/* round-half-even: round up if bit lsb-1 is 1 and at least one of
1483	   bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1484	if ((digit & half_eps) != 0) {
1485		round_up = 0;
1486		if ((digit & (3*half_eps-1)) != 0 ||
1487		    (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1488			round_up = 1;
1489		else
1490			for (i = key_digit-1; i >= 0; i--)
1491				if (HEX_DIGIT(i) != 0) {
1492					round_up = 1;
1493					break;
1494				}
1495		if (round_up == 1) {
1496			x += 2*half_eps;
1497			if (top_exp == DBL_MAX_EXP &&
1498			    x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1499				/* overflow corner case: pre-rounded value <
1500				   2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1501				goto overflow_error;
1502		}
1503	}
1504	x = ldexp(x, (int)(exp+4*key_digit));
1505
1506  finished:
1507	/* optional trailing whitespace leading to the end of the string */
1508	while (*s && isspace(Py_CHARMASK(*s)))
1509		s++;
1510	if (s != s_end)
1511		goto parse_error;
1512	result_as_float = Py_BuildValue("(d)", sign * x);
1513	if (result_as_float == NULL)
1514		return NULL;
1515	result = PyObject_CallObject(cls, result_as_float);
1516	Py_DECREF(result_as_float);
1517	return result;
1518
1519  overflow_error:
1520	PyErr_SetString(PyExc_OverflowError,
1521			"hexadecimal value too large to represent as a float");
1522	return NULL;
1523
1524  parse_error:
1525	PyErr_SetString(PyExc_ValueError,
1526			"invalid hexadecimal floating-point string");
1527	return NULL;
1528
1529  insane_length_error:
1530	PyErr_SetString(PyExc_ValueError,
1531			"hexadecimal string too long to convert");
1532	return NULL;
1533}
1534
1535PyDoc_STRVAR(float_fromhex_doc,
1536"float.fromhex(string) -> float\n\
1537\n\
1538Create a floating-point number from a hexadecimal string.\n\
1539>>> float.fromhex('0x1.ffffp10')\n\
15402047.984375\n\
1541>>> float.fromhex('-0x1p-1074')\n\
1542-4.9406564584124654e-324");
1543
1544
1545static PyObject *
1546float_as_integer_ratio(PyObject *v, PyObject *unused)
1547{
1548	double self;
1549	double float_part;
1550	int exponent;
1551	int i;
1552
1553	PyObject *prev;
1554	PyObject *py_exponent = NULL;
1555	PyObject *numerator = NULL;
1556	PyObject *denominator = NULL;
1557	PyObject *result_pair = NULL;
1558	PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
1559
1560#define INPLACE_UPDATE(obj, call) \
1561	prev = obj; \
1562	obj = call; \
1563	Py_DECREF(prev); \
1564
1565	CONVERT_TO_DOUBLE(v, self);
1566
1567	if (Py_IS_INFINITY(self)) {
1568	  PyErr_SetString(PyExc_OverflowError,
1569			  "Cannot pass infinity to float.as_integer_ratio.");
1570	  return NULL;
1571	}
1572#ifdef Py_NAN
1573	if (Py_IS_NAN(self)) {
1574	  PyErr_SetString(PyExc_ValueError,
1575			  "Cannot pass NaN to float.as_integer_ratio.");
1576	  return NULL;
1577	}
1578#endif
1579
1580	PyFPE_START_PROTECT("as_integer_ratio", goto error);
1581	float_part = frexp(self, &exponent);  	/* self == float_part * 2**exponent exactly */
1582	PyFPE_END_PROTECT(float_part);
1583	
1584	for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1585		float_part *= 2.0;
1586		exponent--;
1587	}	
1588	/* self == float_part * 2**exponent exactly and float_part is integral.
1589           If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1590           to be truncated by PyLong_FromDouble(). */
1591
1592	numerator = PyLong_FromDouble(float_part);
1593	if (numerator == NULL) goto error;
1594
1595	/* fold in 2**exponent */
1596	denominator = PyLong_FromLong(1);
1597	py_exponent = PyLong_FromLong(labs((long)exponent));
1598	if (py_exponent == NULL) goto error;
1599	INPLACE_UPDATE(py_exponent,
1600		       long_methods->nb_lshift(denominator, py_exponent));
1601	if (py_exponent == NULL) goto error;
1602	if (exponent > 0) {
1603		INPLACE_UPDATE(numerator,
1604			       long_methods->nb_multiply(numerator, py_exponent));
1605		if (numerator == NULL) goto error;
1606	}
1607	else {
1608		Py_DECREF(denominator);
1609		denominator = py_exponent;
1610		py_exponent = NULL;
1611	}
1612
1613	/* Returns ints instead of longs where possible */
1614	INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1615	if (numerator == NULL) goto error;
1616	INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1617	if (denominator == NULL) goto error;
1618
1619	result_pair = PyTuple_Pack(2, numerator, denominator);
1620
1621#undef INPLACE_UPDATE
1622error:
1623	Py_XDECREF(py_exponent);
1624	Py_XDECREF(denominator);
1625	Py_XDECREF(numerator);
1626	return result_pair;
1627}
1628
1629PyDoc_STRVAR(float_as_integer_ratio_doc,
1630"float.as_integer_ratio() -> (int, int)\n"
1631"\n"
1632"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1633"float and with a positive denominator.\n"
1634"Raises OverflowError on infinities and a ValueError on NaNs.\n"
1635"\n"
1636">>> (10.0).as_integer_ratio()\n"
1637"(10, 1)\n"
1638">>> (0.0).as_integer_ratio()\n"
1639"(0, 1)\n"
1640">>> (-.25).as_integer_ratio()\n"
1641"(-1, 4)");
1642
1643
1644static PyObject *
1645float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1646
1647static PyObject *
1648float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1649{
1650	PyObject *x = Py_False; /* Integer zero */
1651	static char *kwlist[] = {"x", 0};
1652
1653	if (type != &PyFloat_Type)
1654		return float_subtype_new(type, args, kwds); /* Wimp out */
1655	if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1656		return NULL;
1657	/* If it's a string, but not a string subclass, use
1658	   PyFloat_FromString. */
1659	if (PyString_CheckExact(x))
1660		return PyFloat_FromString(x, NULL);
1661	return PyNumber_Float(x);
1662}
1663
1664/* Wimpy, slow approach to tp_new calls for subtypes of float:
1665   first create a regular float from whatever arguments we got,
1666   then allocate a subtype instance and initialize its ob_fval
1667   from the regular float.  The regular float is then thrown away.
1668*/
1669static PyObject *
1670float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1671{
1672	PyObject *tmp, *newobj;
1673
1674	assert(PyType_IsSubtype(type, &PyFloat_Type));
1675	tmp = float_new(&PyFloat_Type, args, kwds);
1676	if (tmp == NULL)
1677		return NULL;
1678	assert(PyFloat_CheckExact(tmp));
1679	newobj = type->tp_alloc(type, 0);
1680	if (newobj == NULL) {
1681		Py_DECREF(tmp);
1682		return NULL;
1683	}
1684	((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1685	Py_DECREF(tmp);
1686	return newobj;
1687}
1688
1689static PyObject *
1690float_getnewargs(PyFloatObject *v)
1691{
1692	return Py_BuildValue("(d)", v->ob_fval);
1693}
1694
1695/* this is for the benefit of the pack/unpack routines below */
1696
1697typedef enum {
1698	unknown_format, ieee_big_endian_format, ieee_little_endian_format
1699} float_format_type;
1700
1701static float_format_type double_format, float_format;
1702static float_format_type detected_double_format, detected_float_format;
1703
1704static PyObject *
1705float_getformat(PyTypeObject *v, PyObject* arg)
1706{
1707	char* s;
1708	float_format_type r;
1709
1710	if (!PyString_Check(arg)) {
1711		PyErr_Format(PyExc_TypeError,
1712	     "__getformat__() argument must be string, not %.500s",
1713			     Py_TYPE(arg)->tp_name);
1714		return NULL;
1715	}
1716	s = PyString_AS_STRING(arg);
1717	if (strcmp(s, "double") == 0) {
1718		r = double_format;
1719	}
1720	else if (strcmp(s, "float") == 0) {
1721		r = float_format;
1722	}
1723	else {
1724		PyErr_SetString(PyExc_ValueError,
1725				"__getformat__() argument 1 must be "
1726				"'double' or 'float'");
1727		return NULL;
1728	}
1729	
1730	switch (r) {
1731	case unknown_format:
1732		return PyString_FromString("unknown");
1733	case ieee_little_endian_format:
1734		return PyString_FromString("IEEE, little-endian");
1735	case ieee_big_endian_format:
1736		return PyString_FromString("IEEE, big-endian");
1737	default:
1738		Py_FatalError("insane float_format or double_format");
1739		return NULL;
1740	}
1741}
1742
1743PyDoc_STRVAR(float_getformat_doc,
1744"float.__getformat__(typestr) -> string\n"
1745"\n"
1746"You probably don't want to use this function.  It exists mainly to be\n"
1747"used in Python's test suite.\n"
1748"\n"
1749"typestr must be 'double' or 'float'.  This function returns whichever of\n"
1750"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1751"format of floating point numbers used by the C type named by typestr.");
1752
1753static PyObject *
1754float_setformat(PyTypeObject *v, PyObject* args)
1755{
1756	char* typestr;
1757	char* format;
1758	float_format_type f;
1759	float_format_type detected;
1760	float_format_type *p;
1761
1762	if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1763		return NULL;
1764
1765	if (strcmp(typestr, "double") == 0) {
1766		p = &double_format;
1767		detected = detected_double_format;
1768	}
1769	else if (strcmp(typestr, "float") == 0) {
1770		p = &float_format;
1771		detected = detected_float_format;
1772	}
1773	else {
1774		PyErr_SetString(PyExc_ValueError,
1775				"__setformat__() argument 1 must "
1776				"be 'double' or 'float'");
1777		return NULL;
1778	}
1779	
1780	if (strcmp(format, "unknown") == 0) {
1781		f = unknown_format;
1782	}
1783	else if (strcmp(format, "IEEE, little-endian") == 0) {
1784		f = ieee_little_endian_format;
1785	}
1786	else if (strcmp(format, "IEEE, big-endian") == 0) {
1787		f = ieee_big_endian_format;
1788	}
1789	else {
1790		PyErr_SetString(PyExc_ValueError,
1791				"__setformat__() argument 2 must be "
1792				"'unknown', 'IEEE, little-endian' or "
1793				"'IEEE, big-endian'");
1794		return NULL;
1795
1796	}
1797
1798	if (f != unknown_format && f != detected) {
1799		PyErr_Format(PyExc_ValueError,
1800			     "can only set %s format to 'unknown' or the "
1801			     "detected platform value", typestr);
1802		return NULL;
1803	}
1804
1805	*p = f;
1806	Py_RETURN_NONE;
1807}
1808
1809PyDoc_STRVAR(float_setformat_doc,
1810"float.__setformat__(typestr, fmt) -> None\n"
1811"\n"
1812"You probably don't want to use this function.  It exists mainly to be\n"
1813"used in Python's test suite.\n"
1814"\n"
1815"typestr must be 'double' or 'float'.  fmt must be one of 'unknown',\n"
1816"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1817"one of the latter two if it appears to match the underlying C reality.\n"
1818"\n"
1819"Overrides the automatic determination of C-level floating point type.\n"
1820"This affects how floats are converted to and from binary strings.");
1821
1822static PyObject *
1823float_getzero(PyObject *v, void *closure)
1824{
1825	return PyFloat_FromDouble(0.0);
1826}
1827
1828static PyObject *
1829float__format__(PyObject *self, PyObject *args)
1830{
1831	PyObject *format_spec;
1832
1833	if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1834		return NULL;
1835	if (PyBytes_Check(format_spec))
1836		return _PyFloat_FormatAdvanced(self,
1837					       PyBytes_AS_STRING(format_spec),
1838					       PyBytes_GET_SIZE(format_spec));
1839	if (PyUnicode_Check(format_spec)) {
1840		/* Convert format_spec to a str */
1841		PyObject *result;
1842		PyObject *str_spec = PyObject_Str(format_spec);
1843
1844		if (str_spec == NULL)
1845			return NULL;
1846
1847		result = _PyFloat_FormatAdvanced(self,
1848						 PyBytes_AS_STRING(str_spec),
1849						 PyBytes_GET_SIZE(str_spec));
1850
1851		Py_DECREF(str_spec);
1852		return result;
1853	}
1854	PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1855	return NULL;
1856}
1857
1858PyDoc_STRVAR(float__format__doc,
1859"float.__format__(format_spec) -> string\n"
1860"\n"
1861"Formats the float according to format_spec.");
1862
1863
1864static PyMethodDef float_methods[] = {
1865	{"conjugate",	(PyCFunction)float_float,	METH_NOARGS,
1866	 "Returns self, the complex conjugate of any float."},
1867	{"__trunc__",	(PyCFunction)float_trunc, METH_NOARGS,
1868         "Returns the Integral closest to x between 0 and x."},
1869	{"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1870	 float_as_integer_ratio_doc},
1871	{"fromhex", (PyCFunction)float_fromhex,
1872	 METH_O|METH_CLASS, float_fromhex_doc},
1873	{"hex", (PyCFunction)float_hex,
1874	 METH_NOARGS, float_hex_doc},
1875	{"is_integer",	(PyCFunction)float_is_integer,	METH_NOARGS,
1876	 "Returns True if the float is an integer."},
1877#if 0
1878	{"is_inf",	(PyCFunction)float_is_inf,	METH_NOARGS,
1879	 "Returns True if the float is positive or negative infinite."},
1880	{"is_finite",	(PyCFunction)float_is_finite,	METH_NOARGS,
1881	 "Returns True if the float is finite, neither infinite nor NaN."},
1882	{"is_nan",	(PyCFunction)float_is_nan,	METH_NOARGS,
1883	 "Returns True if the float is not a number (NaN)."},
1884#endif
1885	{"__getnewargs__",	(PyCFunction)float_getnewargs,	METH_NOARGS},
1886	{"__getformat__",	(PyCFunction)float_getformat,	
1887	 METH_O|METH_CLASS,		float_getformat_doc},
1888	{"__setformat__",	(PyCFunction)float_setformat,	
1889	 METH_VARARGS|METH_CLASS,	float_setformat_doc},
1890        {"__format__",          (PyCFunction)float__format__,
1891         METH_VARARGS,                  float__format__doc},
1892	{NULL,		NULL}		/* sentinel */
1893};
1894
1895static PyGetSetDef float_getset[] = {
1896    {"real", 
1897     (getter)float_float, (setter)NULL,
1898     "the real part of a complex number",
1899     NULL},
1900    {"imag", 
1901     (getter)float_getzero, (setter)NULL,
1902     "the imaginary part of a complex number",
1903     NULL},
1904    {NULL}  /* Sentinel */
1905};
1906
1907PyDoc_STRVAR(float_doc,
1908"float(x) -> floating point number\n\
1909\n\
1910Convert a string or number to a floating point number, if possible.");
1911
1912
1913static PyNumberMethods float_as_number = {
1914	float_add, 	/*nb_add*/
1915	float_sub, 	/*nb_subtract*/
1916	float_mul, 	/*nb_multiply*/
1917	float_classic_div, /*nb_divide*/
1918	float_rem, 	/*nb_remainder*/
1919	float_divmod, 	/*nb_divmod*/
1920	float_pow, 	/*nb_power*/
1921	(unaryfunc)float_neg, /*nb_negative*/
1922	(unaryfunc)float_float, /*nb_positive*/
1923	(unaryfunc)float_abs, /*nb_absolute*/
1924	(inquiry)float_nonzero, /*nb_nonzero*/
1925	0,		/*nb_invert*/
1926	0,		/*nb_lshift*/
1927	0,		/*nb_rshift*/
1928	0,		/*nb_and*/
1929	0,		/*nb_xor*/
1930	0,		/*nb_or*/
1931	float_coerce, 	/*nb_coerce*/
1932	float_trunc, 	/*nb_int*/
1933	float_long, 	/*nb_long*/
1934	float_float,	/*nb_float*/
1935	0,		/* nb_oct */
1936	0,		/* nb_hex */
1937	0,		/* nb_inplace_add */
1938	0,		/* nb_inplace_subtract */
1939	0,		/* nb_inplace_multiply */
1940	0,		/* nb_inplace_divide */
1941	0,		/* nb_inplace_remainder */
1942	0, 		/* nb_inplace_power */
1943	0,		/* nb_inplace_lshift */
1944	0,		/* nb_inplace_rshift */
1945	0,		/* nb_inplace_and */
1946	0,		/* nb_inplace_xor */
1947	0,		/* nb_inplace_or */
1948	float_floor_div, /* nb_floor_divide */
1949	float_div,	/* nb_true_divide */
1950	0,		/* nb_inplace_floor_divide */
1951	0,		/* nb_inplace_true_divide */
1952};
1953
1954PyTypeObject PyFloat_Type = {
1955	PyVarObject_HEAD_INIT(&PyType_Type, 0)
1956	"float",
1957	sizeof(PyFloatObject),
1958	0,
1959	(destructor)float_dealloc,		/* tp_dealloc */
1960	(printfunc)float_print, 		/* tp_print */
1961	0,					/* tp_getattr */
1962	0,					/* tp_setattr */
1963	0,			 		/* tp_compare */
1964	(reprfunc)float_repr,			/* tp_repr */
1965	&float_as_number,			/* tp_as_number */
1966	0,					/* tp_as_sequence */
1967	0,					/* tp_as_mapping */
1968	(hashfunc)float_hash,			/* tp_hash */
1969	0,					/* tp_call */
1970	(reprfunc)float_str,			/* tp_str */
1971	PyObject_GenericGetAttr,		/* tp_getattro */
1972	0,					/* tp_setattro */
1973	0,					/* tp_as_buffer */
1974	Py_TPFLAGS_D

Large files files are truncated, but you can click here to view the full file