PageRenderTime 26ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/Objects/floatobject.c

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