blob: 609f66f8b32ca93a3ec38bbf4e45b0069a55d5eb [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Float object implementation */
2
Guido van Rossum2a9096b1990-10-21 22:15:08 +00003/* XXX There should be overflow checks here, but it's hard to check
4 for any kind of float exception without losing portability. */
5
Guido van Rossumc0b618a1997-05-02 03:12:38 +00006#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007
Guido van Rossum3f5da241990-12-20 15:06:42 +00008#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +00009#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Serhiy Storchakab5c51d32017-03-11 09:21:05 +020011/*[clinic input]
12class float "PyObject *" "&PyFloat_Type"
13[clinic start generated code]*/
14/*[clinic end generated code: output=da39a3ee5e6b4b0d input=dd0003f68f144284]*/
15
16#include "clinic/floatobject.c.h"
Guido van Rossum6923e131990-11-02 17:50:43 +000017
Mark Dickinsond19052c2010-06-27 18:19:09 +000018/* Special free list
Mark Dickinsond19052c2010-06-27 18:19:09 +000019 free_list is a singly-linked list of available PyFloatObjects, linked
20 via abuse of their ob_type members.
21*/
22
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000023#ifndef PyFloat_MAXFREELIST
24#define PyFloat_MAXFREELIST 100
25#endif
26static int numfree = 0;
Guido van Rossum3fce8831999-03-12 19:43:17 +000027static PyFloatObject *free_list = NULL;
28
Christian Heimes93852662007-12-01 12:22:32 +000029double
30PyFloat_GetMax(void)
31{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000032 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000033}
34
35double
36PyFloat_GetMin(void)
37{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000038 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000039}
40
Christian Heimesd32ed6f2008-01-14 18:49:24 +000041static PyTypeObject FloatInfoType;
42
43PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000044"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000045\n\
Paul Ganssle2bb6bf02019-09-12 03:50:29 +010046A named tuple holding information about the float type. It contains low level\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000047information about the precision and internal representation. Please study\n\
48your system's :file:`float.h` for more information.");
49
50static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 {"max", "DBL_MAX -- maximum representable finite float"},
52 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
53 "is representable"},
54 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
55 "is representable"},
Stefano Taschini0301c9b2018-03-26 11:41:30 +020056 {"min", "DBL_MIN -- Minimum positive normalized float"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
58 "is a normalized float"},
59 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
60 "a normalized"},
61 {"dig", "DBL_DIG -- digits"},
62 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
63 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
64 "representable float"},
65 {"radix", "FLT_RADIX -- radix of exponent"},
Stefano Taschini0301c9b2018-03-26 11:41:30 +020066 {"rounds", "FLT_ROUNDS -- rounding mode"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +000068};
69
70static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 "sys.float_info", /* name */
72 floatinfo__doc__, /* doc */
73 floatinfo_fields, /* fields */
74 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +000075};
76
Christian Heimes93852662007-12-01 12:22:32 +000077PyObject *
78PyFloat_GetInfo(void)
79{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 PyObject* floatinfo;
81 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +000082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 floatinfo = PyStructSequence_New(&FloatInfoType);
84 if (floatinfo == NULL) {
85 return NULL;
86 }
Christian Heimes93852662007-12-01 12:22:32 +000087
Christian Heimesd32ed6f2008-01-14 18:49:24 +000088#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +000090#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +000092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 SetDblFlag(DBL_MAX);
94 SetIntFlag(DBL_MAX_EXP);
95 SetIntFlag(DBL_MAX_10_EXP);
96 SetDblFlag(DBL_MIN);
97 SetIntFlag(DBL_MIN_EXP);
98 SetIntFlag(DBL_MIN_10_EXP);
99 SetIntFlag(DBL_DIG);
100 SetIntFlag(DBL_MANT_DIG);
101 SetDblFlag(DBL_EPSILON);
102 SetIntFlag(FLT_RADIX);
103 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000104#undef SetIntFlag
105#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106
107 if (PyErr_Occurred()) {
108 Py_CLEAR(floatinfo);
109 return NULL;
110 }
111 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000112}
113
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000114PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000116{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200117 PyFloatObject *op = free_list;
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000118 if (op != NULL) {
119 free_list = (PyFloatObject *) Py_TYPE(op);
120 numfree--;
121 } else {
122 op = (PyFloatObject*) PyObject_MALLOC(sizeof(PyFloatObject));
123 if (!op)
124 return PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 }
126 /* Inline PyObject_New */
Victor Stinnerb509d522018-11-23 14:27:38 +0100127 (void)PyObject_INIT(op, &PyFloat_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 op->ob_fval = fval;
129 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130}
131
Brett Cannona721aba2016-09-09 14:57:09 -0700132static PyObject *
133float_from_string_inner(const char *s, Py_ssize_t len, void *obj)
134{
135 double x;
136 const char *end;
137 const char *last = s + len;
138 /* strip space */
139 while (s < last && Py_ISSPACE(*s)) {
140 s++;
141 }
142
143 while (s < last - 1 && Py_ISSPACE(last[-1])) {
144 last--;
145 }
146
147 /* We don't care about overflow or underflow. If the platform
148 * supports them, infinities and signed zeroes (on underflow) are
149 * fine. */
150 x = PyOS_string_to_double(s, (char **)&end, NULL);
151 if (end != last) {
152 PyErr_Format(PyExc_ValueError,
153 "could not convert string to float: "
154 "%R", obj);
155 return NULL;
156 }
157 else if (x == -1.0 && PyErr_Occurred()) {
158 return NULL;
159 }
160 else {
161 return PyFloat_FromDouble(x);
162 }
163}
164
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000165PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000166PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000167{
Brett Cannona721aba2016-09-09 14:57:09 -0700168 const char *s;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000169 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 Py_ssize_t len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200171 Py_buffer view = {NULL, NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200175 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000177 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200178 assert(PyUnicode_IS_ASCII(s_buffer));
179 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200180 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200181 assert(s != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000183 else if (PyBytes_Check(v)) {
184 s = PyBytes_AS_STRING(v);
185 len = PyBytes_GET_SIZE(v);
186 }
187 else if (PyByteArray_Check(v)) {
188 s = PyByteArray_AS_STRING(v);
189 len = PyByteArray_GET_SIZE(v);
190 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200191 else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
192 s = (const char *)view.buf;
193 len = view.len;
Martin Pantereeb896c2015-11-07 02:32:21 +0000194 /* Copy to NUL-terminated buffer. */
195 s_buffer = PyBytes_FromStringAndSize(s, len);
196 if (s_buffer == NULL) {
197 PyBuffer_Release(&view);
198 return NULL;
199 }
200 s = PyBytes_AS_STRING(s_buffer);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200201 }
202 else {
Ezio Melottia5b95992013-11-07 19:18:34 +0200203 PyErr_Format(PyExc_TypeError,
204 "float() argument must be a string or a number, not '%.200s'",
205 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 return NULL;
207 }
Brett Cannona721aba2016-09-09 14:57:09 -0700208 result = _Py_string_to_number_with_underscores(s, len, "float", v, v,
209 float_from_string_inner);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200210 PyBuffer_Release(&view);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000211 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000213}
214
Guido van Rossum234f9421993-06-17 12:35:49 +0000215static void
Fred Drakefd99de62000-07-09 05:02:18 +0000216float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 if (PyFloat_CheckExact(op)) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000219 if (numfree >= PyFloat_MAXFREELIST) {
220 PyObject_FREE(op);
221 return;
222 }
223 numfree++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 Py_TYPE(op) = (struct _typeobject *)free_list;
225 free_list = op;
226 }
227 else
228 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000229}
230
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000231double
Fred Drakefd99de62000-07-09 05:02:18 +0000232PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 PyNumberMethods *nb;
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300235 PyObject *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 if (op == NULL) {
239 PyErr_BadArgument();
240 return -1;
241 }
Tim Petersd2364e82001-11-01 20:09:42 +0000242
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300243 if (PyFloat_Check(op)) {
244 return PyFloat_AS_DOUBLE(op);
245 }
246
247 nb = Py_TYPE(op)->tp_as_number;
248 if (nb == NULL || nb->nb_float == NULL) {
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300249 if (nb && nb->nb_index) {
250 PyObject *res = PyNumber_Index(op);
251 if (!res) {
252 return -1;
253 }
254 double val = PyLong_AsDouble(res);
255 Py_DECREF(res);
256 return val;
257 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300258 PyErr_Format(PyExc_TypeError, "must be real number, not %.50s",
259 op->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 return -1;
261 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000262
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300263 res = (*nb->nb_float) (op);
264 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 return -1;
266 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300267 if (!PyFloat_CheckExact(res)) {
268 if (!PyFloat_Check(res)) {
269 PyErr_Format(PyExc_TypeError,
270 "%.50s.__float__ returned non-float (type %.50s)",
271 op->ob_type->tp_name, res->ob_type->tp_name);
272 Py_DECREF(res);
273 return -1;
274 }
275 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
276 "%.50s.__float__ returned non-float (type %.50s). "
277 "The ability to return an instance of a strict subclass of float "
278 "is deprecated, and may be removed in a future version of Python.",
279 op->ob_type->tp_name, res->ob_type->tp_name)) {
280 Py_DECREF(res);
281 return -1;
282 }
283 }
Tim Petersd2364e82001-11-01 20:09:42 +0000284
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300285 val = PyFloat_AS_DOUBLE(res);
286 Py_DECREF(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000288}
289
Neil Schemenauer32117e52001-01-04 01:44:34 +0000290/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000291 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000292 set to NULL, and the function invoking this macro returns NULL. If
Serhiy Storchaka95949422013-08-27 19:40:23 +0300293 obj is not of float or int type, Py_NotImplemented is incref'ed,
Tim Peters77d8a4f2001-12-11 20:31:34 +0000294 stored in obj, and returned from the function invoking this macro.
295*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296#define CONVERT_TO_DOUBLE(obj, dbl) \
297 if (PyFloat_Check(obj)) \
298 dbl = PyFloat_AS_DOUBLE(obj); \
299 else if (convert_to_double(&(obj), &(dbl)) < 0) \
300 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000301
Eric Smith0923d1d2009-04-16 20:16:10 +0000302/* Methods */
303
Neil Schemenauer32117e52001-01-04 01:44:34 +0000304static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000305convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000306{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200307 PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (PyLong_Check(obj)) {
310 *dbl = PyLong_AsDouble(obj);
311 if (*dbl == -1.0 && PyErr_Occurred()) {
312 *v = NULL;
313 return -1;
314 }
315 }
316 else {
317 Py_INCREF(Py_NotImplemented);
318 *v = Py_NotImplemented;
319 return -1;
320 }
321 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000322}
323
Eric Smith0923d1d2009-04-16 20:16:10 +0000324static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000325float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000326{
327 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200328 char *buf;
329
330 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
331 'r', 0,
332 Py_DTSF_ADD_DOT_0,
333 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000334 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000335 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200336 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000337 PyMem_Free(buf);
338 return result;
339}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000340
Tim Peters307fa782004-09-23 08:06:40 +0000341/* Comparison is pretty much a nightmare. When comparing float to float,
342 * we do it as straightforwardly (and long-windedly) as conceivable, so
343 * that, e.g., Python x == y delivers the same result as the platform
344 * C x == y when x and/or y is a NaN.
345 * When mixing float with an integer type, there's no good *uniform* approach.
346 * Converting the double to an integer obviously doesn't work, since we
347 * may lose info from fractional bits. Converting the integer to a double
Serhiy Storchaka95949422013-08-27 19:40:23 +0300348 * also has two failure modes: (1) an int may trigger overflow (too
Tim Peters307fa782004-09-23 08:06:40 +0000349 * 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 +0200350 * 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 +0000351 * 63 bits of precision, but a C double probably has only 53), and then
352 * we can falsely claim equality when low-order integer bits are lost by
353 * coercion to double. So this part is painful too.
354 */
355
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000356static PyObject*
357float_richcompare(PyObject *v, PyObject *w, int op)
358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 double i, j;
360 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 assert(PyFloat_Check(v));
363 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 /* Switch on the type of w. Set i and j to doubles to be compared,
366 * and op to the richcomp to use.
367 */
368 if (PyFloat_Check(w))
369 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 else if (!Py_IS_FINITE(i)) {
372 if (PyLong_Check(w))
373 /* If i is an infinity, its magnitude exceeds any
374 * finite integer, so it doesn't matter which int we
375 * compare i with. If i is a NaN, similarly.
376 */
377 j = 0.0;
378 else
379 goto Unimplemented;
380 }
Tim Peters307fa782004-09-23 08:06:40 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 else if (PyLong_Check(w)) {
383 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
384 int wsign = _PyLong_Sign(w);
385 size_t nbits;
386 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 if (vsign != wsign) {
389 /* Magnitudes are irrelevant -- the signs alone
390 * determine the outcome.
391 */
392 i = (double)vsign;
393 j = (double)wsign;
394 goto Compare;
395 }
396 /* The signs are the same. */
397 /* Convert w to a double if it fits. In particular, 0 fits. */
398 nbits = _PyLong_NumBits(w);
399 if (nbits == (size_t)-1 && PyErr_Occurred()) {
400 /* This long is so large that size_t isn't big enough
401 * to hold the # of bits. Replace with little doubles
402 * that give the same outcome -- w is so large that
403 * its magnitude must exceed the magnitude of any
404 * finite float.
405 */
406 PyErr_Clear();
407 i = (double)vsign;
408 assert(wsign != 0);
409 j = wsign * 2.0;
410 goto Compare;
411 }
412 if (nbits <= 48) {
413 j = PyLong_AsDouble(w);
414 /* It's impossible that <= 48 bits overflowed. */
415 assert(j != -1.0 || ! PyErr_Occurred());
416 goto Compare;
417 }
418 assert(wsign != 0); /* else nbits was 0 */
419 assert(vsign != 0); /* if vsign were 0, then since wsign is
420 * not 0, we would have taken the
421 * vsign != wsign branch at the start */
422 /* We want to work with non-negative numbers. */
423 if (vsign < 0) {
424 /* "Multiply both sides" by -1; this also swaps the
425 * comparator.
426 */
427 i = -i;
428 op = _Py_SwappedOp[op];
429 }
430 assert(i > 0.0);
431 (void) frexp(i, &exponent);
432 /* exponent is the # of bits in v before the radix point;
433 * we know that nbits (the # of bits in w) > 48 at this point
434 */
435 if (exponent < 0 || (size_t)exponent < nbits) {
436 i = 1.0;
437 j = 2.0;
438 goto Compare;
439 }
440 if ((size_t)exponent > nbits) {
441 i = 2.0;
442 j = 1.0;
443 goto Compare;
444 }
445 /* v and w have the same number of bits before the radix
Serhiy Storchaka95949422013-08-27 19:40:23 +0300446 * point. Construct two ints that have the same comparison
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 * outcome.
448 */
449 {
450 double fracpart;
451 double intpart;
452 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 PyObject *vv = NULL;
454 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 if (wsign < 0) {
457 ww = PyNumber_Negative(w);
458 if (ww == NULL)
459 goto Error;
460 }
461 else
462 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 fracpart = modf(i, &intpart);
465 vv = PyLong_FromDouble(intpart);
466 if (vv == NULL)
467 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 if (fracpart != 0.0) {
470 /* Shift left, and or a 1 bit into vv
471 * to represent the lost fraction.
472 */
473 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000474
Serhiy Storchakaa5119e72019-05-19 14:14:38 +0300475 temp = _PyLong_Lshift(ww, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 if (temp == NULL)
477 goto Error;
478 Py_DECREF(ww);
479 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000480
Serhiy Storchakaa5119e72019-05-19 14:14:38 +0300481 temp = _PyLong_Lshift(vv, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (temp == NULL)
483 goto Error;
484 Py_DECREF(vv);
485 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000486
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300487 temp = PyNumber_Or(vv, _PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (temp == NULL)
489 goto Error;
490 Py_DECREF(vv);
491 vv = temp;
492 }
Tim Peters307fa782004-09-23 08:06:40 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 r = PyObject_RichCompareBool(vv, ww, op);
495 if (r < 0)
496 goto Error;
497 result = PyBool_FromLong(r);
498 Error:
499 Py_XDECREF(vv);
500 Py_XDECREF(ww);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 return result;
502 }
503 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000504
Serhiy Storchaka95949422013-08-27 19:40:23 +0300505 else /* w isn't float or int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000507
508 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 PyFPE_START_PROTECT("richcompare", return NULL)
510 switch (op) {
511 case Py_EQ:
512 r = i == j;
513 break;
514 case Py_NE:
515 r = i != j;
516 break;
517 case Py_LE:
518 r = i <= j;
519 break;
520 case Py_GE:
521 r = i >= j;
522 break;
523 case Py_LT:
524 r = i < j;
525 break;
526 case Py_GT:
527 r = i > j;
528 break;
529 }
530 PyFPE_END_PROTECT(r)
531 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000532
533 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500534 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000535}
536
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000537static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000538float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000541}
542
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000543static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000544float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 double a,b;
547 CONVERT_TO_DOUBLE(v, a);
548 CONVERT_TO_DOUBLE(w, b);
549 PyFPE_START_PROTECT("add", return 0)
550 a = a + b;
551 PyFPE_END_PROTECT(a)
552 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000553}
554
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000555static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000556float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 double a,b;
559 CONVERT_TO_DOUBLE(v, a);
560 CONVERT_TO_DOUBLE(w, b);
561 PyFPE_START_PROTECT("subtract", return 0)
562 a = a - b;
563 PyFPE_END_PROTECT(a)
564 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000565}
566
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000567static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000568float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 double a,b;
571 CONVERT_TO_DOUBLE(v, a);
572 CONVERT_TO_DOUBLE(w, b);
573 PyFPE_START_PROTECT("multiply", return 0)
574 a = a * b;
575 PyFPE_END_PROTECT(a)
576 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000577}
578
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000579static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000580float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 double a,b;
583 CONVERT_TO_DOUBLE(v, a);
584 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 if (b == 0.0) {
586 PyErr_SetString(PyExc_ZeroDivisionError,
587 "float division by zero");
588 return NULL;
589 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 PyFPE_START_PROTECT("divide", return 0)
591 a = a / b;
592 PyFPE_END_PROTECT(a)
593 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000594}
595
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000596static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000597float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 double vx, wx;
600 double mod;
601 CONVERT_TO_DOUBLE(v, vx);
602 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 if (wx == 0.0) {
604 PyErr_SetString(PyExc_ZeroDivisionError,
605 "float modulo");
606 return NULL;
607 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 PyFPE_START_PROTECT("modulo", return 0)
609 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000610 if (mod) {
611 /* ensure the remainder has the same sign as the denominator */
612 if ((wx < 0) != (mod < 0)) {
613 mod += wx;
614 }
615 }
616 else {
617 /* the remainder is zero, and in the presence of signed zeroes
618 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000619 it has the same sign as the denominator. */
620 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 }
622 PyFPE_END_PROTECT(mod)
623 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000624}
625
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000626static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000627float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 double vx, wx;
630 double div, mod, floordiv;
631 CONVERT_TO_DOUBLE(v, vx);
632 CONVERT_TO_DOUBLE(w, wx);
633 if (wx == 0.0) {
634 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
635 return NULL;
636 }
637 PyFPE_START_PROTECT("divmod", return 0)
638 mod = fmod(vx, wx);
639 /* fmod is typically exact, so vx-mod is *mathematically* an
640 exact multiple of wx. But this is fp arithmetic, and fp
641 vx - mod is an approximation; the result is that div may
642 not be an exact integral value after the division, although
643 it will always be very close to one.
644 */
645 div = (vx - mod) / wx;
646 if (mod) {
647 /* ensure the remainder has the same sign as the denominator */
648 if ((wx < 0) != (mod < 0)) {
649 mod += wx;
650 div -= 1.0;
651 }
652 }
653 else {
654 /* the remainder is zero, and in the presence of signed zeroes
655 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000656 it has the same sign as the denominator. */
657 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 }
659 /* snap quotient to nearest integral value */
660 if (div) {
661 floordiv = floor(div);
662 if (div - floordiv > 0.5)
663 floordiv += 1.0;
664 }
665 else {
666 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000667 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 }
669 PyFPE_END_PROTECT(floordiv)
670 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000671}
672
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000673static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000674float_floor_div(PyObject *v, PyObject *w)
675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 t = float_divmod(v, w);
679 if (t == NULL || t == Py_NotImplemented)
680 return t;
681 assert(PyTuple_CheckExact(t));
682 r = PyTuple_GET_ITEM(t, 0);
683 Py_INCREF(r);
684 Py_DECREF(t);
685 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000686}
687
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000688/* determine whether x is an odd integer or not; assumes that
689 x is not an infinity or nan. */
690#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
691
Tim Peters63a35712001-12-11 19:57:24 +0000692static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000693float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 double iv, iw, ix;
696 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 if ((PyObject *)z != Py_None) {
699 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
700 "allowed unless all arguments are integers");
701 return NULL;
702 }
Tim Peters32f453e2001-09-03 08:35:41 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 CONVERT_TO_DOUBLE(v, iv);
705 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 /* Sort out special cases here instead of relying on pow() */
708 if (iw == 0) { /* v**0 is 1, even 0**0 */
709 return PyFloat_FromDouble(1.0);
710 }
711 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
712 return PyFloat_FromDouble(iv);
713 }
714 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
715 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
716 }
717 if (Py_IS_INFINITY(iw)) {
718 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
719 * abs(v) > 1 (including case where v infinite)
720 *
721 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
722 * abs(v) > 1 (including case where v infinite)
723 */
724 iv = fabs(iv);
725 if (iv == 1.0)
726 return PyFloat_FromDouble(1.0);
727 else if ((iw > 0.0) == (iv > 1.0))
728 return PyFloat_FromDouble(fabs(iw)); /* return inf */
729 else
730 return PyFloat_FromDouble(0.0);
731 }
732 if (Py_IS_INFINITY(iv)) {
733 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
734 * both cases, we need to add the appropriate sign if w is
735 * an odd integer.
736 */
737 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
738 if (iw > 0.0)
739 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
740 else
741 return PyFloat_FromDouble(iw_is_odd ?
742 copysign(0.0, iv) : 0.0);
743 }
744 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
745 (already dealt with above), and an error
746 if w is negative. */
747 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
748 if (iw < 0.0) {
749 PyErr_SetString(PyExc_ZeroDivisionError,
750 "0.0 cannot be raised to a "
751 "negative power");
752 return NULL;
753 }
754 /* use correct sign if iw is odd */
755 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
756 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 if (iv < 0.0) {
759 /* Whether this is an error is a mess, and bumps into libm
760 * bugs so we have to figure it out ourselves.
761 */
762 if (iw != floor(iw)) {
763 /* Negative numbers raised to fractional powers
764 * become complex.
765 */
766 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
767 }
768 /* iw is an exact integer, albeit perhaps a very large
769 * one. Replace iv by its absolute value and remember
770 * to negate the pow result if iw is odd.
771 */
772 iv = -iv;
773 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
774 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
777 /* (-1) ** large_integer also ends up here. Here's an
778 * extract from the comments for the previous
779 * implementation explaining why this special case is
780 * necessary:
781 *
782 * -1 raised to an exact integer should never be exceptional.
783 * Alas, some libms (chiefly glibc as of early 2003) return
784 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
785 * happen to be representable in a *C* integer. That's a
786 * bug.
787 */
788 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
789 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 /* Now iv and iw are finite, iw is nonzero, and iv is
792 * positive and not equal to 1.0. We finally allow
793 * the platform pow to step in and do the rest.
794 */
795 errno = 0;
796 PyFPE_START_PROTECT("pow", return NULL)
797 ix = pow(iv, iw);
798 PyFPE_END_PROTECT(ix)
799 Py_ADJUST_ERANGE1(ix);
800 if (negate_result)
801 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 if (errno != 0) {
804 /* We don't expect any errno value other than ERANGE, but
805 * the range of libm bugs appears unbounded.
806 */
807 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
808 PyExc_ValueError);
809 return NULL;
810 }
811 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000812}
813
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000814#undef DOUBLE_IS_ODD_INTEGER
815
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000816static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000817float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000820}
821
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000822static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000823float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000826}
827
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000828static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000829float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000832}
833
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200834/*[clinic input]
835float.is_integer
836
837Return True if the float is an integer.
838[clinic start generated code]*/
839
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000840static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200841float_is_integer_impl(PyObject *self)
842/*[clinic end generated code: output=7112acf95a4d31ea input=311810d3f777e10d]*/
Christian Heimes53876d92008-04-19 00:31:39 +0000843{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200844 double x = PyFloat_AsDouble(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 PyObject *o;
846
847 if (x == -1.0 && PyErr_Occurred())
848 return NULL;
849 if (!Py_IS_FINITE(x))
850 Py_RETURN_FALSE;
851 errno = 0;
852 PyFPE_START_PROTECT("is_integer", return NULL)
853 o = (floor(x) == x) ? Py_True : Py_False;
854 PyFPE_END_PROTECT(x)
855 if (errno != 0) {
856 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
857 PyExc_ValueError);
858 return NULL;
859 }
860 Py_INCREF(o);
861 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000862}
863
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200864/*[clinic input]
865float.__trunc__
866
867Return the Integral closest to x between 0 and x.
868[clinic start generated code]*/
869
Christian Heimes53876d92008-04-19 00:31:39 +0000870static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200871float___trunc___impl(PyObject *self)
872/*[clinic end generated code: output=dd3e289dd4c6b538 input=591b9ba0d650fdff]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000873{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200874 double x = PyFloat_AsDouble(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 (void)modf(x, &wholepart);
878 /* Try to get out cheap if this fits in a Python int. The attempt
879 * to cast to long must be protected, as C doesn't define what
880 * happens if the double is too big to fit in a long. Some rare
881 * systems raise an exception then (RISCOS was mentioned as one,
882 * and someone using a non-default option on Sun also bumped into
883 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
884 * still be vulnerable: if a long has more bits of precision than
885 * a double, casting MIN/MAX to double may yield an approximation,
886 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
887 * yield true from the C expression wholepart<=LONG_MAX, despite
888 * that wholepart is actually greater than LONG_MAX.
889 */
890 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
891 const long aslong = (long)wholepart;
892 return PyLong_FromLong(aslong);
893 }
894 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000895}
896
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000897/* double_round: rounds a finite double to the closest multiple of
898 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
899 ndigits <= 323). Returns a Python float, or sets a Python error and
900 returns NULL on failure (OverflowError and memory errors are possible). */
901
902#ifndef PY_NO_SHORT_FLOAT_REPR
903/* version of double_round that uses the correctly-rounded string<->double
904 conversions from Python/dtoa.c */
905
906static PyObject *
907double_round(double x, int ndigits) {
908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 double rounded;
910 Py_ssize_t buflen, mybuflen=100;
911 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
912 int decpt, sign;
913 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000914 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000917 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000919 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 if (buf == NULL) {
921 PyErr_NoMemory();
922 return NULL;
923 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
926 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
927 buflen = buf_end - buf;
928 if (buflen + 8 > mybuflen) {
929 mybuflen = buflen+8;
930 mybuf = (char *)PyMem_Malloc(mybuflen);
931 if (mybuf == NULL) {
932 PyErr_NoMemory();
933 goto exit;
934 }
935 }
936 /* copy buf to mybuf, adding exponent, sign and leading 0 */
937 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
938 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 /* and convert the resulting string back to a double */
941 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000942 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000944 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 if (errno == ERANGE && fabs(rounded) >= 1.)
946 PyErr_SetString(PyExc_OverflowError,
947 "rounded value too large to represent");
948 else
949 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 /* done computing value; now clean up */
952 if (mybuf != shortbuf)
953 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000954 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 _Py_dg_freedtoa(buf);
956 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000957}
958
959#else /* PY_NO_SHORT_FLOAT_REPR */
960
961/* fallback version, to be used when correctly rounded binary<->decimal
962 conversions aren't available */
963
964static PyObject *
965double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 double pow1, pow2, y, z;
967 if (ndigits >= 0) {
968 if (ndigits > 22) {
969 /* pow1 and pow2 are each safe from overflow, but
970 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
971 pow1 = pow(10.0, (double)(ndigits-22));
972 pow2 = 1e22;
973 }
974 else {
975 pow1 = pow(10.0, (double)ndigits);
976 pow2 = 1.0;
977 }
978 y = (x*pow1)*pow2;
979 /* if y overflows, then rounded value is exactly x */
980 if (!Py_IS_FINITE(y))
981 return PyFloat_FromDouble(x);
982 }
983 else {
984 pow1 = pow(10.0, (double)-ndigits);
985 pow2 = 1.0; /* unused; silences a gcc compiler warning */
986 y = x / pow1;
987 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 z = round(y);
990 if (fabs(y-z) == 0.5)
991 /* halfway between two integers; use round-half-even */
992 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 if (ndigits >= 0)
995 z = (z / pow2) / pow1;
996 else
997 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 /* if computation resulted in overflow, raise OverflowError */
1000 if (!Py_IS_FINITE(z)) {
1001 PyErr_SetString(PyExc_OverflowError,
1002 "overflow occurred during round");
1003 return NULL;
1004 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001007}
1008
1009#endif /* PY_NO_SHORT_FLOAT_REPR */
1010
1011/* round a Python float v to the closest multiple of 10**-ndigits */
1012
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001013/*[clinic input]
1014float.__round__
1015
Serhiy Storchakad322abb2019-09-14 13:31:50 +03001016 ndigits as o_ndigits: object = None
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001017 /
1018
1019Return the Integral closest to x, rounding half toward even.
1020
1021When an argument is passed, work like built-in round(x, ndigits).
1022[clinic start generated code]*/
1023
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001024static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001025float___round___impl(PyObject *self, PyObject *o_ndigits)
Serhiy Storchakad322abb2019-09-14 13:31:50 +03001026/*[clinic end generated code: output=374c36aaa0f13980 input=fc0fe25924fbc9ed]*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 double x, rounded;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001030
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001031 x = PyFloat_AsDouble(self);
Serhiy Storchakad322abb2019-09-14 13:31:50 +03001032 if (o_ndigits == Py_None) {
Steve Dowercb39d1f2015-04-15 16:10:59 -04001033 /* single-argument round or with None ndigits:
1034 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 rounded = round(x);
1036 if (fabs(x-rounded) == 0.5)
1037 /* halfway case: round to even */
1038 rounded = 2.0*round(x/2.0);
1039 return PyLong_FromDouble(rounded);
1040 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 /* interpret second argument as a Py_ssize_t; clips on overflow */
1043 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1044 if (ndigits == -1 && PyErr_Occurred())
1045 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 /* nans and infinities round to themselves */
1048 if (!Py_IS_FINITE(x))
1049 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1052 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1053 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001054#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1055#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 if (ndigits > NDIGITS_MAX)
1057 /* return x */
1058 return PyFloat_FromDouble(x);
1059 else if (ndigits < NDIGITS_MIN)
1060 /* return 0.0, but with sign of x */
1061 return PyFloat_FromDouble(0.0*x);
1062 else
1063 /* finite x, and ndigits is not unreasonably large */
1064 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001065#undef NDIGITS_MAX
1066#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001067}
1068
1069static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001070float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 if (PyFloat_CheckExact(v))
1073 Py_INCREF(v);
1074 else
1075 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1076 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001077}
1078
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001079/*[clinic input]
1080float.conjugate
1081
1082Return self, the complex conjugate of any float.
1083[clinic start generated code]*/
1084
1085static PyObject *
1086float_conjugate_impl(PyObject *self)
1087/*[clinic end generated code: output=8ca292c2479194af input=82ba6f37a9ff91dd]*/
1088{
1089 return float_float(self);
1090}
1091
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001092/* turn ASCII hex characters into integer values and vice versa */
1093
1094static char
1095char_from_hex(int x)
1096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001098 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001099}
1100
1101static int
1102hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 int x;
1104 switch(c) {
1105 case '0':
1106 x = 0;
1107 break;
1108 case '1':
1109 x = 1;
1110 break;
1111 case '2':
1112 x = 2;
1113 break;
1114 case '3':
1115 x = 3;
1116 break;
1117 case '4':
1118 x = 4;
1119 break;
1120 case '5':
1121 x = 5;
1122 break;
1123 case '6':
1124 x = 6;
1125 break;
1126 case '7':
1127 x = 7;
1128 break;
1129 case '8':
1130 x = 8;
1131 break;
1132 case '9':
1133 x = 9;
1134 break;
1135 case 'a':
1136 case 'A':
1137 x = 10;
1138 break;
1139 case 'b':
1140 case 'B':
1141 x = 11;
1142 break;
1143 case 'c':
1144 case 'C':
1145 x = 12;
1146 break;
1147 case 'd':
1148 case 'D':
1149 x = 13;
1150 break;
1151 case 'e':
1152 case 'E':
1153 x = 14;
1154 break;
1155 case 'f':
1156 case 'F':
1157 x = 15;
1158 break;
1159 default:
1160 x = -1;
1161 break;
1162 }
1163 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001164}
1165
1166/* convert a float to a hexadecimal string */
1167
1168/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1169 of the form 4k+1. */
1170#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1171
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001172/*[clinic input]
1173float.hex
1174
1175Return a hexadecimal representation of a floating-point number.
1176
1177>>> (-0.1).hex()
1178'-0x1.999999999999ap-4'
1179>>> 3.14159.hex()
1180'0x1.921f9f01b866ep+1'
1181[clinic start generated code]*/
1182
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001183static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001184float_hex_impl(PyObject *self)
1185/*[clinic end generated code: output=0ebc9836e4d302d4 input=bec1271a33d47e67]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 double x, m;
1188 int e, shift, i, si, esign;
1189 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1190 trailing NUL byte. */
1191 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001192
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001193 CONVERT_TO_DOUBLE(self, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001196 return float_repr((PyFloatObject *)self);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001199 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 return PyUnicode_FromString("-0x0.0p+0");
1201 else
1202 return PyUnicode_FromString("0x0.0p+0");
1203 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001206 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 m = ldexp(m, shift);
1208 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 si = 0;
1211 s[si] = char_from_hex((int)m);
1212 si++;
1213 m -= (int)m;
1214 s[si] = '.';
1215 si++;
1216 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1217 m *= 16.0;
1218 s[si] = char_from_hex((int)m);
1219 si++;
1220 m -= (int)m;
1221 }
1222 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 if (e < 0) {
1225 esign = (int)'-';
1226 e = -e;
1227 }
1228 else
1229 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 if (x < 0.0)
1232 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1233 else
1234 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001235}
1236
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001237/* Convert a hexadecimal string to a float. */
1238
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001239/*[clinic input]
1240@classmethod
1241float.fromhex
1242
1243 string: object
1244 /
1245
1246Create a floating-point number from a hexadecimal string.
1247
1248>>> float.fromhex('0x1.ffffp10')
12492047.984375
1250>>> float.fromhex('-0x1p-1074')
1251-5e-324
1252[clinic start generated code]*/
1253
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001254static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001255float_fromhex(PyTypeObject *type, PyObject *string)
1256/*[clinic end generated code: output=46c0274d22b78e82 input=0407bebd354bca89]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001257{
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001258 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 double x;
1260 long exp, top_exp, lsb, key_digit;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001261 const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 int half_eps, digit, round_up, negate=0;
1263 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 /*
1266 * For the sake of simplicity and correctness, we impose an artificial
1267 * limit on ndigits, the total number of hex digits in the coefficient
1268 * The limit is chosen to ensure that, writing exp for the exponent,
1269 *
1270 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1271 * guaranteed to overflow (provided it's nonzero)
1272 *
1273 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1274 * guaranteed to underflow to 0.
1275 *
1276 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1277 * overflow in the calculation of exp and top_exp below.
1278 *
1279 * More specifically, ndigits is assumed to satisfy the following
1280 * inequalities:
1281 *
1282 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1283 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1284 *
1285 * If either of these inequalities is not satisfied, a ValueError is
1286 * raised. Otherwise, write x for the value of the hex string, and
1287 * assume x is nonzero. Then
1288 *
1289 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1290 *
1291 * Now if exp > LONG_MAX/2 then:
1292 *
1293 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1294 * = DBL_MAX_EXP
1295 *
1296 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1297 * double, so overflows. If exp < LONG_MIN/2, then
1298 *
1299 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1300 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1301 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1302 *
1303 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1304 * when converted to a C double.
1305 *
1306 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1307 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1308 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001309
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001310 s = PyUnicode_AsUTF8AndSize(string, &length);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 if (s == NULL)
1312 return NULL;
1313 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 /********************
1316 * Parse the string *
1317 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 /* leading whitespace */
1320 while (Py_ISSPACE(*s))
1321 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 /* infinities and nans */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001324 x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 if (coeff_end != s) {
1326 s = coeff_end;
1327 goto finished;
1328 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 /* optional sign */
1331 if (*s == '-') {
1332 s++;
1333 negate = 1;
1334 }
1335 else if (*s == '+')
1336 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 /* [0x] */
1339 s_store = s;
1340 if (*s == '0') {
1341 s++;
1342 if (*s == 'x' || *s == 'X')
1343 s++;
1344 else
1345 s = s_store;
1346 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 /* coefficient: <integer> [. <fraction>] */
1349 coeff_start = s;
1350 while (hex_from_char(*s) >= 0)
1351 s++;
1352 s_store = s;
1353 if (*s == '.') {
1354 s++;
1355 while (hex_from_char(*s) >= 0)
1356 s++;
1357 coeff_end = s-1;
1358 }
1359 else
1360 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 /* ndigits = total # of hex digits; fdigits = # after point */
1363 ndigits = coeff_end - coeff_start;
1364 fdigits = coeff_end - s_store;
1365 if (ndigits == 0)
1366 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001367 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1368 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 /* [p <exponent>] */
1372 if (*s == 'p' || *s == 'P') {
1373 s++;
1374 exp_start = s;
1375 if (*s == '-' || *s == '+')
1376 s++;
1377 if (!('0' <= *s && *s <= '9'))
1378 goto parse_error;
1379 s++;
1380 while ('0' <= *s && *s <= '9')
1381 s++;
1382 exp = strtol(exp_start, NULL, 10);
1383 }
1384 else
1385 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001386
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001387/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1389 coeff_end-(j) : \
1390 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 /*******************************************
1393 * Compute rounded value of the hex string *
1394 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 /* Discard leading zeros, and catch extreme overflow and underflow */
1397 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1398 ndigits--;
1399 if (ndigits == 0 || exp < LONG_MIN/2) {
1400 x = 0.0;
1401 goto finished;
1402 }
1403 if (exp > LONG_MAX/2)
1404 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 /* Adjust exponent for fractional part. */
1407 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1410 top_exp = exp + 4*((long)ndigits - 1);
1411 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1412 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 /* catch almost all nonextreme cases of overflow and underflow here */
1415 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1416 x = 0.0;
1417 goto finished;
1418 }
1419 if (top_exp > DBL_MAX_EXP)
1420 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 /* lsb = exponent of least significant bit of the *rounded* value.
1423 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001424 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 x = 0.0;
1427 if (exp >= lsb) {
1428 /* no rounding required */
1429 for (i = ndigits-1; i >= 0; i--)
1430 x = 16.0*x + HEX_DIGIT(i);
1431 x = ldexp(x, (int)(exp));
1432 goto finished;
1433 }
1434 /* rounding required. key_digit is the index of the hex digit
1435 containing the first bit to be rounded away. */
1436 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1437 key_digit = (lsb - exp - 1) / 4;
1438 for (i = ndigits-1; i > key_digit; i--)
1439 x = 16.0*x + HEX_DIGIT(i);
1440 digit = HEX_DIGIT(key_digit);
1441 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1444 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1445 if ((digit & half_eps) != 0) {
1446 round_up = 0;
1447 if ((digit & (3*half_eps-1)) != 0 ||
1448 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1449 round_up = 1;
1450 else
1451 for (i = key_digit-1; i >= 0; i--)
1452 if (HEX_DIGIT(i) != 0) {
1453 round_up = 1;
1454 break;
1455 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001456 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 x += 2*half_eps;
1458 if (top_exp == DBL_MAX_EXP &&
1459 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1460 /* overflow corner case: pre-rounded value <
1461 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1462 goto overflow_error;
1463 }
1464 }
1465 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001466
1467 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 /* optional trailing whitespace leading to the end of the string */
1469 while (Py_ISSPACE(*s))
1470 s++;
1471 if (s != s_end)
1472 goto parse_error;
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001473 result = PyFloat_FromDouble(negate ? -x : x);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001474 if (type != &PyFloat_Type && result != NULL) {
1475 Py_SETREF(result, PyObject_CallFunctionObjArgs((PyObject *)type, result, NULL));
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001476 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001478
1479 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 PyErr_SetString(PyExc_OverflowError,
1481 "hexadecimal value too large to represent as a float");
1482 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001483
1484 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 PyErr_SetString(PyExc_ValueError,
1486 "invalid hexadecimal floating-point string");
1487 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001488
1489 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 PyErr_SetString(PyExc_ValueError,
1491 "hexadecimal string too long to convert");
1492 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001493}
1494
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001495/*[clinic input]
1496float.as_integer_ratio
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001497
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001498Return integer ratio.
1499
1500Return a pair of integers, whose ratio is exactly equal to the original float
1501and with a positive denominator.
1502
1503Raise OverflowError on infinities and a ValueError on NaNs.
1504
1505>>> (10.0).as_integer_ratio()
1506(10, 1)
1507>>> (0.0).as_integer_ratio()
1508(0, 1)
1509>>> (-.25).as_integer_ratio()
1510(-1, 4)
1511[clinic start generated code]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001512
Christian Heimes26855632008-01-27 23:50:43 +00001513static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001514float_as_integer_ratio_impl(PyObject *self)
1515/*[clinic end generated code: output=65f25f0d8d30a712 input=e21d08b4630c2e44]*/
Christian Heimes26855632008-01-27 23:50:43 +00001516{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001517 double self_double;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 double float_part;
1519 int exponent;
1520 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 PyObject *py_exponent = NULL;
1523 PyObject *numerator = NULL;
1524 PyObject *denominator = NULL;
1525 PyObject *result_pair = NULL;
1526 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001527
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001528 CONVERT_TO_DOUBLE(self, self_double);
Christian Heimes26855632008-01-27 23:50:43 +00001529
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001530 if (Py_IS_INFINITY(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001531 PyErr_SetString(PyExc_OverflowError,
1532 "cannot convert Infinity to integer ratio");
1533 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001535 if (Py_IS_NAN(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001536 PyErr_SetString(PyExc_ValueError,
1537 "cannot convert NaN to integer ratio");
1538 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 }
Christian Heimes26855632008-01-27 23:50:43 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001542 float_part = frexp(self_double, &exponent); /* self_double == float_part * 2**exponent exactly */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1546 float_part *= 2.0;
1547 exponent--;
1548 }
1549 /* self == float_part * 2**exponent exactly and float_part is integral.
1550 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1551 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 numerator = PyLong_FromDouble(float_part);
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001554 if (numerator == NULL)
1555 goto error;
1556 denominator = PyLong_FromLong(1);
1557 if (denominator == NULL)
1558 goto error;
1559 py_exponent = PyLong_FromLong(Py_ABS(exponent));
1560 if (py_exponent == NULL)
1561 goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 /* fold in 2**exponent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 if (exponent > 0) {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001565 Py_SETREF(numerator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001566 long_methods->nb_lshift(numerator, py_exponent));
1567 if (numerator == NULL)
1568 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 }
1570 else {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001571 Py_SETREF(denominator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001572 long_methods->nb_lshift(denominator, py_exponent));
1573 if (denominator == NULL)
1574 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 }
1576
1577 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001578
Christian Heimes26855632008-01-27 23:50:43 +00001579error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 Py_XDECREF(py_exponent);
1581 Py_XDECREF(denominator);
1582 Py_XDECREF(numerator);
1583 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001584}
1585
Jeremy Hylton938ace62002-07-17 16:30:39 +00001586static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001587float_subtype_new(PyTypeObject *type, PyObject *x);
1588
1589/*[clinic input]
1590@classmethod
1591float.__new__ as float_new
Serhiy Storchakaba85d692017-03-30 09:09:41 +03001592 x: object(c_default="_PyLong_Zero") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001593 /
1594
1595Convert a string or number to a floating point number, if possible.
1596[clinic start generated code]*/
Guido van Rossumbef14172001-08-29 15:47:46 +00001597
Tim Peters6d6c1a32001-08-02 04:15:00 +00001598static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001599float_new_impl(PyTypeObject *type, PyObject *x)
Serhiy Storchakabae68812017-04-05 12:00:42 +03001600/*[clinic end generated code: output=ccf1e8dc460ba6ba input=540ee77c204ff87a]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00001601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 if (type != &PyFloat_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001603 return float_subtype_new(type, x); /* Wimp out */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 /* If it's a string, but not a string subclass, use
1605 PyFloat_FromString. */
1606 if (PyUnicode_CheckExact(x))
1607 return PyFloat_FromString(x);
1608 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001609}
1610
Guido van Rossumbef14172001-08-29 15:47:46 +00001611/* Wimpy, slow approach to tp_new calls for subtypes of float:
1612 first create a regular float from whatever arguments we got,
1613 then allocate a subtype instance and initialize its ob_fval
1614 from the regular float. The regular float is then thrown away.
1615*/
1616static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001617float_subtype_new(PyTypeObject *type, PyObject *x)
Guido van Rossumbef14172001-08-29 15:47:46 +00001618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 assert(PyType_IsSubtype(type, &PyFloat_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001622 tmp = float_new_impl(&PyFloat_Type, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (tmp == NULL)
1624 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001625 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 newobj = type->tp_alloc(type, 0);
1627 if (newobj == NULL) {
1628 Py_DECREF(tmp);
1629 return NULL;
1630 }
1631 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1632 Py_DECREF(tmp);
1633 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001634}
1635
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001636/*[clinic input]
1637float.__getnewargs__
1638[clinic start generated code]*/
1639
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001640static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001641float___getnewargs___impl(PyObject *self)
1642/*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001643{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001644 return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001645}
1646
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001647/* this is for the benefit of the pack/unpack routines below */
1648
1649typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001651} float_format_type;
1652
1653static float_format_type double_format, float_format;
1654static float_format_type detected_double_format, detected_float_format;
1655
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001656/*[clinic input]
1657@classmethod
1658float.__getformat__
1659
1660 typestr: str
1661 Must be 'double' or 'float'.
1662 /
1663
1664You probably don't want to use this function.
1665
1666It exists mainly to be used in Python's test suite.
1667
1668This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
1669little-endian' best describes the format of floating point numbers used by the
1670C type named by typestr.
1671[clinic start generated code]*/
1672
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001673static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001674float___getformat___impl(PyTypeObject *type, const char *typestr)
1675/*[clinic end generated code: output=2bfb987228cc9628 input=d5a52600f835ad67]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001678
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001679 if (strcmp(typestr, "double") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 r = double_format;
1681 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001682 else if (strcmp(typestr, "float") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 r = float_format;
1684 }
1685 else {
1686 PyErr_SetString(PyExc_ValueError,
1687 "__getformat__() argument 1 must be "
1688 "'double' or 'float'");
1689 return NULL;
1690 }
1691
1692 switch (r) {
1693 case unknown_format:
1694 return PyUnicode_FromString("unknown");
1695 case ieee_little_endian_format:
1696 return PyUnicode_FromString("IEEE, little-endian");
1697 case ieee_big_endian_format:
1698 return PyUnicode_FromString("IEEE, big-endian");
1699 default:
1700 Py_FatalError("insane float_format or double_format");
1701 return NULL;
1702 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001703}
1704
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001705/*[clinic input]
1706@classmethod
1707float.__set_format__
1708
1709 typestr: str
1710 Must be 'double' or 'float'.
1711 fmt: str
1712 Must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian',
1713 and in addition can only be one of the latter two if it appears to
1714 match the underlying C reality.
1715 /
1716
1717You probably don't want to use this function.
1718
1719It exists mainly to be used in Python's test suite.
1720
1721Override the automatic determination of C-level floating point type.
1722This affects how floats are converted to and from binary strings.
1723[clinic start generated code]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001724
1725static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001726float___set_format___impl(PyTypeObject *type, const char *typestr,
1727 const char *fmt)
1728/*[clinic end generated code: output=504460f5dc85acbd input=5306fa2b81a997e4]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 float_format_type f;
1731 float_format_type detected;
1732 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 if (strcmp(typestr, "double") == 0) {
1735 p = &double_format;
1736 detected = detected_double_format;
1737 }
1738 else if (strcmp(typestr, "float") == 0) {
1739 p = &float_format;
1740 detected = detected_float_format;
1741 }
1742 else {
1743 PyErr_SetString(PyExc_ValueError,
1744 "__setformat__() argument 1 must "
1745 "be 'double' or 'float'");
1746 return NULL;
1747 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001748
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001749 if (strcmp(fmt, "unknown") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 f = unknown_format;
1751 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001752 else if (strcmp(fmt, "IEEE, little-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 f = ieee_little_endian_format;
1754 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001755 else if (strcmp(fmt, "IEEE, big-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 f = ieee_big_endian_format;
1757 }
1758 else {
1759 PyErr_SetString(PyExc_ValueError,
1760 "__setformat__() argument 2 must be "
1761 "'unknown', 'IEEE, little-endian' or "
1762 "'IEEE, big-endian'");
1763 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 if (f != unknown_format && f != detected) {
1768 PyErr_Format(PyExc_ValueError,
1769 "can only set %s format to 'unknown' or the "
1770 "detected platform value", typestr);
1771 return NULL;
1772 }
1773
1774 *p = f;
1775 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001776}
1777
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001778static PyObject *
1779float_getreal(PyObject *v, void *closure)
1780{
1781 return float_float(v);
1782}
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001783
Guido van Rossumb43daf72007-08-01 18:08:08 +00001784static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001785float_getimag(PyObject *v, void *closure)
Guido van Rossumb43daf72007-08-01 18:08:08 +00001786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001788}
1789
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001790/*[clinic input]
1791float.__format__
1792
1793 format_spec: unicode
1794 /
1795
1796Formats the float according to format_spec.
1797[clinic start generated code]*/
1798
Eric Smith8c663262007-08-25 02:26:07 +00001799static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001800float___format___impl(PyObject *self, PyObject *format_spec)
1801/*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/
Eric Smith8c663262007-08-25 02:26:07 +00001802{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001803 _PyUnicodeWriter writer;
1804 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001805
Victor Stinner8f674cc2013-04-17 23:02:17 +02001806 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001807 ret = _PyFloat_FormatAdvancedWriter(
1808 &writer,
1809 self,
1810 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1811 if (ret == -1) {
1812 _PyUnicodeWriter_Dealloc(&writer);
1813 return NULL;
1814 }
1815 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001816}
1817
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001818static PyMethodDef float_methods[] = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001819 FLOAT_CONJUGATE_METHODDEF
1820 FLOAT___TRUNC___METHODDEF
1821 FLOAT___ROUND___METHODDEF
1822 FLOAT_AS_INTEGER_RATIO_METHODDEF
1823 FLOAT_FROMHEX_METHODDEF
1824 FLOAT_HEX_METHODDEF
1825 FLOAT_IS_INTEGER_METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001826 FLOAT___GETNEWARGS___METHODDEF
1827 FLOAT___GETFORMAT___METHODDEF
1828 FLOAT___SET_FORMAT___METHODDEF
1829 FLOAT___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001831};
1832
Guido van Rossumb43daf72007-08-01 18:08:08 +00001833static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 {"real",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001835 float_getreal, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001836 "the real part of a complex number",
1837 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 {"imag",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001839 float_getimag, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001840 "the imaginary part of a complex number",
1841 NULL},
1842 {NULL} /* Sentinel */
1843};
1844
Tim Peters6d6c1a32001-08-02 04:15:00 +00001845
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001846static PyNumberMethods float_as_number = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001847 float_add, /* nb_add */
1848 float_sub, /* nb_subtract */
1849 float_mul, /* nb_multiply */
1850 float_rem, /* nb_remainder */
1851 float_divmod, /* nb_divmod */
1852 float_pow, /* nb_power */
1853 (unaryfunc)float_neg, /* nb_negative */
1854 float_float, /* nb_positive */
1855 (unaryfunc)float_abs, /* nb_absolute */
1856 (inquiry)float_bool, /* nb_bool */
1857 0, /* nb_invert */
1858 0, /* nb_lshift */
1859 0, /* nb_rshift */
1860 0, /* nb_and */
1861 0, /* nb_xor */
1862 0, /* nb_or */
1863 float___trunc___impl, /* nb_int */
1864 0, /* nb_reserved */
1865 float_float, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 0, /* nb_inplace_add */
1867 0, /* nb_inplace_subtract */
1868 0, /* nb_inplace_multiply */
1869 0, /* nb_inplace_remainder */
1870 0, /* nb_inplace_power */
1871 0, /* nb_inplace_lshift */
1872 0, /* nb_inplace_rshift */
1873 0, /* nb_inplace_and */
1874 0, /* nb_inplace_xor */
1875 0, /* nb_inplace_or */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001876 float_floor_div, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 float_div, /* nb_true_divide */
1878 0, /* nb_inplace_floor_divide */
1879 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001880};
1881
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001882PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1884 "float",
1885 sizeof(PyFloatObject),
1886 0,
1887 (destructor)float_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001888 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 0, /* tp_getattr */
1890 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001891 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 (reprfunc)float_repr, /* tp_repr */
1893 &float_as_number, /* tp_as_number */
1894 0, /* tp_as_sequence */
1895 0, /* tp_as_mapping */
1896 (hashfunc)float_hash, /* tp_hash */
1897 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001898 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 PyObject_GenericGetAttr, /* tp_getattro */
1900 0, /* tp_setattro */
1901 0, /* tp_as_buffer */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001902 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001903 float_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 0, /* tp_traverse */
1905 0, /* tp_clear */
1906 float_richcompare, /* tp_richcompare */
1907 0, /* tp_weaklistoffset */
1908 0, /* tp_iter */
1909 0, /* tp_iternext */
1910 float_methods, /* tp_methods */
1911 0, /* tp_members */
1912 float_getset, /* tp_getset */
1913 0, /* tp_base */
1914 0, /* tp_dict */
1915 0, /* tp_descr_get */
1916 0, /* tp_descr_set */
1917 0, /* tp_dictoffset */
1918 0, /* tp_init */
1919 0, /* tp_alloc */
1920 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001921};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001922
Victor Stinner1c8f0592013-07-22 22:24:54 +02001923int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001924_PyFloat_Init(void)
1925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 /* We attempt to determine if this machine is using IEEE
1927 floating point formats by peering at the bits of some
1928 carefully chosen values. If it looks like we are on an
1929 IEEE platform, the float packing/unpacking routines can
1930 just copy bits, if not they resort to arithmetic & shifts
1931 and masks. The shifts & masks approach works on all finite
1932 values, but what happens to infinities, NaNs and signed
1933 zeroes on packing is an accident, and attempting to unpack
1934 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 Note that if we're on some whacked-out platform which uses
1937 IEEE formats but isn't strictly little-endian or big-
1938 endian, we will fall back to the portable shifts & masks
1939 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001940
1941#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 {
1943 double x = 9006104071832581.0;
1944 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1945 detected_double_format = ieee_big_endian_format;
1946 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1947 detected_double_format = ieee_little_endian_format;
1948 else
1949 detected_double_format = unknown_format;
1950 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001951#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001953#endif
1954
1955#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 {
1957 float y = 16711938.0;
1958 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1959 detected_float_format = ieee_big_endian_format;
1960 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1961 detected_float_format = ieee_little_endian_format;
1962 else
1963 detected_float_format = unknown_format;
1964 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001965#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001967#endif
1968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 double_format = detected_double_format;
1970 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001973 if (FloatInfoType.tp_name == NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001974 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001975 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001976 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02001977 }
1978 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001979}
1980
Georg Brandl2ee470f2008-07-16 12:55:28 +00001981int
1982PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001983{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001984 PyFloatObject *f = free_list, *next;
1985 int i = numfree;
1986 while (f) {
1987 next = (PyFloatObject*) Py_TYPE(f);
1988 PyObject_FREE(f);
1989 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001991 free_list = NULL;
1992 numfree = 0;
1993 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001994}
1995
1996void
1997PyFloat_Fini(void)
1998{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001999 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002000}
Tim Peters9905b942003-03-20 20:53:32 +00002001
David Malcolm49526f42012-06-22 14:55:41 -04002002/* Print summary info about the state of the optimized allocator */
2003void
2004_PyFloat_DebugMallocStats(FILE *out)
2005{
2006 _PyDebugAllocatorStats(out,
2007 "free PyFloatObject",
2008 numfree, sizeof(PyFloatObject));
2009}
2010
2011
Tim Peters9905b942003-03-20 20:53:32 +00002012/*----------------------------------------------------------------------------
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002013 * _PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h.
2014 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
2015 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
2016 * We use:
2017 * bits = (unsigned short)f; Note the truncation
2018 * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
2019 * bits++;
2020 * }
Tim Peters9905b942003-03-20 20:53:32 +00002021 */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002022
2023int
2024_PyFloat_Pack2(double x, unsigned char *p, int le)
2025{
2026 unsigned char sign;
2027 int e;
2028 double f;
2029 unsigned short bits;
2030 int incr = 1;
2031
2032 if (x == 0.0) {
2033 sign = (copysign(1.0, x) == -1.0);
2034 e = 0;
2035 bits = 0;
2036 }
2037 else if (Py_IS_INFINITY(x)) {
2038 sign = (x < 0.0);
2039 e = 0x1f;
2040 bits = 0;
2041 }
2042 else if (Py_IS_NAN(x)) {
2043 /* There are 2046 distinct half-precision NaNs (1022 signaling and
2044 1024 quiet), but there are only two quiet NaNs that don't arise by
2045 quieting a signaling NaN; we get those by setting the topmost bit
2046 of the fraction field and clearing all other fraction bits. We
2047 choose the one with the appropriate sign. */
2048 sign = (copysign(1.0, x) == -1.0);
2049 e = 0x1f;
2050 bits = 512;
2051 }
2052 else {
2053 sign = (x < 0.0);
2054 if (sign) {
2055 x = -x;
2056 }
2057
2058 f = frexp(x, &e);
2059 if (f < 0.5 || f >= 1.0) {
2060 PyErr_SetString(PyExc_SystemError,
2061 "frexp() result out of range");
2062 return -1;
2063 }
2064
2065 /* Normalize f to be in the range [1.0, 2.0) */
2066 f *= 2.0;
2067 e--;
2068
2069 if (e >= 16) {
2070 goto Overflow;
2071 }
2072 else if (e < -25) {
2073 /* |x| < 2**-25. Underflow to zero. */
2074 f = 0.0;
2075 e = 0;
2076 }
2077 else if (e < -14) {
2078 /* |x| < 2**-14. Gradual underflow */
2079 f = ldexp(f, 14 + e);
2080 e = 0;
2081 }
2082 else /* if (!(e == 0 && f == 0.0)) */ {
2083 e += 15;
2084 f -= 1.0; /* Get rid of leading 1 */
2085 }
2086
2087 f *= 1024.0; /* 2**10 */
2088 /* Round to even */
2089 bits = (unsigned short)f; /* Note the truncation */
2090 assert(bits < 1024);
2091 assert(e < 31);
2092 if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2093 ++bits;
2094 if (bits == 1024) {
2095 /* The carry propagated out of a string of 10 1 bits. */
2096 bits = 0;
2097 ++e;
2098 if (e == 31)
2099 goto Overflow;
2100 }
2101 }
2102 }
2103
2104 bits |= (e << 10) | (sign << 15);
2105
2106 /* Write out result. */
2107 if (le) {
2108 p += 1;
2109 incr = -1;
2110 }
2111
2112 /* First byte */
2113 *p = (unsigned char)((bits >> 8) & 0xFF);
2114 p += incr;
2115
2116 /* Second byte */
2117 *p = (unsigned char)(bits & 0xFF);
2118
2119 return 0;
2120
2121 Overflow:
2122 PyErr_SetString(PyExc_OverflowError,
2123 "float too large to pack with e format");
2124 return -1;
2125}
2126
Tim Peters9905b942003-03-20 20:53:32 +00002127int
2128_PyFloat_Pack4(double x, unsigned char *p, int le)
2129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 if (float_format == unknown_format) {
2131 unsigned char sign;
2132 int e;
2133 double f;
2134 unsigned int fbits;
2135 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 if (le) {
2138 p += 3;
2139 incr = -1;
2140 }
Tim Peters9905b942003-03-20 20:53:32 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 if (x < 0) {
2143 sign = 1;
2144 x = -x;
2145 }
2146 else
2147 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 /* Normalize f to be in the range [1.0, 2.0) */
2152 if (0.5 <= f && f < 1.0) {
2153 f *= 2.0;
2154 e--;
2155 }
2156 else if (f == 0.0)
2157 e = 0;
2158 else {
2159 PyErr_SetString(PyExc_SystemError,
2160 "frexp() result out of range");
2161 return -1;
2162 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (e >= 128)
2165 goto Overflow;
2166 else if (e < -126) {
2167 /* Gradual underflow */
2168 f = ldexp(f, 126 + e);
2169 e = 0;
2170 }
2171 else if (!(e == 0 && f == 0.0)) {
2172 e += 127;
2173 f -= 1.0; /* Get rid of leading 1 */
2174 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 f *= 8388608.0; /* 2**23 */
2177 fbits = (unsigned int)(f + 0.5); /* Round */
2178 assert(fbits <= 8388608);
2179 if (fbits >> 23) {
2180 /* The carry propagated out of a string of 23 1 bits. */
2181 fbits = 0;
2182 ++e;
2183 if (e >= 255)
2184 goto Overflow;
2185 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 /* First byte */
2188 *p = (sign << 7) | (e >> 1);
2189 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 /* Second byte */
2192 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2193 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 /* Third byte */
2196 *p = (fbits >> 8) & 0xFF;
2197 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 /* Fourth byte */
2200 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 /* Done */
2203 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 }
2206 else {
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002207 float y = (float)x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002209
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002210 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002212
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002213 unsigned char s[sizeof(float)];
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002214 memcpy(s, &y, sizeof(float));
2215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 if ((float_format == ieee_little_endian_format && !le)
2217 || (float_format == ieee_big_endian_format && le)) {
2218 p += 3;
2219 incr = -1;
2220 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 for (i = 0; i < 4; i++) {
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002223 *p = s[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 p += incr;
2225 }
2226 return 0;
2227 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002228 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 PyErr_SetString(PyExc_OverflowError,
2230 "float too large to pack with f format");
2231 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002232}
2233
2234int
2235_PyFloat_Pack8(double x, unsigned char *p, int le)
2236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 if (double_format == unknown_format) {
2238 unsigned char sign;
2239 int e;
2240 double f;
2241 unsigned int fhi, flo;
2242 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 if (le) {
2245 p += 7;
2246 incr = -1;
2247 }
Tim Peters9905b942003-03-20 20:53:32 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 if (x < 0) {
2250 sign = 1;
2251 x = -x;
2252 }
2253 else
2254 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 /* Normalize f to be in the range [1.0, 2.0) */
2259 if (0.5 <= f && f < 1.0) {
2260 f *= 2.0;
2261 e--;
2262 }
2263 else if (f == 0.0)
2264 e = 0;
2265 else {
2266 PyErr_SetString(PyExc_SystemError,
2267 "frexp() result out of range");
2268 return -1;
2269 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 if (e >= 1024)
2272 goto Overflow;
2273 else if (e < -1022) {
2274 /* Gradual underflow */
2275 f = ldexp(f, 1022 + e);
2276 e = 0;
2277 }
2278 else if (!(e == 0 && f == 0.0)) {
2279 e += 1023;
2280 f -= 1.0; /* Get rid of leading 1 */
2281 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2284 f *= 268435456.0; /* 2**28 */
2285 fhi = (unsigned int)f; /* Truncate */
2286 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 f -= (double)fhi;
2289 f *= 16777216.0; /* 2**24 */
2290 flo = (unsigned int)(f + 0.5); /* Round */
2291 assert(flo <= 16777216);
2292 if (flo >> 24) {
2293 /* The carry propagated out of a string of 24 1 bits. */
2294 flo = 0;
2295 ++fhi;
2296 if (fhi >> 28) {
2297 /* And it also progagated out of the next 28 bits. */
2298 fhi = 0;
2299 ++e;
2300 if (e >= 2047)
2301 goto Overflow;
2302 }
2303 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 /* First byte */
2306 *p = (sign << 7) | (e >> 4);
2307 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 /* Second byte */
2310 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2311 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* Third byte */
2314 *p = (fhi >> 16) & 0xFF;
2315 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 /* Fourth byte */
2318 *p = (fhi >> 8) & 0xFF;
2319 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 /* Fifth byte */
2322 *p = fhi & 0xFF;
2323 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 /* Sixth byte */
2326 *p = (flo >> 16) & 0xFF;
2327 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 /* Seventh byte */
2330 *p = (flo >> 8) & 0xFF;
2331 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 /* Eighth byte */
2334 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002335 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 /* Done */
2338 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 Overflow:
2341 PyErr_SetString(PyExc_OverflowError,
2342 "float too large to pack with d format");
2343 return -1;
2344 }
2345 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002346 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 if ((double_format == ieee_little_endian_format && !le)
2350 || (double_format == ieee_big_endian_format && le)) {
2351 p += 7;
2352 incr = -1;
2353 }
2354
2355 for (i = 0; i < 8; i++) {
2356 *p = *s++;
2357 p += incr;
2358 }
2359 return 0;
2360 }
Tim Peters9905b942003-03-20 20:53:32 +00002361}
2362
2363double
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002364_PyFloat_Unpack2(const unsigned char *p, int le)
2365{
2366 unsigned char sign;
2367 int e;
2368 unsigned int f;
2369 double x;
2370 int incr = 1;
2371
2372 if (le) {
2373 p += 1;
2374 incr = -1;
2375 }
2376
2377 /* First byte */
2378 sign = (*p >> 7) & 1;
2379 e = (*p & 0x7C) >> 2;
2380 f = (*p & 0x03) << 8;
2381 p += incr;
2382
2383 /* Second byte */
2384 f |= *p;
2385
2386 if (e == 0x1f) {
2387#ifdef PY_NO_SHORT_FLOAT_REPR
2388 if (f == 0) {
2389 /* Infinity */
2390 return sign ? -Py_HUGE_VAL : Py_HUGE_VAL;
2391 }
2392 else {
2393 /* NaN */
2394#ifdef Py_NAN
2395 return sign ? -Py_NAN : Py_NAN;
2396#else
2397 PyErr_SetString(
2398 PyExc_ValueError,
2399 "can't unpack IEEE 754 NaN "
2400 "on platform that does not support NaNs");
2401 return -1;
2402#endif /* #ifdef Py_NAN */
2403 }
2404#else
2405 if (f == 0) {
2406 /* Infinity */
2407 return _Py_dg_infinity(sign);
2408 }
2409 else {
2410 /* NaN */
2411 return _Py_dg_stdnan(sign);
2412 }
2413#endif /* #ifdef PY_NO_SHORT_FLOAT_REPR */
2414 }
2415
2416 x = (double)f / 1024.0;
2417
2418 if (e == 0) {
2419 e = -14;
2420 }
2421 else {
2422 x += 1.0;
2423 e -= 15;
2424 }
2425 x = ldexp(x, e);
2426
2427 if (sign)
2428 x = -x;
2429
2430 return x;
2431}
2432
2433double
Tim Peters9905b942003-03-20 20:53:32 +00002434_PyFloat_Unpack4(const unsigned char *p, int le)
2435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 if (float_format == unknown_format) {
2437 unsigned char sign;
2438 int e;
2439 unsigned int f;
2440 double x;
2441 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 if (le) {
2444 p += 3;
2445 incr = -1;
2446 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 /* First byte */
2449 sign = (*p >> 7) & 1;
2450 e = (*p & 0x7F) << 1;
2451 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 /* Second byte */
2454 e |= (*p >> 7) & 1;
2455 f = (*p & 0x7F) << 16;
2456 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 if (e == 255) {
2459 PyErr_SetString(
2460 PyExc_ValueError,
2461 "can't unpack IEEE 754 special value "
2462 "on non-IEEE platform");
2463 return -1;
2464 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 /* Third byte */
2467 f |= *p << 8;
2468 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 /* Fourth byte */
2471 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 /* XXX This sadly ignores Inf/NaN issues */
2476 if (e == 0)
2477 e = -126;
2478 else {
2479 x += 1.0;
2480 e -= 127;
2481 }
2482 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 if (sign)
2485 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 return x;
2488 }
2489 else {
2490 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 if ((float_format == ieee_little_endian_format && !le)
2493 || (float_format == ieee_big_endian_format && le)) {
2494 char buf[4];
2495 char *d = &buf[3];
2496 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 for (i = 0; i < 4; i++) {
2499 *d-- = *p++;
2500 }
2501 memcpy(&x, buf, 4);
2502 }
2503 else {
2504 memcpy(&x, p, 4);
2505 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 return x;
2508 }
Tim Peters9905b942003-03-20 20:53:32 +00002509}
2510
2511double
2512_PyFloat_Unpack8(const unsigned char *p, int le)
2513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 if (double_format == unknown_format) {
2515 unsigned char sign;
2516 int e;
2517 unsigned int fhi, flo;
2518 double x;
2519 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 if (le) {
2522 p += 7;
2523 incr = -1;
2524 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 /* First byte */
2527 sign = (*p >> 7) & 1;
2528 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 /* Second byte */
2533 e |= (*p >> 4) & 0xF;
2534 fhi = (*p & 0xF) << 24;
2535 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 if (e == 2047) {
2538 PyErr_SetString(
2539 PyExc_ValueError,
2540 "can't unpack IEEE 754 special value "
2541 "on non-IEEE platform");
2542 return -1.0;
2543 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 /* Third byte */
2546 fhi |= *p << 16;
2547 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 /* Fourth byte */
2550 fhi |= *p << 8;
2551 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 /* Fifth byte */
2554 fhi |= *p;
2555 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 /* Sixth byte */
2558 flo = *p << 16;
2559 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 /* Seventh byte */
2562 flo |= *p << 8;
2563 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 /* Eighth byte */
2566 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2569 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 if (e == 0)
2572 e = -1022;
2573 else {
2574 x += 1.0;
2575 e -= 1023;
2576 }
2577 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 if (sign)
2580 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 return x;
2583 }
2584 else {
2585 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 if ((double_format == ieee_little_endian_format && !le)
2588 || (double_format == ieee_big_endian_format && le)) {
2589 char buf[8];
2590 char *d = &buf[7];
2591 int i;
2592
2593 for (i = 0; i < 8; i++) {
2594 *d-- = *p++;
2595 }
2596 memcpy(&x, buf, 8);
2597 }
2598 else {
2599 memcpy(&x, p, 8);
2600 }
2601
2602 return x;
2603 }
Tim Peters9905b942003-03-20 20:53:32 +00002604}