You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2698 lines
76 KiB

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