blob: 47a174c241e371c30371e289315dc554e7aee35c [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Guido van Rossum3f5da241990-12-20 15:06:42 +00009#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000010#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Serhiy Storchakab5c51d32017-03-11 09:21:05 +020012/*[clinic input]
13class float "PyObject *" "&PyFloat_Type"
14[clinic start generated code]*/
15/*[clinic end generated code: output=da39a3ee5e6b4b0d input=dd0003f68f144284]*/
16
17#include "clinic/floatobject.c.h"
Guido van Rossum6923e131990-11-02 17:50:43 +000018
Mark Dickinsond19052c2010-06-27 18:19:09 +000019/* Special free list
Mark Dickinsond19052c2010-06-27 18:19:09 +000020 free_list is a singly-linked list of available PyFloatObjects, linked
21 via abuse of their ob_type members.
22*/
23
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000024#ifndef PyFloat_MAXFREELIST
25#define PyFloat_MAXFREELIST 100
26#endif
27static int numfree = 0;
Guido van Rossum3fce8831999-03-12 19:43:17 +000028static PyFloatObject *free_list = NULL;
29
Christian Heimes93852662007-12-01 12:22:32 +000030double
31PyFloat_GetMax(void)
32{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000034}
35
36double
37PyFloat_GetMin(void)
38{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000040}
41
Christian Heimesd32ed6f2008-01-14 18:49:24 +000042static PyTypeObject FloatInfoType;
43
44PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000045"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000046\n\
47A structseq holding information about the float type. It contains low level\n\
48information about the precision and internal representation. Please study\n\
49your system's :file:`float.h` for more information.");
50
51static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 {"max", "DBL_MAX -- maximum representable finite float"},
53 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
54 "is representable"},
55 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
56 "is representable"},
57 {"min", "DBL_MIN -- Minimum positive normalizer float"},
58 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
59 "is a normalized float"},
60 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
61 "a normalized"},
62 {"dig", "DBL_DIG -- digits"},
63 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
64 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
65 "representable float"},
66 {"radix", "FLT_RADIX -- radix of exponent"},
67 {"rounds", "FLT_ROUNDS -- addition rounds"},
68 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +000069};
70
71static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 "sys.float_info", /* name */
73 floatinfo__doc__, /* doc */
74 floatinfo_fields, /* fields */
75 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +000076};
77
Christian Heimes93852662007-12-01 12:22:32 +000078PyObject *
79PyFloat_GetInfo(void)
80{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 PyObject* floatinfo;
82 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +000083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 floatinfo = PyStructSequence_New(&FloatInfoType);
85 if (floatinfo == NULL) {
86 return NULL;
87 }
Christian Heimes93852662007-12-01 12:22:32 +000088
Christian Heimesd32ed6f2008-01-14 18:49:24 +000089#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +000091#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +000093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 SetDblFlag(DBL_MAX);
95 SetIntFlag(DBL_MAX_EXP);
96 SetIntFlag(DBL_MAX_10_EXP);
97 SetDblFlag(DBL_MIN);
98 SetIntFlag(DBL_MIN_EXP);
99 SetIntFlag(DBL_MIN_10_EXP);
100 SetIntFlag(DBL_DIG);
101 SetIntFlag(DBL_MANT_DIG);
102 SetDblFlag(DBL_EPSILON);
103 SetIntFlag(FLT_RADIX);
104 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000105#undef SetIntFlag
106#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107
108 if (PyErr_Occurred()) {
109 Py_CLEAR(floatinfo);
110 return NULL;
111 }
112 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000113}
114
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000116PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000117{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200118 PyFloatObject *op = free_list;
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000119 if (op != NULL) {
120 free_list = (PyFloatObject *) Py_TYPE(op);
121 numfree--;
122 } else {
123 op = (PyFloatObject*) PyObject_MALLOC(sizeof(PyFloatObject));
124 if (!op)
125 return PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 }
127 /* Inline PyObject_New */
Christian Heimesd3afe782013-12-04 09:27:47 +0100128 (void)PyObject_INIT(op, &PyFloat_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 op->ob_fval = fval;
130 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131}
132
Brett Cannona721aba2016-09-09 14:57:09 -0700133static PyObject *
134float_from_string_inner(const char *s, Py_ssize_t len, void *obj)
135{
136 double x;
137 const char *end;
138 const char *last = s + len;
139 /* strip space */
140 while (s < last && Py_ISSPACE(*s)) {
141 s++;
142 }
143
144 while (s < last - 1 && Py_ISSPACE(last[-1])) {
145 last--;
146 }
147
148 /* We don't care about overflow or underflow. If the platform
149 * supports them, infinities and signed zeroes (on underflow) are
150 * fine. */
151 x = PyOS_string_to_double(s, (char **)&end, NULL);
152 if (end != last) {
153 PyErr_Format(PyExc_ValueError,
154 "could not convert string to float: "
155 "%R", obj);
156 return NULL;
157 }
158 else if (x == -1.0 && PyErr_Occurred()) {
159 return NULL;
160 }
161 else {
162 return PyFloat_FromDouble(x);
163 }
164}
165
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000166PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000167PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000168{
Brett Cannona721aba2016-09-09 14:57:09 -0700169 const char *s;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000170 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 Py_ssize_t len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200172 Py_buffer view = {NULL, NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200176 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000178 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200179 assert(PyUnicode_IS_ASCII(s_buffer));
180 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200181 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200182 assert(s != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000184 else if (PyBytes_Check(v)) {
185 s = PyBytes_AS_STRING(v);
186 len = PyBytes_GET_SIZE(v);
187 }
188 else if (PyByteArray_Check(v)) {
189 s = PyByteArray_AS_STRING(v);
190 len = PyByteArray_GET_SIZE(v);
191 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200192 else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
193 s = (const char *)view.buf;
194 len = view.len;
Martin Pantereeb896c2015-11-07 02:32:21 +0000195 /* Copy to NUL-terminated buffer. */
196 s_buffer = PyBytes_FromStringAndSize(s, len);
197 if (s_buffer == NULL) {
198 PyBuffer_Release(&view);
199 return NULL;
200 }
201 s = PyBytes_AS_STRING(s_buffer);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200202 }
203 else {
Ezio Melottia5b95992013-11-07 19:18:34 +0200204 PyErr_Format(PyExc_TypeError,
205 "float() argument must be a string or a number, not '%.200s'",
206 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 return NULL;
208 }
Brett Cannona721aba2016-09-09 14:57:09 -0700209 result = _Py_string_to_number_with_underscores(s, len, "float", v, v,
210 float_from_string_inner);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200211 PyBuffer_Release(&view);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000212 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000214}
215
Guido van Rossum234f9421993-06-17 12:35:49 +0000216static void
Fred Drakefd99de62000-07-09 05:02:18 +0000217float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 if (PyFloat_CheckExact(op)) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000220 if (numfree >= PyFloat_MAXFREELIST) {
221 PyObject_FREE(op);
222 return;
223 }
224 numfree++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 Py_TYPE(op) = (struct _typeobject *)free_list;
226 free_list = op;
227 }
228 else
229 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000230}
231
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000232double
Fred Drakefd99de62000-07-09 05:02:18 +0000233PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 PyNumberMethods *nb;
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300236 PyObject *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 if (op == NULL) {
240 PyErr_BadArgument();
241 return -1;
242 }
Tim Petersd2364e82001-11-01 20:09:42 +0000243
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300244 if (PyFloat_Check(op)) {
245 return PyFloat_AS_DOUBLE(op);
246 }
247
248 nb = Py_TYPE(op)->tp_as_number;
249 if (nb == NULL || nb->nb_float == NULL) {
250 PyErr_Format(PyExc_TypeError, "must be real number, not %.50s",
251 op->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 return -1;
253 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000254
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300255 res = (*nb->nb_float) (op);
256 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 return -1;
258 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300259 if (!PyFloat_CheckExact(res)) {
260 if (!PyFloat_Check(res)) {
261 PyErr_Format(PyExc_TypeError,
262 "%.50s.__float__ returned non-float (type %.50s)",
263 op->ob_type->tp_name, res->ob_type->tp_name);
264 Py_DECREF(res);
265 return -1;
266 }
267 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
268 "%.50s.__float__ returned non-float (type %.50s). "
269 "The ability to return an instance of a strict subclass of float "
270 "is deprecated, and may be removed in a future version of Python.",
271 op->ob_type->tp_name, res->ob_type->tp_name)) {
272 Py_DECREF(res);
273 return -1;
274 }
275 }
Tim Petersd2364e82001-11-01 20:09:42 +0000276
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300277 val = PyFloat_AS_DOUBLE(res);
278 Py_DECREF(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000280}
281
Neil Schemenauer32117e52001-01-04 01:44:34 +0000282/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000283 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000284 set to NULL, and the function invoking this macro returns NULL. If
Serhiy Storchaka95949422013-08-27 19:40:23 +0300285 obj is not of float or int type, Py_NotImplemented is incref'ed,
Tim Peters77d8a4f2001-12-11 20:31:34 +0000286 stored in obj, and returned from the function invoking this macro.
287*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288#define CONVERT_TO_DOUBLE(obj, dbl) \
289 if (PyFloat_Check(obj)) \
290 dbl = PyFloat_AS_DOUBLE(obj); \
291 else if (convert_to_double(&(obj), &(dbl)) < 0) \
292 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000293
Eric Smith0923d1d2009-04-16 20:16:10 +0000294/* Methods */
295
Neil Schemenauer32117e52001-01-04 01:44:34 +0000296static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000297convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000298{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200299 PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 if (PyLong_Check(obj)) {
302 *dbl = PyLong_AsDouble(obj);
303 if (*dbl == -1.0 && PyErr_Occurred()) {
304 *v = NULL;
305 return -1;
306 }
307 }
308 else {
309 Py_INCREF(Py_NotImplemented);
310 *v = Py_NotImplemented;
311 return -1;
312 }
313 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000314}
315
Eric Smith0923d1d2009-04-16 20:16:10 +0000316static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000317float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000318{
319 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200320 char *buf;
321
322 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
323 'r', 0,
324 Py_DTSF_ADD_DOT_0,
325 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000326 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000327 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200328 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000329 PyMem_Free(buf);
330 return result;
331}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000332
Tim Peters307fa782004-09-23 08:06:40 +0000333/* Comparison is pretty much a nightmare. When comparing float to float,
334 * we do it as straightforwardly (and long-windedly) as conceivable, so
335 * that, e.g., Python x == y delivers the same result as the platform
336 * C x == y when x and/or y is a NaN.
337 * When mixing float with an integer type, there's no good *uniform* approach.
338 * Converting the double to an integer obviously doesn't work, since we
339 * may lose info from fractional bits. Converting the integer to a double
Serhiy Storchaka95949422013-08-27 19:40:23 +0300340 * also has two failure modes: (1) an int may trigger overflow (too
Tim Peters307fa782004-09-23 08:06:40 +0000341 * large to fit in the dynamic range of a C double); (2) even a C long may have
Ezio Melotti3f5db392013-01-27 06:20:14 +0200342 * more bits than fit in a C double (e.g., on a 64-bit box long may have
Tim Peters307fa782004-09-23 08:06:40 +0000343 * 63 bits of precision, but a C double probably has only 53), and then
344 * we can falsely claim equality when low-order integer bits are lost by
345 * coercion to double. So this part is painful too.
346 */
347
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000348static PyObject*
349float_richcompare(PyObject *v, PyObject *w, int op)
350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 double i, j;
352 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 assert(PyFloat_Check(v));
355 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 /* Switch on the type of w. Set i and j to doubles to be compared,
358 * and op to the richcomp to use.
359 */
360 if (PyFloat_Check(w))
361 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 else if (!Py_IS_FINITE(i)) {
364 if (PyLong_Check(w))
365 /* If i is an infinity, its magnitude exceeds any
366 * finite integer, so it doesn't matter which int we
367 * compare i with. If i is a NaN, similarly.
368 */
369 j = 0.0;
370 else
371 goto Unimplemented;
372 }
Tim Peters307fa782004-09-23 08:06:40 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 else if (PyLong_Check(w)) {
375 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
376 int wsign = _PyLong_Sign(w);
377 size_t nbits;
378 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 if (vsign != wsign) {
381 /* Magnitudes are irrelevant -- the signs alone
382 * determine the outcome.
383 */
384 i = (double)vsign;
385 j = (double)wsign;
386 goto Compare;
387 }
388 /* The signs are the same. */
389 /* Convert w to a double if it fits. In particular, 0 fits. */
390 nbits = _PyLong_NumBits(w);
391 if (nbits == (size_t)-1 && PyErr_Occurred()) {
392 /* This long is so large that size_t isn't big enough
393 * to hold the # of bits. Replace with little doubles
394 * that give the same outcome -- w is so large that
395 * its magnitude must exceed the magnitude of any
396 * finite float.
397 */
398 PyErr_Clear();
399 i = (double)vsign;
400 assert(wsign != 0);
401 j = wsign * 2.0;
402 goto Compare;
403 }
404 if (nbits <= 48) {
405 j = PyLong_AsDouble(w);
406 /* It's impossible that <= 48 bits overflowed. */
407 assert(j != -1.0 || ! PyErr_Occurred());
408 goto Compare;
409 }
410 assert(wsign != 0); /* else nbits was 0 */
411 assert(vsign != 0); /* if vsign were 0, then since wsign is
412 * not 0, we would have taken the
413 * vsign != wsign branch at the start */
414 /* We want to work with non-negative numbers. */
415 if (vsign < 0) {
416 /* "Multiply both sides" by -1; this also swaps the
417 * comparator.
418 */
419 i = -i;
420 op = _Py_SwappedOp[op];
421 }
422 assert(i > 0.0);
423 (void) frexp(i, &exponent);
424 /* exponent is the # of bits in v before the radix point;
425 * we know that nbits (the # of bits in w) > 48 at this point
426 */
427 if (exponent < 0 || (size_t)exponent < nbits) {
428 i = 1.0;
429 j = 2.0;
430 goto Compare;
431 }
432 if ((size_t)exponent > nbits) {
433 i = 2.0;
434 j = 1.0;
435 goto Compare;
436 }
437 /* v and w have the same number of bits before the radix
Serhiy Storchaka95949422013-08-27 19:40:23 +0300438 * point. Construct two ints that have the same comparison
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 * outcome.
440 */
441 {
442 double fracpart;
443 double intpart;
444 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 PyObject *vv = NULL;
446 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 if (wsign < 0) {
449 ww = PyNumber_Negative(w);
450 if (ww == NULL)
451 goto Error;
452 }
453 else
454 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 fracpart = modf(i, &intpart);
457 vv = PyLong_FromDouble(intpart);
458 if (vv == NULL)
459 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (fracpart != 0.0) {
462 /* Shift left, and or a 1 bit into vv
463 * to represent the lost fraction.
464 */
465 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000466
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300467 temp = PyNumber_Lshift(ww, _PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 if (temp == NULL)
469 goto Error;
470 Py_DECREF(ww);
471 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000472
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300473 temp = PyNumber_Lshift(vv, _PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (temp == NULL)
475 goto Error;
476 Py_DECREF(vv);
477 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000478
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300479 temp = PyNumber_Or(vv, _PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 if (temp == NULL)
481 goto Error;
482 Py_DECREF(vv);
483 vv = temp;
484 }
Tim Peters307fa782004-09-23 08:06:40 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 r = PyObject_RichCompareBool(vv, ww, op);
487 if (r < 0)
488 goto Error;
489 result = PyBool_FromLong(r);
490 Error:
491 Py_XDECREF(vv);
492 Py_XDECREF(ww);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 return result;
494 }
495 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000496
Serhiy Storchaka95949422013-08-27 19:40:23 +0300497 else /* w isn't float or int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000499
500 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 PyFPE_START_PROTECT("richcompare", return NULL)
502 switch (op) {
503 case Py_EQ:
504 r = i == j;
505 break;
506 case Py_NE:
507 r = i != j;
508 break;
509 case Py_LE:
510 r = i <= j;
511 break;
512 case Py_GE:
513 r = i >= j;
514 break;
515 case Py_LT:
516 r = i < j;
517 break;
518 case Py_GT:
519 r = i > j;
520 break;
521 }
522 PyFPE_END_PROTECT(r)
523 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000524
525 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500526 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000527}
528
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000529static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000530float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000533}
534
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000535static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000536float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 double a,b;
539 CONVERT_TO_DOUBLE(v, a);
540 CONVERT_TO_DOUBLE(w, b);
541 PyFPE_START_PROTECT("add", return 0)
542 a = a + b;
543 PyFPE_END_PROTECT(a)
544 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000545}
546
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000547static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000548float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 double a,b;
551 CONVERT_TO_DOUBLE(v, a);
552 CONVERT_TO_DOUBLE(w, b);
553 PyFPE_START_PROTECT("subtract", return 0)
554 a = a - b;
555 PyFPE_END_PROTECT(a)
556 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000557}
558
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000559static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000560float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 double a,b;
563 CONVERT_TO_DOUBLE(v, a);
564 CONVERT_TO_DOUBLE(w, b);
565 PyFPE_START_PROTECT("multiply", return 0)
566 a = a * b;
567 PyFPE_END_PROTECT(a)
568 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000569}
570
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000571static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000572float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 double a,b;
575 CONVERT_TO_DOUBLE(v, a);
576 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 if (b == 0.0) {
578 PyErr_SetString(PyExc_ZeroDivisionError,
579 "float division by zero");
580 return NULL;
581 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 PyFPE_START_PROTECT("divide", return 0)
583 a = a / b;
584 PyFPE_END_PROTECT(a)
585 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000586}
587
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000588static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000589float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 double vx, wx;
592 double mod;
593 CONVERT_TO_DOUBLE(v, vx);
594 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 if (wx == 0.0) {
596 PyErr_SetString(PyExc_ZeroDivisionError,
597 "float modulo");
598 return NULL;
599 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 PyFPE_START_PROTECT("modulo", return 0)
601 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000602 if (mod) {
603 /* ensure the remainder has the same sign as the denominator */
604 if ((wx < 0) != (mod < 0)) {
605 mod += wx;
606 }
607 }
608 else {
609 /* the remainder is zero, and in the presence of signed zeroes
610 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000611 it has the same sign as the denominator. */
612 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 }
614 PyFPE_END_PROTECT(mod)
615 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000616}
617
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000618static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000619float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 double vx, wx;
622 double div, mod, floordiv;
623 CONVERT_TO_DOUBLE(v, vx);
624 CONVERT_TO_DOUBLE(w, wx);
625 if (wx == 0.0) {
626 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
627 return NULL;
628 }
629 PyFPE_START_PROTECT("divmod", return 0)
630 mod = fmod(vx, wx);
631 /* fmod is typically exact, so vx-mod is *mathematically* an
632 exact multiple of wx. But this is fp arithmetic, and fp
633 vx - mod is an approximation; the result is that div may
634 not be an exact integral value after the division, although
635 it will always be very close to one.
636 */
637 div = (vx - mod) / wx;
638 if (mod) {
639 /* ensure the remainder has the same sign as the denominator */
640 if ((wx < 0) != (mod < 0)) {
641 mod += wx;
642 div -= 1.0;
643 }
644 }
645 else {
646 /* the remainder is zero, and in the presence of signed zeroes
647 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000648 it has the same sign as the denominator. */
649 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 }
651 /* snap quotient to nearest integral value */
652 if (div) {
653 floordiv = floor(div);
654 if (div - floordiv > 0.5)
655 floordiv += 1.0;
656 }
657 else {
658 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000659 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 }
661 PyFPE_END_PROTECT(floordiv)
662 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000663}
664
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000665static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000666float_floor_div(PyObject *v, PyObject *w)
667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 t = float_divmod(v, w);
671 if (t == NULL || t == Py_NotImplemented)
672 return t;
673 assert(PyTuple_CheckExact(t));
674 r = PyTuple_GET_ITEM(t, 0);
675 Py_INCREF(r);
676 Py_DECREF(t);
677 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000678}
679
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000680/* determine whether x is an odd integer or not; assumes that
681 x is not an infinity or nan. */
682#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
683
Tim Peters63a35712001-12-11 19:57:24 +0000684static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000685float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 double iv, iw, ix;
688 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 if ((PyObject *)z != Py_None) {
691 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
692 "allowed unless all arguments are integers");
693 return NULL;
694 }
Tim Peters32f453e2001-09-03 08:35:41 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 CONVERT_TO_DOUBLE(v, iv);
697 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 /* Sort out special cases here instead of relying on pow() */
700 if (iw == 0) { /* v**0 is 1, even 0**0 */
701 return PyFloat_FromDouble(1.0);
702 }
703 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
704 return PyFloat_FromDouble(iv);
705 }
706 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
707 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
708 }
709 if (Py_IS_INFINITY(iw)) {
710 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
711 * abs(v) > 1 (including case where v infinite)
712 *
713 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
714 * abs(v) > 1 (including case where v infinite)
715 */
716 iv = fabs(iv);
717 if (iv == 1.0)
718 return PyFloat_FromDouble(1.0);
719 else if ((iw > 0.0) == (iv > 1.0))
720 return PyFloat_FromDouble(fabs(iw)); /* return inf */
721 else
722 return PyFloat_FromDouble(0.0);
723 }
724 if (Py_IS_INFINITY(iv)) {
725 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
726 * both cases, we need to add the appropriate sign if w is
727 * an odd integer.
728 */
729 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
730 if (iw > 0.0)
731 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
732 else
733 return PyFloat_FromDouble(iw_is_odd ?
734 copysign(0.0, iv) : 0.0);
735 }
736 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
737 (already dealt with above), and an error
738 if w is negative. */
739 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
740 if (iw < 0.0) {
741 PyErr_SetString(PyExc_ZeroDivisionError,
742 "0.0 cannot be raised to a "
743 "negative power");
744 return NULL;
745 }
746 /* use correct sign if iw is odd */
747 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
748 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 if (iv < 0.0) {
751 /* Whether this is an error is a mess, and bumps into libm
752 * bugs so we have to figure it out ourselves.
753 */
754 if (iw != floor(iw)) {
755 /* Negative numbers raised to fractional powers
756 * become complex.
757 */
758 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
759 }
760 /* iw is an exact integer, albeit perhaps a very large
761 * one. Replace iv by its absolute value and remember
762 * to negate the pow result if iw is odd.
763 */
764 iv = -iv;
765 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
766 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
769 /* (-1) ** large_integer also ends up here. Here's an
770 * extract from the comments for the previous
771 * implementation explaining why this special case is
772 * necessary:
773 *
774 * -1 raised to an exact integer should never be exceptional.
775 * Alas, some libms (chiefly glibc as of early 2003) return
776 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
777 * happen to be representable in a *C* integer. That's a
778 * bug.
779 */
780 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
781 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 /* Now iv and iw are finite, iw is nonzero, and iv is
784 * positive and not equal to 1.0. We finally allow
785 * the platform pow to step in and do the rest.
786 */
787 errno = 0;
788 PyFPE_START_PROTECT("pow", return NULL)
789 ix = pow(iv, iw);
790 PyFPE_END_PROTECT(ix)
791 Py_ADJUST_ERANGE1(ix);
792 if (negate_result)
793 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 if (errno != 0) {
796 /* We don't expect any errno value other than ERANGE, but
797 * the range of libm bugs appears unbounded.
798 */
799 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
800 PyExc_ValueError);
801 return NULL;
802 }
803 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000804}
805
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000806#undef DOUBLE_IS_ODD_INTEGER
807
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000808static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000809float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000812}
813
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000814static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000815float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000818}
819
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000820static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000821float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000824}
825
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200826/*[clinic input]
827float.is_integer
828
829Return True if the float is an integer.
830[clinic start generated code]*/
831
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000832static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200833float_is_integer_impl(PyObject *self)
834/*[clinic end generated code: output=7112acf95a4d31ea input=311810d3f777e10d]*/
Christian Heimes53876d92008-04-19 00:31:39 +0000835{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200836 double x = PyFloat_AsDouble(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 PyObject *o;
838
839 if (x == -1.0 && PyErr_Occurred())
840 return NULL;
841 if (!Py_IS_FINITE(x))
842 Py_RETURN_FALSE;
843 errno = 0;
844 PyFPE_START_PROTECT("is_integer", return NULL)
845 o = (floor(x) == x) ? Py_True : Py_False;
846 PyFPE_END_PROTECT(x)
847 if (errno != 0) {
848 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
849 PyExc_ValueError);
850 return NULL;
851 }
852 Py_INCREF(o);
853 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000854}
855
856#if 0
857static PyObject *
858float_is_inf(PyObject *v)
859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 double x = PyFloat_AsDouble(v);
861 if (x == -1.0 && PyErr_Occurred())
862 return NULL;
863 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000864}
865
866static PyObject *
867float_is_nan(PyObject *v)
868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 double x = PyFloat_AsDouble(v);
870 if (x == -1.0 && PyErr_Occurred())
871 return NULL;
872 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000873}
874
875static PyObject *
876float_is_finite(PyObject *v)
877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 double x = PyFloat_AsDouble(v);
879 if (x == -1.0 && PyErr_Occurred())
880 return NULL;
881 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000882}
883#endif
884
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200885/*[clinic input]
886float.__trunc__
887
888Return the Integral closest to x between 0 and x.
889[clinic start generated code]*/
890
Christian Heimes53876d92008-04-19 00:31:39 +0000891static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200892float___trunc___impl(PyObject *self)
893/*[clinic end generated code: output=dd3e289dd4c6b538 input=591b9ba0d650fdff]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000894{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200895 double x = PyFloat_AsDouble(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 (void)modf(x, &wholepart);
899 /* Try to get out cheap if this fits in a Python int. The attempt
900 * to cast to long must be protected, as C doesn't define what
901 * happens if the double is too big to fit in a long. Some rare
902 * systems raise an exception then (RISCOS was mentioned as one,
903 * and someone using a non-default option on Sun also bumped into
904 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
905 * still be vulnerable: if a long has more bits of precision than
906 * a double, casting MIN/MAX to double may yield an approximation,
907 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
908 * yield true from the C expression wholepart<=LONG_MAX, despite
909 * that wholepart is actually greater than LONG_MAX.
910 */
911 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
912 const long aslong = (long)wholepart;
913 return PyLong_FromLong(aslong);
914 }
915 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000916}
917
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000918/* double_round: rounds a finite double to the closest multiple of
919 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
920 ndigits <= 323). Returns a Python float, or sets a Python error and
921 returns NULL on failure (OverflowError and memory errors are possible). */
922
923#ifndef PY_NO_SHORT_FLOAT_REPR
924/* version of double_round that uses the correctly-rounded string<->double
925 conversions from Python/dtoa.c */
926
927static PyObject *
928double_round(double x, int ndigits) {
929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 double rounded;
931 Py_ssize_t buflen, mybuflen=100;
932 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
933 int decpt, sign;
934 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000935 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000938 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000940 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 if (buf == NULL) {
942 PyErr_NoMemory();
943 return NULL;
944 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
947 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
948 buflen = buf_end - buf;
949 if (buflen + 8 > mybuflen) {
950 mybuflen = buflen+8;
951 mybuf = (char *)PyMem_Malloc(mybuflen);
952 if (mybuf == NULL) {
953 PyErr_NoMemory();
954 goto exit;
955 }
956 }
957 /* copy buf to mybuf, adding exponent, sign and leading 0 */
958 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
959 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 /* and convert the resulting string back to a double */
962 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000963 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000965 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 if (errno == ERANGE && fabs(rounded) >= 1.)
967 PyErr_SetString(PyExc_OverflowError,
968 "rounded value too large to represent");
969 else
970 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 /* done computing value; now clean up */
973 if (mybuf != shortbuf)
974 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000975 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 _Py_dg_freedtoa(buf);
977 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000978}
979
980#else /* PY_NO_SHORT_FLOAT_REPR */
981
982/* fallback version, to be used when correctly rounded binary<->decimal
983 conversions aren't available */
984
985static PyObject *
986double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 double pow1, pow2, y, z;
988 if (ndigits >= 0) {
989 if (ndigits > 22) {
990 /* pow1 and pow2 are each safe from overflow, but
991 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
992 pow1 = pow(10.0, (double)(ndigits-22));
993 pow2 = 1e22;
994 }
995 else {
996 pow1 = pow(10.0, (double)ndigits);
997 pow2 = 1.0;
998 }
999 y = (x*pow1)*pow2;
1000 /* if y overflows, then rounded value is exactly x */
1001 if (!Py_IS_FINITE(y))
1002 return PyFloat_FromDouble(x);
1003 }
1004 else {
1005 pow1 = pow(10.0, (double)-ndigits);
1006 pow2 = 1.0; /* unused; silences a gcc compiler warning */
1007 y = x / pow1;
1008 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 z = round(y);
1011 if (fabs(y-z) == 0.5)
1012 /* halfway between two integers; use round-half-even */
1013 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 if (ndigits >= 0)
1016 z = (z / pow2) / pow1;
1017 else
1018 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 /* if computation resulted in overflow, raise OverflowError */
1021 if (!Py_IS_FINITE(z)) {
1022 PyErr_SetString(PyExc_OverflowError,
1023 "overflow occurred during round");
1024 return NULL;
1025 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001028}
1029
1030#endif /* PY_NO_SHORT_FLOAT_REPR */
1031
1032/* round a Python float v to the closest multiple of 10**-ndigits */
1033
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001034/*[clinic input]
1035float.__round__
1036
1037 ndigits as o_ndigits: object = NULL
1038 /
1039
1040Return the Integral closest to x, rounding half toward even.
1041
1042When an argument is passed, work like built-in round(x, ndigits).
1043[clinic start generated code]*/
1044
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001045static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001046float___round___impl(PyObject *self, PyObject *o_ndigits)
1047/*[clinic end generated code: output=374c36aaa0f13980 input=1ca2316b510293b8]*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 double x, rounded;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001051
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001052 x = PyFloat_AsDouble(self);
Steve Dowercb39d1f2015-04-15 16:10:59 -04001053 if (o_ndigits == NULL || o_ndigits == Py_None) {
1054 /* single-argument round or with None ndigits:
1055 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 rounded = round(x);
1057 if (fabs(x-rounded) == 0.5)
1058 /* halfway case: round to even */
1059 rounded = 2.0*round(x/2.0);
1060 return PyLong_FromDouble(rounded);
1061 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 /* interpret second argument as a Py_ssize_t; clips on overflow */
1064 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1065 if (ndigits == -1 && PyErr_Occurred())
1066 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 /* nans and infinities round to themselves */
1069 if (!Py_IS_FINITE(x))
1070 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1073 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1074 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001075#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1076#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 if (ndigits > NDIGITS_MAX)
1078 /* return x */
1079 return PyFloat_FromDouble(x);
1080 else if (ndigits < NDIGITS_MIN)
1081 /* return 0.0, but with sign of x */
1082 return PyFloat_FromDouble(0.0*x);
1083 else
1084 /* finite x, and ndigits is not unreasonably large */
1085 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001086#undef NDIGITS_MAX
1087#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001088}
1089
1090static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001091float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 if (PyFloat_CheckExact(v))
1094 Py_INCREF(v);
1095 else
1096 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1097 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001098}
1099
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001100/*[clinic input]
1101float.conjugate
1102
1103Return self, the complex conjugate of any float.
1104[clinic start generated code]*/
1105
1106static PyObject *
1107float_conjugate_impl(PyObject *self)
1108/*[clinic end generated code: output=8ca292c2479194af input=82ba6f37a9ff91dd]*/
1109{
1110 return float_float(self);
1111}
1112
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001113/* turn ASCII hex characters into integer values and vice versa */
1114
1115static char
1116char_from_hex(int x)
1117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001119 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001120}
1121
1122static int
1123hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 int x;
1125 switch(c) {
1126 case '0':
1127 x = 0;
1128 break;
1129 case '1':
1130 x = 1;
1131 break;
1132 case '2':
1133 x = 2;
1134 break;
1135 case '3':
1136 x = 3;
1137 break;
1138 case '4':
1139 x = 4;
1140 break;
1141 case '5':
1142 x = 5;
1143 break;
1144 case '6':
1145 x = 6;
1146 break;
1147 case '7':
1148 x = 7;
1149 break;
1150 case '8':
1151 x = 8;
1152 break;
1153 case '9':
1154 x = 9;
1155 break;
1156 case 'a':
1157 case 'A':
1158 x = 10;
1159 break;
1160 case 'b':
1161 case 'B':
1162 x = 11;
1163 break;
1164 case 'c':
1165 case 'C':
1166 x = 12;
1167 break;
1168 case 'd':
1169 case 'D':
1170 x = 13;
1171 break;
1172 case 'e':
1173 case 'E':
1174 x = 14;
1175 break;
1176 case 'f':
1177 case 'F':
1178 x = 15;
1179 break;
1180 default:
1181 x = -1;
1182 break;
1183 }
1184 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001185}
1186
1187/* convert a float to a hexadecimal string */
1188
1189/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1190 of the form 4k+1. */
1191#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1192
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001193/*[clinic input]
1194float.hex
1195
1196Return a hexadecimal representation of a floating-point number.
1197
1198>>> (-0.1).hex()
1199'-0x1.999999999999ap-4'
1200>>> 3.14159.hex()
1201'0x1.921f9f01b866ep+1'
1202[clinic start generated code]*/
1203
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001204static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001205float_hex_impl(PyObject *self)
1206/*[clinic end generated code: output=0ebc9836e4d302d4 input=bec1271a33d47e67]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 double x, m;
1209 int e, shift, i, si, esign;
1210 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1211 trailing NUL byte. */
1212 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001213
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001214 CONVERT_TO_DOUBLE(self, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001217 return float_repr((PyFloatObject *)self);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001220 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 return PyUnicode_FromString("-0x0.0p+0");
1222 else
1223 return PyUnicode_FromString("0x0.0p+0");
1224 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001227 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 m = ldexp(m, shift);
1229 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 si = 0;
1232 s[si] = char_from_hex((int)m);
1233 si++;
1234 m -= (int)m;
1235 s[si] = '.';
1236 si++;
1237 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1238 m *= 16.0;
1239 s[si] = char_from_hex((int)m);
1240 si++;
1241 m -= (int)m;
1242 }
1243 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 if (e < 0) {
1246 esign = (int)'-';
1247 e = -e;
1248 }
1249 else
1250 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 if (x < 0.0)
1253 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1254 else
1255 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001256}
1257
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001258/* Convert a hexadecimal string to a float. */
1259
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001260/*[clinic input]
1261@classmethod
1262float.fromhex
1263
1264 string: object
1265 /
1266
1267Create a floating-point number from a hexadecimal string.
1268
1269>>> float.fromhex('0x1.ffffp10')
12702047.984375
1271>>> float.fromhex('-0x1p-1074')
1272-5e-324
1273[clinic start generated code]*/
1274
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001275static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001276float_fromhex(PyTypeObject *type, PyObject *string)
1277/*[clinic end generated code: output=46c0274d22b78e82 input=0407bebd354bca89]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001278{
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001279 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 double x;
1281 long exp, top_exp, lsb, key_digit;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001282 const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 int half_eps, digit, round_up, negate=0;
1284 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 /*
1287 * For the sake of simplicity and correctness, we impose an artificial
1288 * limit on ndigits, the total number of hex digits in the coefficient
1289 * The limit is chosen to ensure that, writing exp for the exponent,
1290 *
1291 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1292 * guaranteed to overflow (provided it's nonzero)
1293 *
1294 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1295 * guaranteed to underflow to 0.
1296 *
1297 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1298 * overflow in the calculation of exp and top_exp below.
1299 *
1300 * More specifically, ndigits is assumed to satisfy the following
1301 * inequalities:
1302 *
1303 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1304 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1305 *
1306 * If either of these inequalities is not satisfied, a ValueError is
1307 * raised. Otherwise, write x for the value of the hex string, and
1308 * assume x is nonzero. Then
1309 *
1310 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1311 *
1312 * Now if exp > LONG_MAX/2 then:
1313 *
1314 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1315 * = DBL_MAX_EXP
1316 *
1317 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1318 * double, so overflows. If exp < LONG_MIN/2, then
1319 *
1320 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1321 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1322 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1323 *
1324 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1325 * when converted to a C double.
1326 *
1327 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1328 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1329 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001330
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001331 s = PyUnicode_AsUTF8AndSize(string, &length);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 if (s == NULL)
1333 return NULL;
1334 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 /********************
1337 * Parse the string *
1338 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 /* leading whitespace */
1341 while (Py_ISSPACE(*s))
1342 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 /* infinities and nans */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001345 x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 if (coeff_end != s) {
1347 s = coeff_end;
1348 goto finished;
1349 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 /* optional sign */
1352 if (*s == '-') {
1353 s++;
1354 negate = 1;
1355 }
1356 else if (*s == '+')
1357 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 /* [0x] */
1360 s_store = s;
1361 if (*s == '0') {
1362 s++;
1363 if (*s == 'x' || *s == 'X')
1364 s++;
1365 else
1366 s = s_store;
1367 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 /* coefficient: <integer> [. <fraction>] */
1370 coeff_start = s;
1371 while (hex_from_char(*s) >= 0)
1372 s++;
1373 s_store = s;
1374 if (*s == '.') {
1375 s++;
1376 while (hex_from_char(*s) >= 0)
1377 s++;
1378 coeff_end = s-1;
1379 }
1380 else
1381 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 /* ndigits = total # of hex digits; fdigits = # after point */
1384 ndigits = coeff_end - coeff_start;
1385 fdigits = coeff_end - s_store;
1386 if (ndigits == 0)
1387 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001388 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1389 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 /* [p <exponent>] */
1393 if (*s == 'p' || *s == 'P') {
1394 s++;
1395 exp_start = s;
1396 if (*s == '-' || *s == '+')
1397 s++;
1398 if (!('0' <= *s && *s <= '9'))
1399 goto parse_error;
1400 s++;
1401 while ('0' <= *s && *s <= '9')
1402 s++;
1403 exp = strtol(exp_start, NULL, 10);
1404 }
1405 else
1406 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001407
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001408/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1410 coeff_end-(j) : \
1411 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 /*******************************************
1414 * Compute rounded value of the hex string *
1415 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 /* Discard leading zeros, and catch extreme overflow and underflow */
1418 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1419 ndigits--;
1420 if (ndigits == 0 || exp < LONG_MIN/2) {
1421 x = 0.0;
1422 goto finished;
1423 }
1424 if (exp > LONG_MAX/2)
1425 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 /* Adjust exponent for fractional part. */
1428 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1431 top_exp = exp + 4*((long)ndigits - 1);
1432 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1433 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 /* catch almost all nonextreme cases of overflow and underflow here */
1436 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1437 x = 0.0;
1438 goto finished;
1439 }
1440 if (top_exp > DBL_MAX_EXP)
1441 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 /* lsb = exponent of least significant bit of the *rounded* value.
1444 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001445 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 x = 0.0;
1448 if (exp >= lsb) {
1449 /* no rounding required */
1450 for (i = ndigits-1; i >= 0; i--)
1451 x = 16.0*x + HEX_DIGIT(i);
1452 x = ldexp(x, (int)(exp));
1453 goto finished;
1454 }
1455 /* rounding required. key_digit is the index of the hex digit
1456 containing the first bit to be rounded away. */
1457 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1458 key_digit = (lsb - exp - 1) / 4;
1459 for (i = ndigits-1; i > key_digit; i--)
1460 x = 16.0*x + HEX_DIGIT(i);
1461 digit = HEX_DIGIT(key_digit);
1462 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 /* 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 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001477 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 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));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001487
1488 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 /* optional trailing whitespace leading to the end of the string */
1490 while (Py_ISSPACE(*s))
1491 s++;
1492 if (s != s_end)
1493 goto parse_error;
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001494 result = PyFloat_FromDouble(negate ? -x : x);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001495 if (type != &PyFloat_Type && result != NULL) {
1496 Py_SETREF(result, PyObject_CallFunctionObjArgs((PyObject *)type, result, NULL));
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001497 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001499
1500 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 PyErr_SetString(PyExc_OverflowError,
1502 "hexadecimal value too large to represent as a float");
1503 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001504
1505 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 PyErr_SetString(PyExc_ValueError,
1507 "invalid hexadecimal floating-point string");
1508 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001509
1510 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 PyErr_SetString(PyExc_ValueError,
1512 "hexadecimal string too long to convert");
1513 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001514}
1515
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001516/*[clinic input]
1517float.as_integer_ratio
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001518
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001519Return integer ratio.
1520
1521Return a pair of integers, whose ratio is exactly equal to the original float
1522and with a positive denominator.
1523
1524Raise OverflowError on infinities and a ValueError on NaNs.
1525
1526>>> (10.0).as_integer_ratio()
1527(10, 1)
1528>>> (0.0).as_integer_ratio()
1529(0, 1)
1530>>> (-.25).as_integer_ratio()
1531(-1, 4)
1532[clinic start generated code]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001533
Christian Heimes26855632008-01-27 23:50:43 +00001534static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001535float_as_integer_ratio_impl(PyObject *self)
1536/*[clinic end generated code: output=65f25f0d8d30a712 input=e21d08b4630c2e44]*/
Christian Heimes26855632008-01-27 23:50:43 +00001537{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001538 double self_double;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 double float_part;
1540 int exponent;
1541 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 PyObject *py_exponent = NULL;
1544 PyObject *numerator = NULL;
1545 PyObject *denominator = NULL;
1546 PyObject *result_pair = NULL;
1547 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001548
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001549 CONVERT_TO_DOUBLE(self, self_double);
Christian Heimes26855632008-01-27 23:50:43 +00001550
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001551 if (Py_IS_INFINITY(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001552 PyErr_SetString(PyExc_OverflowError,
1553 "cannot convert Infinity to integer ratio");
1554 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001556 if (Py_IS_NAN(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001557 PyErr_SetString(PyExc_ValueError,
1558 "cannot convert NaN to integer ratio");
1559 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 }
Christian Heimes26855632008-01-27 23:50:43 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001563 float_part = frexp(self_double, &exponent); /* self_double == float_part * 2**exponent exactly */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1567 float_part *= 2.0;
1568 exponent--;
1569 }
1570 /* self == float_part * 2**exponent exactly and float_part is integral.
1571 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1572 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 numerator = PyLong_FromDouble(float_part);
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001575 if (numerator == NULL)
1576 goto error;
1577 denominator = PyLong_FromLong(1);
1578 if (denominator == NULL)
1579 goto error;
1580 py_exponent = PyLong_FromLong(Py_ABS(exponent));
1581 if (py_exponent == NULL)
1582 goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 /* fold in 2**exponent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 if (exponent > 0) {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001586 Py_SETREF(numerator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001587 long_methods->nb_lshift(numerator, py_exponent));
1588 if (numerator == NULL)
1589 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 }
1591 else {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001592 Py_SETREF(denominator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001593 long_methods->nb_lshift(denominator, py_exponent));
1594 if (denominator == NULL)
1595 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 }
1597
1598 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001599
Christian Heimes26855632008-01-27 23:50:43 +00001600error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 Py_XDECREF(py_exponent);
1602 Py_XDECREF(denominator);
1603 Py_XDECREF(numerator);
1604 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001605}
1606
Jeremy Hylton938ace62002-07-17 16:30:39 +00001607static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001608float_subtype_new(PyTypeObject *type, PyObject *x);
1609
1610/*[clinic input]
1611@classmethod
1612float.__new__ as float_new
Serhiy Storchakaba85d692017-03-30 09:09:41 +03001613 x: object(c_default="_PyLong_Zero") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001614 /
1615
1616Convert a string or number to a floating point number, if possible.
1617[clinic start generated code]*/
Guido van Rossumbef14172001-08-29 15:47:46 +00001618
Tim Peters6d6c1a32001-08-02 04:15:00 +00001619static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001620float_new_impl(PyTypeObject *type, PyObject *x)
Serhiy Storchakabae68812017-04-05 12:00:42 +03001621/*[clinic end generated code: output=ccf1e8dc460ba6ba input=540ee77c204ff87a]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00001622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (type != &PyFloat_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001624 return float_subtype_new(type, x); /* Wimp out */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 /* If it's a string, but not a string subclass, use
1626 PyFloat_FromString. */
1627 if (PyUnicode_CheckExact(x))
1628 return PyFloat_FromString(x);
1629 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001630}
1631
Guido van Rossumbef14172001-08-29 15:47:46 +00001632/* Wimpy, slow approach to tp_new calls for subtypes of float:
1633 first create a regular float from whatever arguments we got,
1634 then allocate a subtype instance and initialize its ob_fval
1635 from the regular float. The regular float is then thrown away.
1636*/
1637static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001638float_subtype_new(PyTypeObject *type, PyObject *x)
Guido van Rossumbef14172001-08-29 15:47:46 +00001639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 assert(PyType_IsSubtype(type, &PyFloat_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001643 tmp = float_new_impl(&PyFloat_Type, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 if (tmp == NULL)
1645 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001646 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 newobj = type->tp_alloc(type, 0);
1648 if (newobj == NULL) {
1649 Py_DECREF(tmp);
1650 return NULL;
1651 }
1652 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1653 Py_DECREF(tmp);
1654 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001655}
1656
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001657/*[clinic input]
1658float.__getnewargs__
1659[clinic start generated code]*/
1660
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001661static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001662float___getnewargs___impl(PyObject *self)
1663/*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001664{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001665 return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001666}
1667
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001668/* this is for the benefit of the pack/unpack routines below */
1669
1670typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001672} float_format_type;
1673
1674static float_format_type double_format, float_format;
1675static float_format_type detected_double_format, detected_float_format;
1676
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001677/*[clinic input]
1678@classmethod
1679float.__getformat__
1680
1681 typestr: str
1682 Must be 'double' or 'float'.
1683 /
1684
1685You probably don't want to use this function.
1686
1687It exists mainly to be used in Python's test suite.
1688
1689This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
1690little-endian' best describes the format of floating point numbers used by the
1691C type named by typestr.
1692[clinic start generated code]*/
1693
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001694static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001695float___getformat___impl(PyTypeObject *type, const char *typestr)
1696/*[clinic end generated code: output=2bfb987228cc9628 input=d5a52600f835ad67]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001699
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001700 if (strcmp(typestr, "double") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 r = double_format;
1702 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001703 else if (strcmp(typestr, "float") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 r = float_format;
1705 }
1706 else {
1707 PyErr_SetString(PyExc_ValueError,
1708 "__getformat__() argument 1 must be "
1709 "'double' or 'float'");
1710 return NULL;
1711 }
1712
1713 switch (r) {
1714 case unknown_format:
1715 return PyUnicode_FromString("unknown");
1716 case ieee_little_endian_format:
1717 return PyUnicode_FromString("IEEE, little-endian");
1718 case ieee_big_endian_format:
1719 return PyUnicode_FromString("IEEE, big-endian");
1720 default:
1721 Py_FatalError("insane float_format or double_format");
1722 return NULL;
1723 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001724}
1725
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001726/*[clinic input]
1727@classmethod
1728float.__set_format__
1729
1730 typestr: str
1731 Must be 'double' or 'float'.
1732 fmt: str
1733 Must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian',
1734 and in addition can only be one of the latter two if it appears to
1735 match the underlying C reality.
1736 /
1737
1738You probably don't want to use this function.
1739
1740It exists mainly to be used in Python's test suite.
1741
1742Override the automatic determination of C-level floating point type.
1743This affects how floats are converted to and from binary strings.
1744[clinic start generated code]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001745
1746static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001747float___set_format___impl(PyTypeObject *type, const char *typestr,
1748 const char *fmt)
1749/*[clinic end generated code: output=504460f5dc85acbd input=5306fa2b81a997e4]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 float_format_type f;
1752 float_format_type detected;
1753 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 if (strcmp(typestr, "double") == 0) {
1756 p = &double_format;
1757 detected = detected_double_format;
1758 }
1759 else if (strcmp(typestr, "float") == 0) {
1760 p = &float_format;
1761 detected = detected_float_format;
1762 }
1763 else {
1764 PyErr_SetString(PyExc_ValueError,
1765 "__setformat__() argument 1 must "
1766 "be 'double' or 'float'");
1767 return NULL;
1768 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001769
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001770 if (strcmp(fmt, "unknown") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 f = unknown_format;
1772 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001773 else if (strcmp(fmt, "IEEE, little-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 f = ieee_little_endian_format;
1775 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001776 else if (strcmp(fmt, "IEEE, big-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 f = ieee_big_endian_format;
1778 }
1779 else {
1780 PyErr_SetString(PyExc_ValueError,
1781 "__setformat__() argument 2 must be "
1782 "'unknown', 'IEEE, little-endian' or "
1783 "'IEEE, big-endian'");
1784 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 if (f != unknown_format && f != detected) {
1789 PyErr_Format(PyExc_ValueError,
1790 "can only set %s format to 'unknown' or the "
1791 "detected platform value", typestr);
1792 return NULL;
1793 }
1794
1795 *p = f;
1796 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001797}
1798
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001799static PyObject *
1800float_getreal(PyObject *v, void *closure)
1801{
1802 return float_float(v);
1803}
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001804
Guido van Rossumb43daf72007-08-01 18:08:08 +00001805static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001806float_getimag(PyObject *v, void *closure)
Guido van Rossumb43daf72007-08-01 18:08:08 +00001807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001809}
1810
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001811/*[clinic input]
1812float.__format__
1813
1814 format_spec: unicode
1815 /
1816
1817Formats the float according to format_spec.
1818[clinic start generated code]*/
1819
Eric Smith8c663262007-08-25 02:26:07 +00001820static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001821float___format___impl(PyObject *self, PyObject *format_spec)
1822/*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/
Eric Smith8c663262007-08-25 02:26:07 +00001823{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001824 _PyUnicodeWriter writer;
1825 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001826
Victor Stinner8f674cc2013-04-17 23:02:17 +02001827 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001828 ret = _PyFloat_FormatAdvancedWriter(
1829 &writer,
1830 self,
1831 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1832 if (ret == -1) {
1833 _PyUnicodeWriter_Dealloc(&writer);
1834 return NULL;
1835 }
1836 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001837}
1838
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001839static PyMethodDef float_methods[] = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001840 FLOAT_CONJUGATE_METHODDEF
1841 FLOAT___TRUNC___METHODDEF
1842 FLOAT___ROUND___METHODDEF
1843 FLOAT_AS_INTEGER_RATIO_METHODDEF
1844 FLOAT_FROMHEX_METHODDEF
1845 FLOAT_HEX_METHODDEF
1846 FLOAT_IS_INTEGER_METHODDEF
Christian Heimes53876d92008-04-19 00:31:39 +00001847#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001849 "Return True if the float is positive or negative infinite."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001851 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001853 "Return True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001854#endif
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001855 FLOAT___GETNEWARGS___METHODDEF
1856 FLOAT___GETFORMAT___METHODDEF
1857 FLOAT___SET_FORMAT___METHODDEF
1858 FLOAT___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001860};
1861
Guido van Rossumb43daf72007-08-01 18:08:08 +00001862static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 {"real",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001864 float_getreal, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001865 "the real part of a complex number",
1866 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 {"imag",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001868 float_getimag, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001869 "the imaginary part of a complex number",
1870 NULL},
1871 {NULL} /* Sentinel */
1872};
1873
Tim Peters6d6c1a32001-08-02 04:15:00 +00001874
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001875static PyNumberMethods float_as_number = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001876 float_add, /* nb_add */
1877 float_sub, /* nb_subtract */
1878 float_mul, /* nb_multiply */
1879 float_rem, /* nb_remainder */
1880 float_divmod, /* nb_divmod */
1881 float_pow, /* nb_power */
1882 (unaryfunc)float_neg, /* nb_negative */
1883 float_float, /* nb_positive */
1884 (unaryfunc)float_abs, /* nb_absolute */
1885 (inquiry)float_bool, /* nb_bool */
1886 0, /* nb_invert */
1887 0, /* nb_lshift */
1888 0, /* nb_rshift */
1889 0, /* nb_and */
1890 0, /* nb_xor */
1891 0, /* nb_or */
1892 float___trunc___impl, /* nb_int */
1893 0, /* nb_reserved */
1894 float_float, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 0, /* nb_inplace_add */
1896 0, /* nb_inplace_subtract */
1897 0, /* nb_inplace_multiply */
1898 0, /* nb_inplace_remainder */
1899 0, /* nb_inplace_power */
1900 0, /* nb_inplace_lshift */
1901 0, /* nb_inplace_rshift */
1902 0, /* nb_inplace_and */
1903 0, /* nb_inplace_xor */
1904 0, /* nb_inplace_or */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001905 float_floor_div, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 float_div, /* nb_true_divide */
1907 0, /* nb_inplace_floor_divide */
1908 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001909};
1910
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001911PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1913 "float",
1914 sizeof(PyFloatObject),
1915 0,
1916 (destructor)float_dealloc, /* tp_dealloc */
1917 0, /* tp_print */
1918 0, /* tp_getattr */
1919 0, /* tp_setattr */
1920 0, /* tp_reserved */
1921 (reprfunc)float_repr, /* tp_repr */
1922 &float_as_number, /* tp_as_number */
1923 0, /* tp_as_sequence */
1924 0, /* tp_as_mapping */
1925 (hashfunc)float_hash, /* tp_hash */
1926 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001927 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 PyObject_GenericGetAttr, /* tp_getattro */
1929 0, /* tp_setattro */
1930 0, /* tp_as_buffer */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001931 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001932 float_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 0, /* tp_traverse */
1934 0, /* tp_clear */
1935 float_richcompare, /* tp_richcompare */
1936 0, /* tp_weaklistoffset */
1937 0, /* tp_iter */
1938 0, /* tp_iternext */
1939 float_methods, /* tp_methods */
1940 0, /* tp_members */
1941 float_getset, /* tp_getset */
1942 0, /* tp_base */
1943 0, /* tp_dict */
1944 0, /* tp_descr_get */
1945 0, /* tp_descr_set */
1946 0, /* tp_dictoffset */
1947 0, /* tp_init */
1948 0, /* tp_alloc */
1949 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001950};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001951
Victor Stinner1c8f0592013-07-22 22:24:54 +02001952int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001953_PyFloat_Init(void)
1954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 /* We attempt to determine if this machine is using IEEE
1956 floating point formats by peering at the bits of some
1957 carefully chosen values. If it looks like we are on an
1958 IEEE platform, the float packing/unpacking routines can
1959 just copy bits, if not they resort to arithmetic & shifts
1960 and masks. The shifts & masks approach works on all finite
1961 values, but what happens to infinities, NaNs and signed
1962 zeroes on packing is an accident, and attempting to unpack
1963 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 Note that if we're on some whacked-out platform which uses
1966 IEEE formats but isn't strictly little-endian or big-
1967 endian, we will fall back to the portable shifts & masks
1968 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001969
1970#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 {
1972 double x = 9006104071832581.0;
1973 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1974 detected_double_format = ieee_big_endian_format;
1975 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1976 detected_double_format = ieee_little_endian_format;
1977 else
1978 detected_double_format = unknown_format;
1979 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001980#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001982#endif
1983
1984#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 {
1986 float y = 16711938.0;
1987 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1988 detected_float_format = ieee_big_endian_format;
1989 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1990 detected_float_format = ieee_little_endian_format;
1991 else
1992 detected_float_format = unknown_format;
1993 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001994#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001996#endif
1997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 double_format = detected_double_format;
1999 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002002 if (FloatInfoType.tp_name == NULL) {
2003 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0)
2004 return 0;
2005 }
2006 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002007}
2008
Georg Brandl2ee470f2008-07-16 12:55:28 +00002009int
2010PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002011{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002012 PyFloatObject *f = free_list, *next;
2013 int i = numfree;
2014 while (f) {
2015 next = (PyFloatObject*) Py_TYPE(f);
2016 PyObject_FREE(f);
2017 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002019 free_list = NULL;
2020 numfree = 0;
2021 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00002022}
2023
2024void
2025PyFloat_Fini(void)
2026{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002027 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002028}
Tim Peters9905b942003-03-20 20:53:32 +00002029
David Malcolm49526f42012-06-22 14:55:41 -04002030/* Print summary info about the state of the optimized allocator */
2031void
2032_PyFloat_DebugMallocStats(FILE *out)
2033{
2034 _PyDebugAllocatorStats(out,
2035 "free PyFloatObject",
2036 numfree, sizeof(PyFloatObject));
2037}
2038
2039
Tim Peters9905b942003-03-20 20:53:32 +00002040/*----------------------------------------------------------------------------
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002041 * _PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h.
2042 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
2043 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
2044 * We use:
2045 * bits = (unsigned short)f; Note the truncation
2046 * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
2047 * bits++;
2048 * }
Tim Peters9905b942003-03-20 20:53:32 +00002049 */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002050
2051int
2052_PyFloat_Pack2(double x, unsigned char *p, int le)
2053{
2054 unsigned char sign;
2055 int e;
2056 double f;
2057 unsigned short bits;
2058 int incr = 1;
2059
2060 if (x == 0.0) {
2061 sign = (copysign(1.0, x) == -1.0);
2062 e = 0;
2063 bits = 0;
2064 }
2065 else if (Py_IS_INFINITY(x)) {
2066 sign = (x < 0.0);
2067 e = 0x1f;
2068 bits = 0;
2069 }
2070 else if (Py_IS_NAN(x)) {
2071 /* There are 2046 distinct half-precision NaNs (1022 signaling and
2072 1024 quiet), but there are only two quiet NaNs that don't arise by
2073 quieting a signaling NaN; we get those by setting the topmost bit
2074 of the fraction field and clearing all other fraction bits. We
2075 choose the one with the appropriate sign. */
2076 sign = (copysign(1.0, x) == -1.0);
2077 e = 0x1f;
2078 bits = 512;
2079 }
2080 else {
2081 sign = (x < 0.0);
2082 if (sign) {
2083 x = -x;
2084 }
2085
2086 f = frexp(x, &e);
2087 if (f < 0.5 || f >= 1.0) {
2088 PyErr_SetString(PyExc_SystemError,
2089 "frexp() result out of range");
2090 return -1;
2091 }
2092
2093 /* Normalize f to be in the range [1.0, 2.0) */
2094 f *= 2.0;
2095 e--;
2096
2097 if (e >= 16) {
2098 goto Overflow;
2099 }
2100 else if (e < -25) {
2101 /* |x| < 2**-25. Underflow to zero. */
2102 f = 0.0;
2103 e = 0;
2104 }
2105 else if (e < -14) {
2106 /* |x| < 2**-14. Gradual underflow */
2107 f = ldexp(f, 14 + e);
2108 e = 0;
2109 }
2110 else /* if (!(e == 0 && f == 0.0)) */ {
2111 e += 15;
2112 f -= 1.0; /* Get rid of leading 1 */
2113 }
2114
2115 f *= 1024.0; /* 2**10 */
2116 /* Round to even */
2117 bits = (unsigned short)f; /* Note the truncation */
2118 assert(bits < 1024);
2119 assert(e < 31);
2120 if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2121 ++bits;
2122 if (bits == 1024) {
2123 /* The carry propagated out of a string of 10 1 bits. */
2124 bits = 0;
2125 ++e;
2126 if (e == 31)
2127 goto Overflow;
2128 }
2129 }
2130 }
2131
2132 bits |= (e << 10) | (sign << 15);
2133
2134 /* Write out result. */
2135 if (le) {
2136 p += 1;
2137 incr = -1;
2138 }
2139
2140 /* First byte */
2141 *p = (unsigned char)((bits >> 8) & 0xFF);
2142 p += incr;
2143
2144 /* Second byte */
2145 *p = (unsigned char)(bits & 0xFF);
2146
2147 return 0;
2148
2149 Overflow:
2150 PyErr_SetString(PyExc_OverflowError,
2151 "float too large to pack with e format");
2152 return -1;
2153}
2154
Tim Peters9905b942003-03-20 20:53:32 +00002155int
2156_PyFloat_Pack4(double x, unsigned char *p, int le)
2157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 if (float_format == unknown_format) {
2159 unsigned char sign;
2160 int e;
2161 double f;
2162 unsigned int fbits;
2163 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (le) {
2166 p += 3;
2167 incr = -1;
2168 }
Tim Peters9905b942003-03-20 20:53:32 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 if (x < 0) {
2171 sign = 1;
2172 x = -x;
2173 }
2174 else
2175 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 /* Normalize f to be in the range [1.0, 2.0) */
2180 if (0.5 <= f && f < 1.0) {
2181 f *= 2.0;
2182 e--;
2183 }
2184 else if (f == 0.0)
2185 e = 0;
2186 else {
2187 PyErr_SetString(PyExc_SystemError,
2188 "frexp() result out of range");
2189 return -1;
2190 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 if (e >= 128)
2193 goto Overflow;
2194 else if (e < -126) {
2195 /* Gradual underflow */
2196 f = ldexp(f, 126 + e);
2197 e = 0;
2198 }
2199 else if (!(e == 0 && f == 0.0)) {
2200 e += 127;
2201 f -= 1.0; /* Get rid of leading 1 */
2202 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 f *= 8388608.0; /* 2**23 */
2205 fbits = (unsigned int)(f + 0.5); /* Round */
2206 assert(fbits <= 8388608);
2207 if (fbits >> 23) {
2208 /* The carry propagated out of a string of 23 1 bits. */
2209 fbits = 0;
2210 ++e;
2211 if (e >= 255)
2212 goto Overflow;
2213 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 /* First byte */
2216 *p = (sign << 7) | (e >> 1);
2217 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 /* Second byte */
2220 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2221 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 /* Third byte */
2224 *p = (fbits >> 8) & 0xFF;
2225 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 /* Fourth byte */
2228 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 /* Done */
2231 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 }
2234 else {
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002235 float y = (float)x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002237
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002238 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002240
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002241 unsigned char s[sizeof(float)];
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002242 memcpy(s, &y, sizeof(float));
2243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 if ((float_format == ieee_little_endian_format && !le)
2245 || (float_format == ieee_big_endian_format && le)) {
2246 p += 3;
2247 incr = -1;
2248 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 for (i = 0; i < 4; i++) {
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002251 *p = s[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 p += incr;
2253 }
2254 return 0;
2255 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002256 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 PyErr_SetString(PyExc_OverflowError,
2258 "float too large to pack with f format");
2259 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002260}
2261
2262int
2263_PyFloat_Pack8(double x, unsigned char *p, int le)
2264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 if (double_format == unknown_format) {
2266 unsigned char sign;
2267 int e;
2268 double f;
2269 unsigned int fhi, flo;
2270 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 if (le) {
2273 p += 7;
2274 incr = -1;
2275 }
Tim Peters9905b942003-03-20 20:53:32 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 if (x < 0) {
2278 sign = 1;
2279 x = -x;
2280 }
2281 else
2282 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 /* Normalize f to be in the range [1.0, 2.0) */
2287 if (0.5 <= f && f < 1.0) {
2288 f *= 2.0;
2289 e--;
2290 }
2291 else if (f == 0.0)
2292 e = 0;
2293 else {
2294 PyErr_SetString(PyExc_SystemError,
2295 "frexp() result out of range");
2296 return -1;
2297 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 if (e >= 1024)
2300 goto Overflow;
2301 else if (e < -1022) {
2302 /* Gradual underflow */
2303 f = ldexp(f, 1022 + e);
2304 e = 0;
2305 }
2306 else if (!(e == 0 && f == 0.0)) {
2307 e += 1023;
2308 f -= 1.0; /* Get rid of leading 1 */
2309 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2312 f *= 268435456.0; /* 2**28 */
2313 fhi = (unsigned int)f; /* Truncate */
2314 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 f -= (double)fhi;
2317 f *= 16777216.0; /* 2**24 */
2318 flo = (unsigned int)(f + 0.5); /* Round */
2319 assert(flo <= 16777216);
2320 if (flo >> 24) {
2321 /* The carry propagated out of a string of 24 1 bits. */
2322 flo = 0;
2323 ++fhi;
2324 if (fhi >> 28) {
2325 /* And it also progagated out of the next 28 bits. */
2326 fhi = 0;
2327 ++e;
2328 if (e >= 2047)
2329 goto Overflow;
2330 }
2331 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 /* First byte */
2334 *p = (sign << 7) | (e >> 4);
2335 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 /* Second byte */
2338 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2339 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 /* Third byte */
2342 *p = (fhi >> 16) & 0xFF;
2343 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 /* Fourth byte */
2346 *p = (fhi >> 8) & 0xFF;
2347 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* Fifth byte */
2350 *p = fhi & 0xFF;
2351 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 /* Sixth byte */
2354 *p = (flo >> 16) & 0xFF;
2355 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 /* Seventh byte */
2358 *p = (flo >> 8) & 0xFF;
2359 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 /* Eighth byte */
2362 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002363 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 /* Done */
2366 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 Overflow:
2369 PyErr_SetString(PyExc_OverflowError,
2370 "float too large to pack with d format");
2371 return -1;
2372 }
2373 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002374 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 if ((double_format == ieee_little_endian_format && !le)
2378 || (double_format == ieee_big_endian_format && le)) {
2379 p += 7;
2380 incr = -1;
2381 }
2382
2383 for (i = 0; i < 8; i++) {
2384 *p = *s++;
2385 p += incr;
2386 }
2387 return 0;
2388 }
Tim Peters9905b942003-03-20 20:53:32 +00002389}
2390
2391double
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002392_PyFloat_Unpack2(const unsigned char *p, int le)
2393{
2394 unsigned char sign;
2395 int e;
2396 unsigned int f;
2397 double x;
2398 int incr = 1;
2399
2400 if (le) {
2401 p += 1;
2402 incr = -1;
2403 }
2404
2405 /* First byte */
2406 sign = (*p >> 7) & 1;
2407 e = (*p & 0x7C) >> 2;
2408 f = (*p & 0x03) << 8;
2409 p += incr;
2410
2411 /* Second byte */
2412 f |= *p;
2413
2414 if (e == 0x1f) {
2415#ifdef PY_NO_SHORT_FLOAT_REPR
2416 if (f == 0) {
2417 /* Infinity */
2418 return sign ? -Py_HUGE_VAL : Py_HUGE_VAL;
2419 }
2420 else {
2421 /* NaN */
2422#ifdef Py_NAN
2423 return sign ? -Py_NAN : Py_NAN;
2424#else
2425 PyErr_SetString(
2426 PyExc_ValueError,
2427 "can't unpack IEEE 754 NaN "
2428 "on platform that does not support NaNs");
2429 return -1;
2430#endif /* #ifdef Py_NAN */
2431 }
2432#else
2433 if (f == 0) {
2434 /* Infinity */
2435 return _Py_dg_infinity(sign);
2436 }
2437 else {
2438 /* NaN */
2439 return _Py_dg_stdnan(sign);
2440 }
2441#endif /* #ifdef PY_NO_SHORT_FLOAT_REPR */
2442 }
2443
2444 x = (double)f / 1024.0;
2445
2446 if (e == 0) {
2447 e = -14;
2448 }
2449 else {
2450 x += 1.0;
2451 e -= 15;
2452 }
2453 x = ldexp(x, e);
2454
2455 if (sign)
2456 x = -x;
2457
2458 return x;
2459}
2460
2461double
Tim Peters9905b942003-03-20 20:53:32 +00002462_PyFloat_Unpack4(const unsigned char *p, int le)
2463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 if (float_format == unknown_format) {
2465 unsigned char sign;
2466 int e;
2467 unsigned int f;
2468 double x;
2469 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 if (le) {
2472 p += 3;
2473 incr = -1;
2474 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 /* First byte */
2477 sign = (*p >> 7) & 1;
2478 e = (*p & 0x7F) << 1;
2479 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 /* Second byte */
2482 e |= (*p >> 7) & 1;
2483 f = (*p & 0x7F) << 16;
2484 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 if (e == 255) {
2487 PyErr_SetString(
2488 PyExc_ValueError,
2489 "can't unpack IEEE 754 special value "
2490 "on non-IEEE platform");
2491 return -1;
2492 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 /* Third byte */
2495 f |= *p << 8;
2496 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 /* Fourth byte */
2499 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 /* XXX This sadly ignores Inf/NaN issues */
2504 if (e == 0)
2505 e = -126;
2506 else {
2507 x += 1.0;
2508 e -= 127;
2509 }
2510 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 if (sign)
2513 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 return x;
2516 }
2517 else {
2518 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 if ((float_format == ieee_little_endian_format && !le)
2521 || (float_format == ieee_big_endian_format && le)) {
2522 char buf[4];
2523 char *d = &buf[3];
2524 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 for (i = 0; i < 4; i++) {
2527 *d-- = *p++;
2528 }
2529 memcpy(&x, buf, 4);
2530 }
2531 else {
2532 memcpy(&x, p, 4);
2533 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 return x;
2536 }
Tim Peters9905b942003-03-20 20:53:32 +00002537}
2538
2539double
2540_PyFloat_Unpack8(const unsigned char *p, int le)
2541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 if (double_format == unknown_format) {
2543 unsigned char sign;
2544 int e;
2545 unsigned int fhi, flo;
2546 double x;
2547 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 if (le) {
2550 p += 7;
2551 incr = -1;
2552 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 /* First byte */
2555 sign = (*p >> 7) & 1;
2556 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 /* Second byte */
2561 e |= (*p >> 4) & 0xF;
2562 fhi = (*p & 0xF) << 24;
2563 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 if (e == 2047) {
2566 PyErr_SetString(
2567 PyExc_ValueError,
2568 "can't unpack IEEE 754 special value "
2569 "on non-IEEE platform");
2570 return -1.0;
2571 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 /* Third byte */
2574 fhi |= *p << 16;
2575 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 /* Fourth byte */
2578 fhi |= *p << 8;
2579 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 /* Fifth byte */
2582 fhi |= *p;
2583 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 /* Sixth byte */
2586 flo = *p << 16;
2587 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 /* Seventh byte */
2590 flo |= *p << 8;
2591 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 /* Eighth byte */
2594 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2597 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 if (e == 0)
2600 e = -1022;
2601 else {
2602 x += 1.0;
2603 e -= 1023;
2604 }
2605 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 if (sign)
2608 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 return x;
2611 }
2612 else {
2613 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 if ((double_format == ieee_little_endian_format && !le)
2616 || (double_format == ieee_big_endian_format && le)) {
2617 char buf[8];
2618 char *d = &buf[7];
2619 int i;
2620
2621 for (i = 0; i < 8; i++) {
2622 *d-- = *p++;
2623 }
2624 memcpy(&x, buf, 8);
2625 }
2626 else {
2627 memcpy(&x, p, 8);
2628 }
2629
2630 return x;
2631 }
Tim Peters9905b942003-03-20 20:53:32 +00002632}