blob: 1cb8ff795fb87f0ae383642f3040f4f22c88ff5b [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
864#if 0
865static PyObject *
866float_is_inf(PyObject *v)
867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 double x = PyFloat_AsDouble(v);
869 if (x == -1.0 && PyErr_Occurred())
870 return NULL;
871 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000872}
873
874static PyObject *
875float_is_nan(PyObject *v)
876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 double x = PyFloat_AsDouble(v);
878 if (x == -1.0 && PyErr_Occurred())
879 return NULL;
880 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000881}
882
883static PyObject *
884float_is_finite(PyObject *v)
885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 double x = PyFloat_AsDouble(v);
887 if (x == -1.0 && PyErr_Occurred())
888 return NULL;
889 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000890}
891#endif
892
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200893/*[clinic input]
894float.__trunc__
895
896Return the Integral closest to x between 0 and x.
897[clinic start generated code]*/
898
Christian Heimes53876d92008-04-19 00:31:39 +0000899static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200900float___trunc___impl(PyObject *self)
901/*[clinic end generated code: output=dd3e289dd4c6b538 input=591b9ba0d650fdff]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000902{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200903 double x = PyFloat_AsDouble(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 (void)modf(x, &wholepart);
907 /* Try to get out cheap if this fits in a Python int. The attempt
908 * to cast to long must be protected, as C doesn't define what
909 * happens if the double is too big to fit in a long. Some rare
910 * systems raise an exception then (RISCOS was mentioned as one,
911 * and someone using a non-default option on Sun also bumped into
912 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
913 * still be vulnerable: if a long has more bits of precision than
914 * a double, casting MIN/MAX to double may yield an approximation,
915 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
916 * yield true from the C expression wholepart<=LONG_MAX, despite
917 * that wholepart is actually greater than LONG_MAX.
918 */
919 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
920 const long aslong = (long)wholepart;
921 return PyLong_FromLong(aslong);
922 }
923 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000924}
925
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000926/* double_round: rounds a finite double to the closest multiple of
927 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
928 ndigits <= 323). Returns a Python float, or sets a Python error and
929 returns NULL on failure (OverflowError and memory errors are possible). */
930
931#ifndef PY_NO_SHORT_FLOAT_REPR
932/* version of double_round that uses the correctly-rounded string<->double
933 conversions from Python/dtoa.c */
934
935static PyObject *
936double_round(double x, int ndigits) {
937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 double rounded;
939 Py_ssize_t buflen, mybuflen=100;
940 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
941 int decpt, sign;
942 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000943 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000946 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000948 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 if (buf == NULL) {
950 PyErr_NoMemory();
951 return NULL;
952 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
955 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
956 buflen = buf_end - buf;
957 if (buflen + 8 > mybuflen) {
958 mybuflen = buflen+8;
959 mybuf = (char *)PyMem_Malloc(mybuflen);
960 if (mybuf == NULL) {
961 PyErr_NoMemory();
962 goto exit;
963 }
964 }
965 /* copy buf to mybuf, adding exponent, sign and leading 0 */
966 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
967 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 /* and convert the resulting string back to a double */
970 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000971 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000973 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (errno == ERANGE && fabs(rounded) >= 1.)
975 PyErr_SetString(PyExc_OverflowError,
976 "rounded value too large to represent");
977 else
978 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 /* done computing value; now clean up */
981 if (mybuf != shortbuf)
982 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000983 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 _Py_dg_freedtoa(buf);
985 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000986}
987
988#else /* PY_NO_SHORT_FLOAT_REPR */
989
990/* fallback version, to be used when correctly rounded binary<->decimal
991 conversions aren't available */
992
993static PyObject *
994double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 double pow1, pow2, y, z;
996 if (ndigits >= 0) {
997 if (ndigits > 22) {
998 /* pow1 and pow2 are each safe from overflow, but
999 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
1000 pow1 = pow(10.0, (double)(ndigits-22));
1001 pow2 = 1e22;
1002 }
1003 else {
1004 pow1 = pow(10.0, (double)ndigits);
1005 pow2 = 1.0;
1006 }
1007 y = (x*pow1)*pow2;
1008 /* if y overflows, then rounded value is exactly x */
1009 if (!Py_IS_FINITE(y))
1010 return PyFloat_FromDouble(x);
1011 }
1012 else {
1013 pow1 = pow(10.0, (double)-ndigits);
1014 pow2 = 1.0; /* unused; silences a gcc compiler warning */
1015 y = x / pow1;
1016 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 z = round(y);
1019 if (fabs(y-z) == 0.5)
1020 /* halfway between two integers; use round-half-even */
1021 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 if (ndigits >= 0)
1024 z = (z / pow2) / pow1;
1025 else
1026 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* if computation resulted in overflow, raise OverflowError */
1029 if (!Py_IS_FINITE(z)) {
1030 PyErr_SetString(PyExc_OverflowError,
1031 "overflow occurred during round");
1032 return NULL;
1033 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001036}
1037
1038#endif /* PY_NO_SHORT_FLOAT_REPR */
1039
1040/* round a Python float v to the closest multiple of 10**-ndigits */
1041
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001042/*[clinic input]
1043float.__round__
1044
Serhiy Storchakad322abb2019-09-14 13:31:50 +03001045 ndigits as o_ndigits: object = None
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001046 /
1047
1048Return the Integral closest to x, rounding half toward even.
1049
1050When an argument is passed, work like built-in round(x, ndigits).
1051[clinic start generated code]*/
1052
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001053static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001054float___round___impl(PyObject *self, PyObject *o_ndigits)
Serhiy Storchakad322abb2019-09-14 13:31:50 +03001055/*[clinic end generated code: output=374c36aaa0f13980 input=fc0fe25924fbc9ed]*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 double x, rounded;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001059
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001060 x = PyFloat_AsDouble(self);
Serhiy Storchakad322abb2019-09-14 13:31:50 +03001061 if (o_ndigits == Py_None) {
Steve Dowercb39d1f2015-04-15 16:10:59 -04001062 /* single-argument round or with None ndigits:
1063 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 rounded = round(x);
1065 if (fabs(x-rounded) == 0.5)
1066 /* halfway case: round to even */
1067 rounded = 2.0*round(x/2.0);
1068 return PyLong_FromDouble(rounded);
1069 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 /* interpret second argument as a Py_ssize_t; clips on overflow */
1072 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1073 if (ndigits == -1 && PyErr_Occurred())
1074 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 /* nans and infinities round to themselves */
1077 if (!Py_IS_FINITE(x))
1078 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1081 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1082 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001083#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1084#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 if (ndigits > NDIGITS_MAX)
1086 /* return x */
1087 return PyFloat_FromDouble(x);
1088 else if (ndigits < NDIGITS_MIN)
1089 /* return 0.0, but with sign of x */
1090 return PyFloat_FromDouble(0.0*x);
1091 else
1092 /* finite x, and ndigits is not unreasonably large */
1093 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001094#undef NDIGITS_MAX
1095#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001096}
1097
1098static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001099float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (PyFloat_CheckExact(v))
1102 Py_INCREF(v);
1103 else
1104 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1105 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001106}
1107
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001108/*[clinic input]
1109float.conjugate
1110
1111Return self, the complex conjugate of any float.
1112[clinic start generated code]*/
1113
1114static PyObject *
1115float_conjugate_impl(PyObject *self)
1116/*[clinic end generated code: output=8ca292c2479194af input=82ba6f37a9ff91dd]*/
1117{
1118 return float_float(self);
1119}
1120
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001121/* turn ASCII hex characters into integer values and vice versa */
1122
1123static char
1124char_from_hex(int x)
1125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001127 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001128}
1129
1130static int
1131hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 int x;
1133 switch(c) {
1134 case '0':
1135 x = 0;
1136 break;
1137 case '1':
1138 x = 1;
1139 break;
1140 case '2':
1141 x = 2;
1142 break;
1143 case '3':
1144 x = 3;
1145 break;
1146 case '4':
1147 x = 4;
1148 break;
1149 case '5':
1150 x = 5;
1151 break;
1152 case '6':
1153 x = 6;
1154 break;
1155 case '7':
1156 x = 7;
1157 break;
1158 case '8':
1159 x = 8;
1160 break;
1161 case '9':
1162 x = 9;
1163 break;
1164 case 'a':
1165 case 'A':
1166 x = 10;
1167 break;
1168 case 'b':
1169 case 'B':
1170 x = 11;
1171 break;
1172 case 'c':
1173 case 'C':
1174 x = 12;
1175 break;
1176 case 'd':
1177 case 'D':
1178 x = 13;
1179 break;
1180 case 'e':
1181 case 'E':
1182 x = 14;
1183 break;
1184 case 'f':
1185 case 'F':
1186 x = 15;
1187 break;
1188 default:
1189 x = -1;
1190 break;
1191 }
1192 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001193}
1194
1195/* convert a float to a hexadecimal string */
1196
1197/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1198 of the form 4k+1. */
1199#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1200
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001201/*[clinic input]
1202float.hex
1203
1204Return a hexadecimal representation of a floating-point number.
1205
1206>>> (-0.1).hex()
1207'-0x1.999999999999ap-4'
1208>>> 3.14159.hex()
1209'0x1.921f9f01b866ep+1'
1210[clinic start generated code]*/
1211
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001212static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001213float_hex_impl(PyObject *self)
1214/*[clinic end generated code: output=0ebc9836e4d302d4 input=bec1271a33d47e67]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 double x, m;
1217 int e, shift, i, si, esign;
1218 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1219 trailing NUL byte. */
1220 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001221
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001222 CONVERT_TO_DOUBLE(self, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001225 return float_repr((PyFloatObject *)self);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001228 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 return PyUnicode_FromString("-0x0.0p+0");
1230 else
1231 return PyUnicode_FromString("0x0.0p+0");
1232 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001235 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 m = ldexp(m, shift);
1237 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 si = 0;
1240 s[si] = char_from_hex((int)m);
1241 si++;
1242 m -= (int)m;
1243 s[si] = '.';
1244 si++;
1245 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1246 m *= 16.0;
1247 s[si] = char_from_hex((int)m);
1248 si++;
1249 m -= (int)m;
1250 }
1251 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 if (e < 0) {
1254 esign = (int)'-';
1255 e = -e;
1256 }
1257 else
1258 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 if (x < 0.0)
1261 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1262 else
1263 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001264}
1265
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001266/* Convert a hexadecimal string to a float. */
1267
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001268/*[clinic input]
1269@classmethod
1270float.fromhex
1271
1272 string: object
1273 /
1274
1275Create a floating-point number from a hexadecimal string.
1276
1277>>> float.fromhex('0x1.ffffp10')
12782047.984375
1279>>> float.fromhex('-0x1p-1074')
1280-5e-324
1281[clinic start generated code]*/
1282
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001283static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001284float_fromhex(PyTypeObject *type, PyObject *string)
1285/*[clinic end generated code: output=46c0274d22b78e82 input=0407bebd354bca89]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001286{
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001287 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 double x;
1289 long exp, top_exp, lsb, key_digit;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001290 const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 int half_eps, digit, round_up, negate=0;
1292 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 /*
1295 * For the sake of simplicity and correctness, we impose an artificial
1296 * limit on ndigits, the total number of hex digits in the coefficient
1297 * The limit is chosen to ensure that, writing exp for the exponent,
1298 *
1299 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1300 * guaranteed to overflow (provided it's nonzero)
1301 *
1302 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1303 * guaranteed to underflow to 0.
1304 *
1305 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1306 * overflow in the calculation of exp and top_exp below.
1307 *
1308 * More specifically, ndigits is assumed to satisfy the following
1309 * inequalities:
1310 *
1311 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1312 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1313 *
1314 * If either of these inequalities is not satisfied, a ValueError is
1315 * raised. Otherwise, write x for the value of the hex string, and
1316 * assume x is nonzero. Then
1317 *
1318 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1319 *
1320 * Now if exp > LONG_MAX/2 then:
1321 *
1322 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1323 * = DBL_MAX_EXP
1324 *
1325 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1326 * double, so overflows. If exp < LONG_MIN/2, then
1327 *
1328 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1329 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1330 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1331 *
1332 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1333 * when converted to a C double.
1334 *
1335 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1336 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1337 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001338
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001339 s = PyUnicode_AsUTF8AndSize(string, &length);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 if (s == NULL)
1341 return NULL;
1342 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 /********************
1345 * Parse the string *
1346 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 /* leading whitespace */
1349 while (Py_ISSPACE(*s))
1350 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 /* infinities and nans */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001353 x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 if (coeff_end != s) {
1355 s = coeff_end;
1356 goto finished;
1357 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 /* optional sign */
1360 if (*s == '-') {
1361 s++;
1362 negate = 1;
1363 }
1364 else if (*s == '+')
1365 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 /* [0x] */
1368 s_store = s;
1369 if (*s == '0') {
1370 s++;
1371 if (*s == 'x' || *s == 'X')
1372 s++;
1373 else
1374 s = s_store;
1375 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 /* coefficient: <integer> [. <fraction>] */
1378 coeff_start = s;
1379 while (hex_from_char(*s) >= 0)
1380 s++;
1381 s_store = s;
1382 if (*s == '.') {
1383 s++;
1384 while (hex_from_char(*s) >= 0)
1385 s++;
1386 coeff_end = s-1;
1387 }
1388 else
1389 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 /* ndigits = total # of hex digits; fdigits = # after point */
1392 ndigits = coeff_end - coeff_start;
1393 fdigits = coeff_end - s_store;
1394 if (ndigits == 0)
1395 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001396 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1397 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 /* [p <exponent>] */
1401 if (*s == 'p' || *s == 'P') {
1402 s++;
1403 exp_start = s;
1404 if (*s == '-' || *s == '+')
1405 s++;
1406 if (!('0' <= *s && *s <= '9'))
1407 goto parse_error;
1408 s++;
1409 while ('0' <= *s && *s <= '9')
1410 s++;
1411 exp = strtol(exp_start, NULL, 10);
1412 }
1413 else
1414 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001415
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001416/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1418 coeff_end-(j) : \
1419 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 /*******************************************
1422 * Compute rounded value of the hex string *
1423 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 /* Discard leading zeros, and catch extreme overflow and underflow */
1426 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1427 ndigits--;
1428 if (ndigits == 0 || exp < LONG_MIN/2) {
1429 x = 0.0;
1430 goto finished;
1431 }
1432 if (exp > LONG_MAX/2)
1433 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 /* Adjust exponent for fractional part. */
1436 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1439 top_exp = exp + 4*((long)ndigits - 1);
1440 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1441 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 /* catch almost all nonextreme cases of overflow and underflow here */
1444 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1445 x = 0.0;
1446 goto finished;
1447 }
1448 if (top_exp > DBL_MAX_EXP)
1449 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 /* lsb = exponent of least significant bit of the *rounded* value.
1452 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001453 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 x = 0.0;
1456 if (exp >= lsb) {
1457 /* no rounding required */
1458 for (i = ndigits-1; i >= 0; i--)
1459 x = 16.0*x + HEX_DIGIT(i);
1460 x = ldexp(x, (int)(exp));
1461 goto finished;
1462 }
1463 /* rounding required. key_digit is the index of the hex digit
1464 containing the first bit to be rounded away. */
1465 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1466 key_digit = (lsb - exp - 1) / 4;
1467 for (i = ndigits-1; i > key_digit; i--)
1468 x = 16.0*x + HEX_DIGIT(i);
1469 digit = HEX_DIGIT(key_digit);
1470 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1473 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1474 if ((digit & half_eps) != 0) {
1475 round_up = 0;
1476 if ((digit & (3*half_eps-1)) != 0 ||
1477 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1478 round_up = 1;
1479 else
1480 for (i = key_digit-1; i >= 0; i--)
1481 if (HEX_DIGIT(i) != 0) {
1482 round_up = 1;
1483 break;
1484 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001485 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 x += 2*half_eps;
1487 if (top_exp == DBL_MAX_EXP &&
1488 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1489 /* overflow corner case: pre-rounded value <
1490 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1491 goto overflow_error;
1492 }
1493 }
1494 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001495
1496 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 /* optional trailing whitespace leading to the end of the string */
1498 while (Py_ISSPACE(*s))
1499 s++;
1500 if (s != s_end)
1501 goto parse_error;
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001502 result = PyFloat_FromDouble(negate ? -x : x);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001503 if (type != &PyFloat_Type && result != NULL) {
1504 Py_SETREF(result, PyObject_CallFunctionObjArgs((PyObject *)type, result, NULL));
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001505 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001507
1508 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 PyErr_SetString(PyExc_OverflowError,
1510 "hexadecimal value too large to represent as a float");
1511 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001512
1513 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 PyErr_SetString(PyExc_ValueError,
1515 "invalid hexadecimal floating-point string");
1516 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001517
1518 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 PyErr_SetString(PyExc_ValueError,
1520 "hexadecimal string too long to convert");
1521 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001522}
1523
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001524/*[clinic input]
1525float.as_integer_ratio
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001526
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001527Return integer ratio.
1528
1529Return a pair of integers, whose ratio is exactly equal to the original float
1530and with a positive denominator.
1531
1532Raise OverflowError on infinities and a ValueError on NaNs.
1533
1534>>> (10.0).as_integer_ratio()
1535(10, 1)
1536>>> (0.0).as_integer_ratio()
1537(0, 1)
1538>>> (-.25).as_integer_ratio()
1539(-1, 4)
1540[clinic start generated code]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001541
Christian Heimes26855632008-01-27 23:50:43 +00001542static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001543float_as_integer_ratio_impl(PyObject *self)
1544/*[clinic end generated code: output=65f25f0d8d30a712 input=e21d08b4630c2e44]*/
Christian Heimes26855632008-01-27 23:50:43 +00001545{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001546 double self_double;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 double float_part;
1548 int exponent;
1549 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 PyObject *py_exponent = NULL;
1552 PyObject *numerator = NULL;
1553 PyObject *denominator = NULL;
1554 PyObject *result_pair = NULL;
1555 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001556
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001557 CONVERT_TO_DOUBLE(self, self_double);
Christian Heimes26855632008-01-27 23:50:43 +00001558
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001559 if (Py_IS_INFINITY(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001560 PyErr_SetString(PyExc_OverflowError,
1561 "cannot convert Infinity to integer ratio");
1562 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001564 if (Py_IS_NAN(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001565 PyErr_SetString(PyExc_ValueError,
1566 "cannot convert NaN to integer ratio");
1567 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 }
Christian Heimes26855632008-01-27 23:50:43 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001571 float_part = frexp(self_double, &exponent); /* self_double == float_part * 2**exponent exactly */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1575 float_part *= 2.0;
1576 exponent--;
1577 }
1578 /* self == float_part * 2**exponent exactly and float_part is integral.
1579 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1580 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 numerator = PyLong_FromDouble(float_part);
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001583 if (numerator == NULL)
1584 goto error;
1585 denominator = PyLong_FromLong(1);
1586 if (denominator == NULL)
1587 goto error;
1588 py_exponent = PyLong_FromLong(Py_ABS(exponent));
1589 if (py_exponent == NULL)
1590 goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 /* fold in 2**exponent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 if (exponent > 0) {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001594 Py_SETREF(numerator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001595 long_methods->nb_lshift(numerator, py_exponent));
1596 if (numerator == NULL)
1597 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 }
1599 else {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001600 Py_SETREF(denominator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001601 long_methods->nb_lshift(denominator, py_exponent));
1602 if (denominator == NULL)
1603 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 }
1605
1606 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001607
Christian Heimes26855632008-01-27 23:50:43 +00001608error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 Py_XDECREF(py_exponent);
1610 Py_XDECREF(denominator);
1611 Py_XDECREF(numerator);
1612 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001613}
1614
Jeremy Hylton938ace62002-07-17 16:30:39 +00001615static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001616float_subtype_new(PyTypeObject *type, PyObject *x);
1617
1618/*[clinic input]
1619@classmethod
1620float.__new__ as float_new
Serhiy Storchakaba85d692017-03-30 09:09:41 +03001621 x: object(c_default="_PyLong_Zero") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001622 /
1623
1624Convert a string or number to a floating point number, if possible.
1625[clinic start generated code]*/
Guido van Rossumbef14172001-08-29 15:47:46 +00001626
Tim Peters6d6c1a32001-08-02 04:15:00 +00001627static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001628float_new_impl(PyTypeObject *type, PyObject *x)
Serhiy Storchakabae68812017-04-05 12:00:42 +03001629/*[clinic end generated code: output=ccf1e8dc460ba6ba input=540ee77c204ff87a]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00001630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 if (type != &PyFloat_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001632 return float_subtype_new(type, x); /* Wimp out */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 /* If it's a string, but not a string subclass, use
1634 PyFloat_FromString. */
1635 if (PyUnicode_CheckExact(x))
1636 return PyFloat_FromString(x);
1637 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001638}
1639
Guido van Rossumbef14172001-08-29 15:47:46 +00001640/* Wimpy, slow approach to tp_new calls for subtypes of float:
1641 first create a regular float from whatever arguments we got,
1642 then allocate a subtype instance and initialize its ob_fval
1643 from the regular float. The regular float is then thrown away.
1644*/
1645static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001646float_subtype_new(PyTypeObject *type, PyObject *x)
Guido van Rossumbef14172001-08-29 15:47:46 +00001647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 assert(PyType_IsSubtype(type, &PyFloat_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001651 tmp = float_new_impl(&PyFloat_Type, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 if (tmp == NULL)
1653 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001654 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 newobj = type->tp_alloc(type, 0);
1656 if (newobj == NULL) {
1657 Py_DECREF(tmp);
1658 return NULL;
1659 }
1660 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1661 Py_DECREF(tmp);
1662 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001663}
1664
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001665/*[clinic input]
1666float.__getnewargs__
1667[clinic start generated code]*/
1668
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001669static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001670float___getnewargs___impl(PyObject *self)
1671/*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001672{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001673 return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001674}
1675
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001676/* this is for the benefit of the pack/unpack routines below */
1677
1678typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001680} float_format_type;
1681
1682static float_format_type double_format, float_format;
1683static float_format_type detected_double_format, detected_float_format;
1684
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001685/*[clinic input]
1686@classmethod
1687float.__getformat__
1688
1689 typestr: str
1690 Must be 'double' or 'float'.
1691 /
1692
1693You probably don't want to use this function.
1694
1695It exists mainly to be used in Python's test suite.
1696
1697This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
1698little-endian' best describes the format of floating point numbers used by the
1699C type named by typestr.
1700[clinic start generated code]*/
1701
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001702static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001703float___getformat___impl(PyTypeObject *type, const char *typestr)
1704/*[clinic end generated code: output=2bfb987228cc9628 input=d5a52600f835ad67]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001707
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001708 if (strcmp(typestr, "double") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 r = double_format;
1710 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001711 else if (strcmp(typestr, "float") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 r = float_format;
1713 }
1714 else {
1715 PyErr_SetString(PyExc_ValueError,
1716 "__getformat__() argument 1 must be "
1717 "'double' or 'float'");
1718 return NULL;
1719 }
1720
1721 switch (r) {
1722 case unknown_format:
1723 return PyUnicode_FromString("unknown");
1724 case ieee_little_endian_format:
1725 return PyUnicode_FromString("IEEE, little-endian");
1726 case ieee_big_endian_format:
1727 return PyUnicode_FromString("IEEE, big-endian");
1728 default:
1729 Py_FatalError("insane float_format or double_format");
1730 return NULL;
1731 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001732}
1733
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001734/*[clinic input]
1735@classmethod
1736float.__set_format__
1737
1738 typestr: str
1739 Must be 'double' or 'float'.
1740 fmt: str
1741 Must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian',
1742 and in addition can only be one of the latter two if it appears to
1743 match the underlying C reality.
1744 /
1745
1746You probably don't want to use this function.
1747
1748It exists mainly to be used in Python's test suite.
1749
1750Override the automatic determination of C-level floating point type.
1751This affects how floats are converted to and from binary strings.
1752[clinic start generated code]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001753
1754static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001755float___set_format___impl(PyTypeObject *type, const char *typestr,
1756 const char *fmt)
1757/*[clinic end generated code: output=504460f5dc85acbd input=5306fa2b81a997e4]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 float_format_type f;
1760 float_format_type detected;
1761 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 if (strcmp(typestr, "double") == 0) {
1764 p = &double_format;
1765 detected = detected_double_format;
1766 }
1767 else if (strcmp(typestr, "float") == 0) {
1768 p = &float_format;
1769 detected = detected_float_format;
1770 }
1771 else {
1772 PyErr_SetString(PyExc_ValueError,
1773 "__setformat__() argument 1 must "
1774 "be 'double' or 'float'");
1775 return NULL;
1776 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001777
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001778 if (strcmp(fmt, "unknown") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 f = unknown_format;
1780 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001781 else if (strcmp(fmt, "IEEE, little-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 f = ieee_little_endian_format;
1783 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001784 else if (strcmp(fmt, "IEEE, big-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 f = ieee_big_endian_format;
1786 }
1787 else {
1788 PyErr_SetString(PyExc_ValueError,
1789 "__setformat__() argument 2 must be "
1790 "'unknown', 'IEEE, little-endian' or "
1791 "'IEEE, big-endian'");
1792 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 if (f != unknown_format && f != detected) {
1797 PyErr_Format(PyExc_ValueError,
1798 "can only set %s format to 'unknown' or the "
1799 "detected platform value", typestr);
1800 return NULL;
1801 }
1802
1803 *p = f;
1804 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001805}
1806
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001807static PyObject *
1808float_getreal(PyObject *v, void *closure)
1809{
1810 return float_float(v);
1811}
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001812
Guido van Rossumb43daf72007-08-01 18:08:08 +00001813static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001814float_getimag(PyObject *v, void *closure)
Guido van Rossumb43daf72007-08-01 18:08:08 +00001815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001817}
1818
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001819/*[clinic input]
1820float.__format__
1821
1822 format_spec: unicode
1823 /
1824
1825Formats the float according to format_spec.
1826[clinic start generated code]*/
1827
Eric Smith8c663262007-08-25 02:26:07 +00001828static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001829float___format___impl(PyObject *self, PyObject *format_spec)
1830/*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/
Eric Smith8c663262007-08-25 02:26:07 +00001831{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001832 _PyUnicodeWriter writer;
1833 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001834
Victor Stinner8f674cc2013-04-17 23:02:17 +02001835 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001836 ret = _PyFloat_FormatAdvancedWriter(
1837 &writer,
1838 self,
1839 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1840 if (ret == -1) {
1841 _PyUnicodeWriter_Dealloc(&writer);
1842 return NULL;
1843 }
1844 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001845}
1846
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001847static PyMethodDef float_methods[] = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001848 FLOAT_CONJUGATE_METHODDEF
1849 FLOAT___TRUNC___METHODDEF
1850 FLOAT___ROUND___METHODDEF
1851 FLOAT_AS_INTEGER_RATIO_METHODDEF
1852 FLOAT_FROMHEX_METHODDEF
1853 FLOAT_HEX_METHODDEF
1854 FLOAT_IS_INTEGER_METHODDEF
Christian Heimes53876d92008-04-19 00:31:39 +00001855#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001857 "Return True if the float is positive or negative infinite."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001859 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001861 "Return True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001862#endif
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001863 FLOAT___GETNEWARGS___METHODDEF
1864 FLOAT___GETFORMAT___METHODDEF
1865 FLOAT___SET_FORMAT___METHODDEF
1866 FLOAT___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001868};
1869
Guido van Rossumb43daf72007-08-01 18:08:08 +00001870static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 {"real",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001872 float_getreal, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001873 "the real part of a complex number",
1874 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 {"imag",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001876 float_getimag, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001877 "the imaginary part of a complex number",
1878 NULL},
1879 {NULL} /* Sentinel */
1880};
1881
Tim Peters6d6c1a32001-08-02 04:15:00 +00001882
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001883static PyNumberMethods float_as_number = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001884 float_add, /* nb_add */
1885 float_sub, /* nb_subtract */
1886 float_mul, /* nb_multiply */
1887 float_rem, /* nb_remainder */
1888 float_divmod, /* nb_divmod */
1889 float_pow, /* nb_power */
1890 (unaryfunc)float_neg, /* nb_negative */
1891 float_float, /* nb_positive */
1892 (unaryfunc)float_abs, /* nb_absolute */
1893 (inquiry)float_bool, /* nb_bool */
1894 0, /* nb_invert */
1895 0, /* nb_lshift */
1896 0, /* nb_rshift */
1897 0, /* nb_and */
1898 0, /* nb_xor */
1899 0, /* nb_or */
1900 float___trunc___impl, /* nb_int */
1901 0, /* nb_reserved */
1902 float_float, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 0, /* nb_inplace_add */
1904 0, /* nb_inplace_subtract */
1905 0, /* nb_inplace_multiply */
1906 0, /* nb_inplace_remainder */
1907 0, /* nb_inplace_power */
1908 0, /* nb_inplace_lshift */
1909 0, /* nb_inplace_rshift */
1910 0, /* nb_inplace_and */
1911 0, /* nb_inplace_xor */
1912 0, /* nb_inplace_or */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001913 float_floor_div, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 float_div, /* nb_true_divide */
1915 0, /* nb_inplace_floor_divide */
1916 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001917};
1918
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001919PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1921 "float",
1922 sizeof(PyFloatObject),
1923 0,
1924 (destructor)float_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001925 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 0, /* tp_getattr */
1927 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001928 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 (reprfunc)float_repr, /* tp_repr */
1930 &float_as_number, /* tp_as_number */
1931 0, /* tp_as_sequence */
1932 0, /* tp_as_mapping */
1933 (hashfunc)float_hash, /* tp_hash */
1934 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001935 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 PyObject_GenericGetAttr, /* tp_getattro */
1937 0, /* tp_setattro */
1938 0, /* tp_as_buffer */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001939 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001940 float_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 0, /* tp_traverse */
1942 0, /* tp_clear */
1943 float_richcompare, /* tp_richcompare */
1944 0, /* tp_weaklistoffset */
1945 0, /* tp_iter */
1946 0, /* tp_iternext */
1947 float_methods, /* tp_methods */
1948 0, /* tp_members */
1949 float_getset, /* tp_getset */
1950 0, /* tp_base */
1951 0, /* tp_dict */
1952 0, /* tp_descr_get */
1953 0, /* tp_descr_set */
1954 0, /* tp_dictoffset */
1955 0, /* tp_init */
1956 0, /* tp_alloc */
1957 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001958};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001959
Victor Stinner1c8f0592013-07-22 22:24:54 +02001960int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001961_PyFloat_Init(void)
1962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 /* We attempt to determine if this machine is using IEEE
1964 floating point formats by peering at the bits of some
1965 carefully chosen values. If it looks like we are on an
1966 IEEE platform, the float packing/unpacking routines can
1967 just copy bits, if not they resort to arithmetic & shifts
1968 and masks. The shifts & masks approach works on all finite
1969 values, but what happens to infinities, NaNs and signed
1970 zeroes on packing is an accident, and attempting to unpack
1971 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 Note that if we're on some whacked-out platform which uses
1974 IEEE formats but isn't strictly little-endian or big-
1975 endian, we will fall back to the portable shifts & masks
1976 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001977
1978#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 {
1980 double x = 9006104071832581.0;
1981 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1982 detected_double_format = ieee_big_endian_format;
1983 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1984 detected_double_format = ieee_little_endian_format;
1985 else
1986 detected_double_format = unknown_format;
1987 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001988#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001990#endif
1991
1992#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 {
1994 float y = 16711938.0;
1995 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1996 detected_float_format = ieee_big_endian_format;
1997 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1998 detected_float_format = ieee_little_endian_format;
1999 else
2000 detected_float_format = unknown_format;
2001 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002002#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002004#endif
2005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 double_format = detected_double_format;
2007 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002010 if (FloatInfoType.tp_name == NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01002011 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02002012 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01002013 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002014 }
2015 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002016}
2017
Georg Brandl2ee470f2008-07-16 12:55:28 +00002018int
2019PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002020{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002021 PyFloatObject *f = free_list, *next;
2022 int i = numfree;
2023 while (f) {
2024 next = (PyFloatObject*) Py_TYPE(f);
2025 PyObject_FREE(f);
2026 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002028 free_list = NULL;
2029 numfree = 0;
2030 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00002031}
2032
2033void
2034PyFloat_Fini(void)
2035{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002036 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002037}
Tim Peters9905b942003-03-20 20:53:32 +00002038
David Malcolm49526f42012-06-22 14:55:41 -04002039/* Print summary info about the state of the optimized allocator */
2040void
2041_PyFloat_DebugMallocStats(FILE *out)
2042{
2043 _PyDebugAllocatorStats(out,
2044 "free PyFloatObject",
2045 numfree, sizeof(PyFloatObject));
2046}
2047
2048
Tim Peters9905b942003-03-20 20:53:32 +00002049/*----------------------------------------------------------------------------
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002050 * _PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h.
2051 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
2052 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
2053 * We use:
2054 * bits = (unsigned short)f; Note the truncation
2055 * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
2056 * bits++;
2057 * }
Tim Peters9905b942003-03-20 20:53:32 +00002058 */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002059
2060int
2061_PyFloat_Pack2(double x, unsigned char *p, int le)
2062{
2063 unsigned char sign;
2064 int e;
2065 double f;
2066 unsigned short bits;
2067 int incr = 1;
2068
2069 if (x == 0.0) {
2070 sign = (copysign(1.0, x) == -1.0);
2071 e = 0;
2072 bits = 0;
2073 }
2074 else if (Py_IS_INFINITY(x)) {
2075 sign = (x < 0.0);
2076 e = 0x1f;
2077 bits = 0;
2078 }
2079 else if (Py_IS_NAN(x)) {
2080 /* There are 2046 distinct half-precision NaNs (1022 signaling and
2081 1024 quiet), but there are only two quiet NaNs that don't arise by
2082 quieting a signaling NaN; we get those by setting the topmost bit
2083 of the fraction field and clearing all other fraction bits. We
2084 choose the one with the appropriate sign. */
2085 sign = (copysign(1.0, x) == -1.0);
2086 e = 0x1f;
2087 bits = 512;
2088 }
2089 else {
2090 sign = (x < 0.0);
2091 if (sign) {
2092 x = -x;
2093 }
2094
2095 f = frexp(x, &e);
2096 if (f < 0.5 || f >= 1.0) {
2097 PyErr_SetString(PyExc_SystemError,
2098 "frexp() result out of range");
2099 return -1;
2100 }
2101
2102 /* Normalize f to be in the range [1.0, 2.0) */
2103 f *= 2.0;
2104 e--;
2105
2106 if (e >= 16) {
2107 goto Overflow;
2108 }
2109 else if (e < -25) {
2110 /* |x| < 2**-25. Underflow to zero. */
2111 f = 0.0;
2112 e = 0;
2113 }
2114 else if (e < -14) {
2115 /* |x| < 2**-14. Gradual underflow */
2116 f = ldexp(f, 14 + e);
2117 e = 0;
2118 }
2119 else /* if (!(e == 0 && f == 0.0)) */ {
2120 e += 15;
2121 f -= 1.0; /* Get rid of leading 1 */
2122 }
2123
2124 f *= 1024.0; /* 2**10 */
2125 /* Round to even */
2126 bits = (unsigned short)f; /* Note the truncation */
2127 assert(bits < 1024);
2128 assert(e < 31);
2129 if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2130 ++bits;
2131 if (bits == 1024) {
2132 /* The carry propagated out of a string of 10 1 bits. */
2133 bits = 0;
2134 ++e;
2135 if (e == 31)
2136 goto Overflow;
2137 }
2138 }
2139 }
2140
2141 bits |= (e << 10) | (sign << 15);
2142
2143 /* Write out result. */
2144 if (le) {
2145 p += 1;
2146 incr = -1;
2147 }
2148
2149 /* First byte */
2150 *p = (unsigned char)((bits >> 8) & 0xFF);
2151 p += incr;
2152
2153 /* Second byte */
2154 *p = (unsigned char)(bits & 0xFF);
2155
2156 return 0;
2157
2158 Overflow:
2159 PyErr_SetString(PyExc_OverflowError,
2160 "float too large to pack with e format");
2161 return -1;
2162}
2163
Tim Peters9905b942003-03-20 20:53:32 +00002164int
2165_PyFloat_Pack4(double x, unsigned char *p, int le)
2166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 if (float_format == unknown_format) {
2168 unsigned char sign;
2169 int e;
2170 double f;
2171 unsigned int fbits;
2172 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 if (le) {
2175 p += 3;
2176 incr = -1;
2177 }
Tim Peters9905b942003-03-20 20:53:32 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 if (x < 0) {
2180 sign = 1;
2181 x = -x;
2182 }
2183 else
2184 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 /* Normalize f to be in the range [1.0, 2.0) */
2189 if (0.5 <= f && f < 1.0) {
2190 f *= 2.0;
2191 e--;
2192 }
2193 else if (f == 0.0)
2194 e = 0;
2195 else {
2196 PyErr_SetString(PyExc_SystemError,
2197 "frexp() result out of range");
2198 return -1;
2199 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 if (e >= 128)
2202 goto Overflow;
2203 else if (e < -126) {
2204 /* Gradual underflow */
2205 f = ldexp(f, 126 + e);
2206 e = 0;
2207 }
2208 else if (!(e == 0 && f == 0.0)) {
2209 e += 127;
2210 f -= 1.0; /* Get rid of leading 1 */
2211 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 f *= 8388608.0; /* 2**23 */
2214 fbits = (unsigned int)(f + 0.5); /* Round */
2215 assert(fbits <= 8388608);
2216 if (fbits >> 23) {
2217 /* The carry propagated out of a string of 23 1 bits. */
2218 fbits = 0;
2219 ++e;
2220 if (e >= 255)
2221 goto Overflow;
2222 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* First byte */
2225 *p = (sign << 7) | (e >> 1);
2226 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 /* Second byte */
2229 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2230 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 /* Third byte */
2233 *p = (fbits >> 8) & 0xFF;
2234 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 /* Fourth byte */
2237 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 /* Done */
2240 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 }
2243 else {
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002244 float y = (float)x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002246
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002247 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002249
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002250 unsigned char s[sizeof(float)];
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002251 memcpy(s, &y, sizeof(float));
2252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 if ((float_format == ieee_little_endian_format && !le)
2254 || (float_format == ieee_big_endian_format && le)) {
2255 p += 3;
2256 incr = -1;
2257 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 for (i = 0; i < 4; i++) {
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002260 *p = s[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 p += incr;
2262 }
2263 return 0;
2264 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002265 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 PyErr_SetString(PyExc_OverflowError,
2267 "float too large to pack with f format");
2268 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002269}
2270
2271int
2272_PyFloat_Pack8(double x, unsigned char *p, int le)
2273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 if (double_format == unknown_format) {
2275 unsigned char sign;
2276 int e;
2277 double f;
2278 unsigned int fhi, flo;
2279 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 if (le) {
2282 p += 7;
2283 incr = -1;
2284 }
Tim Peters9905b942003-03-20 20:53:32 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 if (x < 0) {
2287 sign = 1;
2288 x = -x;
2289 }
2290 else
2291 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* Normalize f to be in the range [1.0, 2.0) */
2296 if (0.5 <= f && f < 1.0) {
2297 f *= 2.0;
2298 e--;
2299 }
2300 else if (f == 0.0)
2301 e = 0;
2302 else {
2303 PyErr_SetString(PyExc_SystemError,
2304 "frexp() result out of range");
2305 return -1;
2306 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 if (e >= 1024)
2309 goto Overflow;
2310 else if (e < -1022) {
2311 /* Gradual underflow */
2312 f = ldexp(f, 1022 + e);
2313 e = 0;
2314 }
2315 else if (!(e == 0 && f == 0.0)) {
2316 e += 1023;
2317 f -= 1.0; /* Get rid of leading 1 */
2318 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2321 f *= 268435456.0; /* 2**28 */
2322 fhi = (unsigned int)f; /* Truncate */
2323 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 f -= (double)fhi;
2326 f *= 16777216.0; /* 2**24 */
2327 flo = (unsigned int)(f + 0.5); /* Round */
2328 assert(flo <= 16777216);
2329 if (flo >> 24) {
2330 /* The carry propagated out of a string of 24 1 bits. */
2331 flo = 0;
2332 ++fhi;
2333 if (fhi >> 28) {
2334 /* And it also progagated out of the next 28 bits. */
2335 fhi = 0;
2336 ++e;
2337 if (e >= 2047)
2338 goto Overflow;
2339 }
2340 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 /* First byte */
2343 *p = (sign << 7) | (e >> 4);
2344 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 /* Second byte */
2347 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2348 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 /* Third byte */
2351 *p = (fhi >> 16) & 0xFF;
2352 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 /* Fourth byte */
2355 *p = (fhi >> 8) & 0xFF;
2356 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 /* Fifth byte */
2359 *p = fhi & 0xFF;
2360 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 /* Sixth byte */
2363 *p = (flo >> 16) & 0xFF;
2364 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 /* Seventh byte */
2367 *p = (flo >> 8) & 0xFF;
2368 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 /* Eighth byte */
2371 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002372 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 /* Done */
2375 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 Overflow:
2378 PyErr_SetString(PyExc_OverflowError,
2379 "float too large to pack with d format");
2380 return -1;
2381 }
2382 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002383 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 if ((double_format == ieee_little_endian_format && !le)
2387 || (double_format == ieee_big_endian_format && le)) {
2388 p += 7;
2389 incr = -1;
2390 }
2391
2392 for (i = 0; i < 8; i++) {
2393 *p = *s++;
2394 p += incr;
2395 }
2396 return 0;
2397 }
Tim Peters9905b942003-03-20 20:53:32 +00002398}
2399
2400double
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002401_PyFloat_Unpack2(const unsigned char *p, int le)
2402{
2403 unsigned char sign;
2404 int e;
2405 unsigned int f;
2406 double x;
2407 int incr = 1;
2408
2409 if (le) {
2410 p += 1;
2411 incr = -1;
2412 }
2413
2414 /* First byte */
2415 sign = (*p >> 7) & 1;
2416 e = (*p & 0x7C) >> 2;
2417 f = (*p & 0x03) << 8;
2418 p += incr;
2419
2420 /* Second byte */
2421 f |= *p;
2422
2423 if (e == 0x1f) {
2424#ifdef PY_NO_SHORT_FLOAT_REPR
2425 if (f == 0) {
2426 /* Infinity */
2427 return sign ? -Py_HUGE_VAL : Py_HUGE_VAL;
2428 }
2429 else {
2430 /* NaN */
2431#ifdef Py_NAN
2432 return sign ? -Py_NAN : Py_NAN;
2433#else
2434 PyErr_SetString(
2435 PyExc_ValueError,
2436 "can't unpack IEEE 754 NaN "
2437 "on platform that does not support NaNs");
2438 return -1;
2439#endif /* #ifdef Py_NAN */
2440 }
2441#else
2442 if (f == 0) {
2443 /* Infinity */
2444 return _Py_dg_infinity(sign);
2445 }
2446 else {
2447 /* NaN */
2448 return _Py_dg_stdnan(sign);
2449 }
2450#endif /* #ifdef PY_NO_SHORT_FLOAT_REPR */
2451 }
2452
2453 x = (double)f / 1024.0;
2454
2455 if (e == 0) {
2456 e = -14;
2457 }
2458 else {
2459 x += 1.0;
2460 e -= 15;
2461 }
2462 x = ldexp(x, e);
2463
2464 if (sign)
2465 x = -x;
2466
2467 return x;
2468}
2469
2470double
Tim Peters9905b942003-03-20 20:53:32 +00002471_PyFloat_Unpack4(const unsigned char *p, int le)
2472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 if (float_format == unknown_format) {
2474 unsigned char sign;
2475 int e;
2476 unsigned int f;
2477 double x;
2478 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 if (le) {
2481 p += 3;
2482 incr = -1;
2483 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 /* First byte */
2486 sign = (*p >> 7) & 1;
2487 e = (*p & 0x7F) << 1;
2488 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 /* Second byte */
2491 e |= (*p >> 7) & 1;
2492 f = (*p & 0x7F) << 16;
2493 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 if (e == 255) {
2496 PyErr_SetString(
2497 PyExc_ValueError,
2498 "can't unpack IEEE 754 special value "
2499 "on non-IEEE platform");
2500 return -1;
2501 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 /* Third byte */
2504 f |= *p << 8;
2505 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 /* Fourth byte */
2508 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 /* XXX This sadly ignores Inf/NaN issues */
2513 if (e == 0)
2514 e = -126;
2515 else {
2516 x += 1.0;
2517 e -= 127;
2518 }
2519 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 if (sign)
2522 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 return x;
2525 }
2526 else {
2527 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 if ((float_format == ieee_little_endian_format && !le)
2530 || (float_format == ieee_big_endian_format && le)) {
2531 char buf[4];
2532 char *d = &buf[3];
2533 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 for (i = 0; i < 4; i++) {
2536 *d-- = *p++;
2537 }
2538 memcpy(&x, buf, 4);
2539 }
2540 else {
2541 memcpy(&x, p, 4);
2542 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 return x;
2545 }
Tim Peters9905b942003-03-20 20:53:32 +00002546}
2547
2548double
2549_PyFloat_Unpack8(const unsigned char *p, int le)
2550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 if (double_format == unknown_format) {
2552 unsigned char sign;
2553 int e;
2554 unsigned int fhi, flo;
2555 double x;
2556 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 if (le) {
2559 p += 7;
2560 incr = -1;
2561 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 /* First byte */
2564 sign = (*p >> 7) & 1;
2565 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 /* Second byte */
2570 e |= (*p >> 4) & 0xF;
2571 fhi = (*p & 0xF) << 24;
2572 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 if (e == 2047) {
2575 PyErr_SetString(
2576 PyExc_ValueError,
2577 "can't unpack IEEE 754 special value "
2578 "on non-IEEE platform");
2579 return -1.0;
2580 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 /* Third byte */
2583 fhi |= *p << 16;
2584 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 /* Fourth byte */
2587 fhi |= *p << 8;
2588 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 /* Fifth byte */
2591 fhi |= *p;
2592 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 /* Sixth byte */
2595 flo = *p << 16;
2596 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 /* Seventh byte */
2599 flo |= *p << 8;
2600 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 /* Eighth byte */
2603 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2606 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 if (e == 0)
2609 e = -1022;
2610 else {
2611 x += 1.0;
2612 e -= 1023;
2613 }
2614 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 if (sign)
2617 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 return x;
2620 }
2621 else {
2622 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 if ((double_format == ieee_little_endian_format && !le)
2625 || (double_format == ieee_big_endian_format && le)) {
2626 char buf[8];
2627 char *d = &buf[7];
2628 int i;
2629
2630 for (i = 0; i < 8; i++) {
2631 *d-- = *p++;
2632 }
2633 memcpy(&x, buf, 8);
2634 }
2635 else {
2636 memcpy(&x, p, 8);
2637 }
2638
2639 return x;
2640 }
Tim Peters9905b942003-03-20 20:53:32 +00002641}