blob: 4fc412b43f7a3eabe00478eaa4d288eecb4a679a [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\
Raymond Hettinger71170742019-09-11 07:17:32 -070046A 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 switch (op) {
510 case Py_EQ:
511 r = i == j;
512 break;
513 case Py_NE:
514 r = i != j;
515 break;
516 case Py_LE:
517 r = i <= j;
518 break;
519 case Py_GE:
520 r = i >= j;
521 break;
522 case Py_LT:
523 r = i < j;
524 break;
525 case Py_GT:
526 r = i > j;
527 break;
528 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000530
531 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500532 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000533}
534
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000535static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000536float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000539}
540
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000541static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000542float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 double a,b;
545 CONVERT_TO_DOUBLE(v, a);
546 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 a = a + b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000549}
550
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000551static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000552float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 double a,b;
555 CONVERT_TO_DOUBLE(v, a);
556 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 a = a - b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000559}
560
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000561static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000562float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 double a,b;
565 CONVERT_TO_DOUBLE(v, a);
566 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 a = a * b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000569}
570
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000571static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000572float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 double a,b;
575 CONVERT_TO_DOUBLE(v, a);
576 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 if (b == 0.0) {
578 PyErr_SetString(PyExc_ZeroDivisionError,
579 "float division by zero");
580 return NULL;
581 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 a = a / b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000584}
585
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000586static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000587float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 double vx, wx;
590 double mod;
591 CONVERT_TO_DOUBLE(v, vx);
592 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 if (wx == 0.0) {
594 PyErr_SetString(PyExc_ZeroDivisionError,
595 "float modulo");
596 return NULL;
597 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000599 if (mod) {
600 /* ensure the remainder has the same sign as the denominator */
601 if ((wx < 0) != (mod < 0)) {
602 mod += wx;
603 }
604 }
605 else {
606 /* the remainder is zero, and in the presence of signed zeroes
607 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000608 it has the same sign as the denominator. */
609 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000612}
613
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000614static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000615float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 double vx, wx;
618 double div, mod, floordiv;
619 CONVERT_TO_DOUBLE(v, vx);
620 CONVERT_TO_DOUBLE(w, wx);
621 if (wx == 0.0) {
622 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
623 return NULL;
624 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 mod = fmod(vx, wx);
626 /* fmod is typically exact, so vx-mod is *mathematically* an
627 exact multiple of wx. But this is fp arithmetic, and fp
628 vx - mod is an approximation; the result is that div may
629 not be an exact integral value after the division, although
630 it will always be very close to one.
631 */
632 div = (vx - mod) / wx;
633 if (mod) {
634 /* ensure the remainder has the same sign as the denominator */
635 if ((wx < 0) != (mod < 0)) {
636 mod += wx;
637 div -= 1.0;
638 }
639 }
640 else {
641 /* the remainder is zero, and in the presence of signed zeroes
642 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000643 it has the same sign as the denominator. */
644 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 }
646 /* snap quotient to nearest integral value */
647 if (div) {
648 floordiv = floor(div);
649 if (div - floordiv > 0.5)
650 floordiv += 1.0;
651 }
652 else {
653 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000654 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000657}
658
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000659static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000660float_floor_div(PyObject *v, PyObject *w)
661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 t = float_divmod(v, w);
665 if (t == NULL || t == Py_NotImplemented)
666 return t;
667 assert(PyTuple_CheckExact(t));
668 r = PyTuple_GET_ITEM(t, 0);
669 Py_INCREF(r);
670 Py_DECREF(t);
671 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000672}
673
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000674/* determine whether x is an odd integer or not; assumes that
675 x is not an infinity or nan. */
676#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
677
Tim Peters63a35712001-12-11 19:57:24 +0000678static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000679float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 double iv, iw, ix;
682 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 if ((PyObject *)z != Py_None) {
685 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
686 "allowed unless all arguments are integers");
687 return NULL;
688 }
Tim Peters32f453e2001-09-03 08:35:41 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 CONVERT_TO_DOUBLE(v, iv);
691 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 /* Sort out special cases here instead of relying on pow() */
694 if (iw == 0) { /* v**0 is 1, even 0**0 */
695 return PyFloat_FromDouble(1.0);
696 }
697 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
698 return PyFloat_FromDouble(iv);
699 }
700 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
701 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
702 }
703 if (Py_IS_INFINITY(iw)) {
704 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
705 * abs(v) > 1 (including case where v infinite)
706 *
707 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
708 * abs(v) > 1 (including case where v infinite)
709 */
710 iv = fabs(iv);
711 if (iv == 1.0)
712 return PyFloat_FromDouble(1.0);
713 else if ((iw > 0.0) == (iv > 1.0))
714 return PyFloat_FromDouble(fabs(iw)); /* return inf */
715 else
716 return PyFloat_FromDouble(0.0);
717 }
718 if (Py_IS_INFINITY(iv)) {
719 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
720 * both cases, we need to add the appropriate sign if w is
721 * an odd integer.
722 */
723 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
724 if (iw > 0.0)
725 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
726 else
727 return PyFloat_FromDouble(iw_is_odd ?
728 copysign(0.0, iv) : 0.0);
729 }
730 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
731 (already dealt with above), and an error
732 if w is negative. */
733 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
734 if (iw < 0.0) {
735 PyErr_SetString(PyExc_ZeroDivisionError,
736 "0.0 cannot be raised to a "
737 "negative power");
738 return NULL;
739 }
740 /* use correct sign if iw is odd */
741 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
742 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (iv < 0.0) {
745 /* Whether this is an error is a mess, and bumps into libm
746 * bugs so we have to figure it out ourselves.
747 */
748 if (iw != floor(iw)) {
749 /* Negative numbers raised to fractional powers
750 * become complex.
751 */
752 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
753 }
754 /* iw is an exact integer, albeit perhaps a very large
755 * one. Replace iv by its absolute value and remember
756 * to negate the pow result if iw is odd.
757 */
758 iv = -iv;
759 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
760 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
763 /* (-1) ** large_integer also ends up here. Here's an
764 * extract from the comments for the previous
765 * implementation explaining why this special case is
766 * necessary:
767 *
768 * -1 raised to an exact integer should never be exceptional.
769 * Alas, some libms (chiefly glibc as of early 2003) return
770 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
771 * happen to be representable in a *C* integer. That's a
772 * bug.
773 */
774 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
775 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 /* Now iv and iw are finite, iw is nonzero, and iv is
778 * positive and not equal to 1.0. We finally allow
779 * the platform pow to step in and do the rest.
780 */
781 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 ix = pow(iv, iw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 Py_ADJUST_ERANGE1(ix);
784 if (negate_result)
785 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (errno != 0) {
788 /* We don't expect any errno value other than ERANGE, but
789 * the range of libm bugs appears unbounded.
790 */
791 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
792 PyExc_ValueError);
793 return NULL;
794 }
795 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000796}
797
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000798#undef DOUBLE_IS_ODD_INTEGER
799
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000800static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000801float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000804}
805
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000806static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000807float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000810}
811
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000812static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000813float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000816}
817
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200818/*[clinic input]
819float.is_integer
820
821Return True if the float is an integer.
822[clinic start generated code]*/
823
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000824static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200825float_is_integer_impl(PyObject *self)
826/*[clinic end generated code: output=7112acf95a4d31ea input=311810d3f777e10d]*/
Christian Heimes53876d92008-04-19 00:31:39 +0000827{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200828 double x = PyFloat_AsDouble(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 PyObject *o;
830
831 if (x == -1.0 && PyErr_Occurred())
832 return NULL;
833 if (!Py_IS_FINITE(x))
834 Py_RETURN_FALSE;
835 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 o = (floor(x) == x) ? Py_True : Py_False;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 if (errno != 0) {
838 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
839 PyExc_ValueError);
840 return NULL;
841 }
842 Py_INCREF(o);
843 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000844}
845
846#if 0
847static PyObject *
848float_is_inf(PyObject *v)
849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 double x = PyFloat_AsDouble(v);
851 if (x == -1.0 && PyErr_Occurred())
852 return NULL;
853 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000854}
855
856static PyObject *
857float_is_nan(PyObject *v)
858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 double x = PyFloat_AsDouble(v);
860 if (x == -1.0 && PyErr_Occurred())
861 return NULL;
862 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000863}
864
865static PyObject *
866float_is_finite(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_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000872}
873#endif
874
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200875/*[clinic input]
876float.__trunc__
877
878Return the Integral closest to x between 0 and x.
879[clinic start generated code]*/
880
Christian Heimes53876d92008-04-19 00:31:39 +0000881static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200882float___trunc___impl(PyObject *self)
883/*[clinic end generated code: output=dd3e289dd4c6b538 input=591b9ba0d650fdff]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000884{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200885 double x = PyFloat_AsDouble(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 (void)modf(x, &wholepart);
889 /* Try to get out cheap if this fits in a Python int. The attempt
890 * to cast to long must be protected, as C doesn't define what
891 * happens if the double is too big to fit in a long. Some rare
892 * systems raise an exception then (RISCOS was mentioned as one,
893 * and someone using a non-default option on Sun also bumped into
894 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
895 * still be vulnerable: if a long has more bits of precision than
896 * a double, casting MIN/MAX to double may yield an approximation,
897 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
898 * yield true from the C expression wholepart<=LONG_MAX, despite
899 * that wholepart is actually greater than LONG_MAX.
900 */
901 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
902 const long aslong = (long)wholepart;
903 return PyLong_FromLong(aslong);
904 }
905 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000906}
907
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +0300908/*[clinic input]
909float.__floor__
910
911Return the floor as an Integral.
912[clinic start generated code]*/
913
914static PyObject *
915float___floor___impl(PyObject *self)
916/*[clinic end generated code: output=e0551dbaea8c01d1 input=77bb13eb12e268df]*/
917{
918 double x = PyFloat_AS_DOUBLE(self);
919 return PyLong_FromDouble(floor(x));
920}
921
922/*[clinic input]
923float.__ceil__
924
925Return the ceiling as an Integral.
926[clinic start generated code]*/
927
928static PyObject *
929float___ceil___impl(PyObject *self)
930/*[clinic end generated code: output=a2fd8858f73736f9 input=79e41ae94aa0a516]*/
931{
932 double x = PyFloat_AS_DOUBLE(self);
933 return PyLong_FromDouble(ceil(x));
934}
935
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000936/* double_round: rounds a finite double to the closest multiple of
937 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
938 ndigits <= 323). Returns a Python float, or sets a Python error and
939 returns NULL on failure (OverflowError and memory errors are possible). */
940
941#ifndef PY_NO_SHORT_FLOAT_REPR
942/* version of double_round that uses the correctly-rounded string<->double
943 conversions from Python/dtoa.c */
944
945static PyObject *
946double_round(double x, int ndigits) {
947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 double rounded;
949 Py_ssize_t buflen, mybuflen=100;
950 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
951 int decpt, sign;
952 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000953 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000956 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000958 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 if (buf == NULL) {
960 PyErr_NoMemory();
961 return NULL;
962 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
965 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
966 buflen = buf_end - buf;
967 if (buflen + 8 > mybuflen) {
968 mybuflen = buflen+8;
969 mybuf = (char *)PyMem_Malloc(mybuflen);
970 if (mybuf == NULL) {
971 PyErr_NoMemory();
972 goto exit;
973 }
974 }
975 /* copy buf to mybuf, adding exponent, sign and leading 0 */
976 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
977 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 /* and convert the resulting string back to a double */
980 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000981 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000983 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 if (errno == ERANGE && fabs(rounded) >= 1.)
985 PyErr_SetString(PyExc_OverflowError,
986 "rounded value too large to represent");
987 else
988 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 /* done computing value; now clean up */
991 if (mybuf != shortbuf)
992 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000993 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 _Py_dg_freedtoa(buf);
995 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000996}
997
998#else /* PY_NO_SHORT_FLOAT_REPR */
999
1000/* fallback version, to be used when correctly rounded binary<->decimal
1001 conversions aren't available */
1002
1003static PyObject *
1004double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 double pow1, pow2, y, z;
1006 if (ndigits >= 0) {
1007 if (ndigits > 22) {
1008 /* pow1 and pow2 are each safe from overflow, but
1009 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
1010 pow1 = pow(10.0, (double)(ndigits-22));
1011 pow2 = 1e22;
1012 }
1013 else {
1014 pow1 = pow(10.0, (double)ndigits);
1015 pow2 = 1.0;
1016 }
1017 y = (x*pow1)*pow2;
1018 /* if y overflows, then rounded value is exactly x */
1019 if (!Py_IS_FINITE(y))
1020 return PyFloat_FromDouble(x);
1021 }
1022 else {
1023 pow1 = pow(10.0, (double)-ndigits);
1024 pow2 = 1.0; /* unused; silences a gcc compiler warning */
1025 y = x / pow1;
1026 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 z = round(y);
1029 if (fabs(y-z) == 0.5)
1030 /* halfway between two integers; use round-half-even */
1031 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 if (ndigits >= 0)
1034 z = (z / pow2) / pow1;
1035 else
1036 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 /* if computation resulted in overflow, raise OverflowError */
1039 if (!Py_IS_FINITE(z)) {
1040 PyErr_SetString(PyExc_OverflowError,
1041 "overflow occurred during round");
1042 return NULL;
1043 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001046}
1047
1048#endif /* PY_NO_SHORT_FLOAT_REPR */
1049
1050/* round a Python float v to the closest multiple of 10**-ndigits */
1051
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001052/*[clinic input]
1053float.__round__
1054
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001055 ndigits as o_ndigits: object = None
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001056 /
1057
1058Return the Integral closest to x, rounding half toward even.
1059
1060When an argument is passed, work like built-in round(x, ndigits).
1061[clinic start generated code]*/
1062
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001063static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001064float___round___impl(PyObject *self, PyObject *o_ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001065/*[clinic end generated code: output=374c36aaa0f13980 input=fc0fe25924fbc9ed]*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 double x, rounded;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001069
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001070 x = PyFloat_AsDouble(self);
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001071 if (o_ndigits == Py_None) {
Steve Dowercb39d1f2015-04-15 16:10:59 -04001072 /* single-argument round or with None ndigits:
1073 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 rounded = round(x);
1075 if (fabs(x-rounded) == 0.5)
1076 /* halfway case: round to even */
1077 rounded = 2.0*round(x/2.0);
1078 return PyLong_FromDouble(rounded);
1079 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 /* interpret second argument as a Py_ssize_t; clips on overflow */
1082 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1083 if (ndigits == -1 && PyErr_Occurred())
1084 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 /* nans and infinities round to themselves */
1087 if (!Py_IS_FINITE(x))
1088 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1091 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1092 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001093#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1094#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 if (ndigits > NDIGITS_MAX)
1096 /* return x */
1097 return PyFloat_FromDouble(x);
1098 else if (ndigits < NDIGITS_MIN)
1099 /* return 0.0, but with sign of x */
1100 return PyFloat_FromDouble(0.0*x);
1101 else
1102 /* finite x, and ndigits is not unreasonably large */
1103 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001104#undef NDIGITS_MAX
1105#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001106}
1107
1108static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001109float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 if (PyFloat_CheckExact(v))
1112 Py_INCREF(v);
1113 else
1114 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1115 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001116}
1117
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001118/*[clinic input]
1119float.conjugate
1120
1121Return self, the complex conjugate of any float.
1122[clinic start generated code]*/
1123
1124static PyObject *
1125float_conjugate_impl(PyObject *self)
1126/*[clinic end generated code: output=8ca292c2479194af input=82ba6f37a9ff91dd]*/
1127{
1128 return float_float(self);
1129}
1130
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001131/* turn ASCII hex characters into integer values and vice versa */
1132
1133static char
1134char_from_hex(int x)
1135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001137 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001138}
1139
1140static int
1141hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 int x;
1143 switch(c) {
1144 case '0':
1145 x = 0;
1146 break;
1147 case '1':
1148 x = 1;
1149 break;
1150 case '2':
1151 x = 2;
1152 break;
1153 case '3':
1154 x = 3;
1155 break;
1156 case '4':
1157 x = 4;
1158 break;
1159 case '5':
1160 x = 5;
1161 break;
1162 case '6':
1163 x = 6;
1164 break;
1165 case '7':
1166 x = 7;
1167 break;
1168 case '8':
1169 x = 8;
1170 break;
1171 case '9':
1172 x = 9;
1173 break;
1174 case 'a':
1175 case 'A':
1176 x = 10;
1177 break;
1178 case 'b':
1179 case 'B':
1180 x = 11;
1181 break;
1182 case 'c':
1183 case 'C':
1184 x = 12;
1185 break;
1186 case 'd':
1187 case 'D':
1188 x = 13;
1189 break;
1190 case 'e':
1191 case 'E':
1192 x = 14;
1193 break;
1194 case 'f':
1195 case 'F':
1196 x = 15;
1197 break;
1198 default:
1199 x = -1;
1200 break;
1201 }
1202 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001203}
1204
1205/* convert a float to a hexadecimal string */
1206
1207/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1208 of the form 4k+1. */
1209#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1210
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001211/*[clinic input]
1212float.hex
1213
1214Return a hexadecimal representation of a floating-point number.
1215
1216>>> (-0.1).hex()
1217'-0x1.999999999999ap-4'
1218>>> 3.14159.hex()
1219'0x1.921f9f01b866ep+1'
1220[clinic start generated code]*/
1221
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001222static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001223float_hex_impl(PyObject *self)
1224/*[clinic end generated code: output=0ebc9836e4d302d4 input=bec1271a33d47e67]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 double x, m;
1227 int e, shift, i, si, esign;
1228 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1229 trailing NUL byte. */
1230 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001231
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001232 CONVERT_TO_DOUBLE(self, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001235 return float_repr((PyFloatObject *)self);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001238 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 return PyUnicode_FromString("-0x0.0p+0");
1240 else
1241 return PyUnicode_FromString("0x0.0p+0");
1242 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001245 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 m = ldexp(m, shift);
1247 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 si = 0;
1250 s[si] = char_from_hex((int)m);
1251 si++;
1252 m -= (int)m;
1253 s[si] = '.';
1254 si++;
1255 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1256 m *= 16.0;
1257 s[si] = char_from_hex((int)m);
1258 si++;
1259 m -= (int)m;
1260 }
1261 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (e < 0) {
1264 esign = (int)'-';
1265 e = -e;
1266 }
1267 else
1268 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 if (x < 0.0)
1271 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1272 else
1273 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001274}
1275
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001276/* Convert a hexadecimal string to a float. */
1277
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001278/*[clinic input]
1279@classmethod
1280float.fromhex
1281
1282 string: object
1283 /
1284
1285Create a floating-point number from a hexadecimal string.
1286
1287>>> float.fromhex('0x1.ffffp10')
12882047.984375
1289>>> float.fromhex('-0x1p-1074')
1290-5e-324
1291[clinic start generated code]*/
1292
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001293static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001294float_fromhex(PyTypeObject *type, PyObject *string)
1295/*[clinic end generated code: output=46c0274d22b78e82 input=0407bebd354bca89]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001296{
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001297 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 double x;
1299 long exp, top_exp, lsb, key_digit;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001300 const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 int half_eps, digit, round_up, negate=0;
1302 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 /*
1305 * For the sake of simplicity and correctness, we impose an artificial
1306 * limit on ndigits, the total number of hex digits in the coefficient
1307 * The limit is chosen to ensure that, writing exp for the exponent,
1308 *
1309 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1310 * guaranteed to overflow (provided it's nonzero)
1311 *
1312 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1313 * guaranteed to underflow to 0.
1314 *
1315 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1316 * overflow in the calculation of exp and top_exp below.
1317 *
1318 * More specifically, ndigits is assumed to satisfy the following
1319 * inequalities:
1320 *
1321 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1322 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1323 *
1324 * If either of these inequalities is not satisfied, a ValueError is
1325 * raised. Otherwise, write x for the value of the hex string, and
1326 * assume x is nonzero. Then
1327 *
1328 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1329 *
1330 * Now if exp > LONG_MAX/2 then:
1331 *
1332 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1333 * = DBL_MAX_EXP
1334 *
1335 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1336 * double, so overflows. If exp < LONG_MIN/2, then
1337 *
1338 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1339 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1340 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1341 *
1342 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1343 * when converted to a C double.
1344 *
1345 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1346 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1347 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001348
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001349 s = PyUnicode_AsUTF8AndSize(string, &length);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 if (s == NULL)
1351 return NULL;
1352 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 /********************
1355 * Parse the string *
1356 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 /* leading whitespace */
1359 while (Py_ISSPACE(*s))
1360 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 /* infinities and nans */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001363 x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 if (coeff_end != s) {
1365 s = coeff_end;
1366 goto finished;
1367 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 /* optional sign */
1370 if (*s == '-') {
1371 s++;
1372 negate = 1;
1373 }
1374 else if (*s == '+')
1375 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 /* [0x] */
1378 s_store = s;
1379 if (*s == '0') {
1380 s++;
1381 if (*s == 'x' || *s == 'X')
1382 s++;
1383 else
1384 s = s_store;
1385 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 /* coefficient: <integer> [. <fraction>] */
1388 coeff_start = s;
1389 while (hex_from_char(*s) >= 0)
1390 s++;
1391 s_store = s;
1392 if (*s == '.') {
1393 s++;
1394 while (hex_from_char(*s) >= 0)
1395 s++;
1396 coeff_end = s-1;
1397 }
1398 else
1399 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 /* ndigits = total # of hex digits; fdigits = # after point */
1402 ndigits = coeff_end - coeff_start;
1403 fdigits = coeff_end - s_store;
1404 if (ndigits == 0)
1405 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001406 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1407 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 /* [p <exponent>] */
1411 if (*s == 'p' || *s == 'P') {
1412 s++;
1413 exp_start = s;
1414 if (*s == '-' || *s == '+')
1415 s++;
1416 if (!('0' <= *s && *s <= '9'))
1417 goto parse_error;
1418 s++;
1419 while ('0' <= *s && *s <= '9')
1420 s++;
1421 exp = strtol(exp_start, NULL, 10);
1422 }
1423 else
1424 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001425
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001426/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1428 coeff_end-(j) : \
1429 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 /*******************************************
1432 * Compute rounded value of the hex string *
1433 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 /* Discard leading zeros, and catch extreme overflow and underflow */
1436 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1437 ndigits--;
1438 if (ndigits == 0 || exp < LONG_MIN/2) {
1439 x = 0.0;
1440 goto finished;
1441 }
1442 if (exp > LONG_MAX/2)
1443 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 /* Adjust exponent for fractional part. */
1446 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1449 top_exp = exp + 4*((long)ndigits - 1);
1450 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1451 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 /* catch almost all nonextreme cases of overflow and underflow here */
1454 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1455 x = 0.0;
1456 goto finished;
1457 }
1458 if (top_exp > DBL_MAX_EXP)
1459 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 /* lsb = exponent of least significant bit of the *rounded* value.
1462 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001463 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 x = 0.0;
1466 if (exp >= lsb) {
1467 /* no rounding required */
1468 for (i = ndigits-1; i >= 0; i--)
1469 x = 16.0*x + HEX_DIGIT(i);
1470 x = ldexp(x, (int)(exp));
1471 goto finished;
1472 }
1473 /* rounding required. key_digit is the index of the hex digit
1474 containing the first bit to be rounded away. */
1475 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1476 key_digit = (lsb - exp - 1) / 4;
1477 for (i = ndigits-1; i > key_digit; i--)
1478 x = 16.0*x + HEX_DIGIT(i);
1479 digit = HEX_DIGIT(key_digit);
1480 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1483 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1484 if ((digit & half_eps) != 0) {
1485 round_up = 0;
1486 if ((digit & (3*half_eps-1)) != 0 ||
1487 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1488 round_up = 1;
1489 else
1490 for (i = key_digit-1; i >= 0; i--)
1491 if (HEX_DIGIT(i) != 0) {
1492 round_up = 1;
1493 break;
1494 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001495 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 x += 2*half_eps;
1497 if (top_exp == DBL_MAX_EXP &&
1498 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1499 /* overflow corner case: pre-rounded value <
1500 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1501 goto overflow_error;
1502 }
1503 }
1504 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001505
1506 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 /* optional trailing whitespace leading to the end of the string */
1508 while (Py_ISSPACE(*s))
1509 s++;
1510 if (s != s_end)
1511 goto parse_error;
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001512 result = PyFloat_FromDouble(negate ? -x : x);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001513 if (type != &PyFloat_Type && result != NULL) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +02001514 Py_SETREF(result, _PyObject_CallOneArg((PyObject *)type, result));
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001515 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001517
1518 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 PyErr_SetString(PyExc_OverflowError,
1520 "hexadecimal value too large to represent as a float");
1521 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001522
1523 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 PyErr_SetString(PyExc_ValueError,
1525 "invalid hexadecimal floating-point string");
1526 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001527
1528 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 PyErr_SetString(PyExc_ValueError,
1530 "hexadecimal string too long to convert");
1531 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001532}
1533
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001534/*[clinic input]
1535float.as_integer_ratio
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001536
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001537Return integer ratio.
1538
1539Return a pair of integers, whose ratio is exactly equal to the original float
1540and with a positive denominator.
1541
1542Raise OverflowError on infinities and a ValueError on NaNs.
1543
1544>>> (10.0).as_integer_ratio()
1545(10, 1)
1546>>> (0.0).as_integer_ratio()
1547(0, 1)
1548>>> (-.25).as_integer_ratio()
1549(-1, 4)
1550[clinic start generated code]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001551
Christian Heimes26855632008-01-27 23:50:43 +00001552static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001553float_as_integer_ratio_impl(PyObject *self)
1554/*[clinic end generated code: output=65f25f0d8d30a712 input=e21d08b4630c2e44]*/
Christian Heimes26855632008-01-27 23:50:43 +00001555{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001556 double self_double;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 double float_part;
1558 int exponent;
1559 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 PyObject *py_exponent = NULL;
1562 PyObject *numerator = NULL;
1563 PyObject *denominator = NULL;
1564 PyObject *result_pair = NULL;
1565 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001566
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001567 CONVERT_TO_DOUBLE(self, self_double);
Christian Heimes26855632008-01-27 23:50:43 +00001568
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001569 if (Py_IS_INFINITY(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001570 PyErr_SetString(PyExc_OverflowError,
1571 "cannot convert Infinity to integer ratio");
1572 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001574 if (Py_IS_NAN(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001575 PyErr_SetString(PyExc_ValueError,
1576 "cannot convert NaN to integer ratio");
1577 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 }
Christian Heimes26855632008-01-27 23:50:43 +00001579
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001580 float_part = frexp(self_double, &exponent); /* self_double == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1583 float_part *= 2.0;
1584 exponent--;
1585 }
1586 /* self == float_part * 2**exponent exactly and float_part is integral.
1587 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1588 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 numerator = PyLong_FromDouble(float_part);
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001591 if (numerator == NULL)
1592 goto error;
1593 denominator = PyLong_FromLong(1);
1594 if (denominator == NULL)
1595 goto error;
1596 py_exponent = PyLong_FromLong(Py_ABS(exponent));
1597 if (py_exponent == NULL)
1598 goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 /* fold in 2**exponent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 if (exponent > 0) {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001602 Py_SETREF(numerator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001603 long_methods->nb_lshift(numerator, py_exponent));
1604 if (numerator == NULL)
1605 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 }
1607 else {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001608 Py_SETREF(denominator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001609 long_methods->nb_lshift(denominator, py_exponent));
1610 if (denominator == NULL)
1611 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 }
1613
1614 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001615
Christian Heimes26855632008-01-27 23:50:43 +00001616error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 Py_XDECREF(py_exponent);
1618 Py_XDECREF(denominator);
1619 Py_XDECREF(numerator);
1620 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001621}
1622
Jeremy Hylton938ace62002-07-17 16:30:39 +00001623static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001624float_subtype_new(PyTypeObject *type, PyObject *x);
1625
1626/*[clinic input]
1627@classmethod
1628float.__new__ as float_new
Serhiy Storchakaba85d692017-03-30 09:09:41 +03001629 x: object(c_default="_PyLong_Zero") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001630 /
1631
1632Convert a string or number to a floating point number, if possible.
1633[clinic start generated code]*/
Guido van Rossumbef14172001-08-29 15:47:46 +00001634
Tim Peters6d6c1a32001-08-02 04:15:00 +00001635static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001636float_new_impl(PyTypeObject *type, PyObject *x)
Serhiy Storchakabae68812017-04-05 12:00:42 +03001637/*[clinic end generated code: output=ccf1e8dc460ba6ba input=540ee77c204ff87a]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00001638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 if (type != &PyFloat_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001640 return float_subtype_new(type, x); /* Wimp out */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 /* If it's a string, but not a string subclass, use
1642 PyFloat_FromString. */
1643 if (PyUnicode_CheckExact(x))
1644 return PyFloat_FromString(x);
1645 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001646}
1647
Guido van Rossumbef14172001-08-29 15:47:46 +00001648/* Wimpy, slow approach to tp_new calls for subtypes of float:
1649 first create a regular float from whatever arguments we got,
1650 then allocate a subtype instance and initialize its ob_fval
1651 from the regular float. The regular float is then thrown away.
1652*/
1653static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001654float_subtype_new(PyTypeObject *type, PyObject *x)
Guido van Rossumbef14172001-08-29 15:47:46 +00001655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 assert(PyType_IsSubtype(type, &PyFloat_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001659 tmp = float_new_impl(&PyFloat_Type, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 if (tmp == NULL)
1661 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001662 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 newobj = type->tp_alloc(type, 0);
1664 if (newobj == NULL) {
1665 Py_DECREF(tmp);
1666 return NULL;
1667 }
1668 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1669 Py_DECREF(tmp);
1670 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001671}
1672
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001673/*[clinic input]
1674float.__getnewargs__
1675[clinic start generated code]*/
1676
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001677static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001678float___getnewargs___impl(PyObject *self)
1679/*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001680{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001681 return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001682}
1683
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001684/* this is for the benefit of the pack/unpack routines below */
1685
1686typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001688} float_format_type;
1689
1690static float_format_type double_format, float_format;
1691static float_format_type detected_double_format, detected_float_format;
1692
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001693/*[clinic input]
1694@classmethod
1695float.__getformat__
1696
1697 typestr: str
1698 Must be 'double' or 'float'.
1699 /
1700
1701You probably don't want to use this function.
1702
1703It exists mainly to be used in Python's test suite.
1704
1705This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
1706little-endian' best describes the format of floating point numbers used by the
1707C type named by typestr.
1708[clinic start generated code]*/
1709
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001710static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001711float___getformat___impl(PyTypeObject *type, const char *typestr)
1712/*[clinic end generated code: output=2bfb987228cc9628 input=d5a52600f835ad67]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001715
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001716 if (strcmp(typestr, "double") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 r = double_format;
1718 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001719 else if (strcmp(typestr, "float") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 r = float_format;
1721 }
1722 else {
1723 PyErr_SetString(PyExc_ValueError,
1724 "__getformat__() argument 1 must be "
1725 "'double' or 'float'");
1726 return NULL;
1727 }
1728
1729 switch (r) {
1730 case unknown_format:
1731 return PyUnicode_FromString("unknown");
1732 case ieee_little_endian_format:
1733 return PyUnicode_FromString("IEEE, little-endian");
1734 case ieee_big_endian_format:
1735 return PyUnicode_FromString("IEEE, big-endian");
1736 default:
Victor Stinner04394df2019-11-18 17:39:48 +01001737 PyErr_SetString(PyExc_RuntimeError,
1738 "insane float_format or double_format");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 return NULL;
1740 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001741}
1742
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001743/*[clinic input]
1744@classmethod
1745float.__set_format__
1746
1747 typestr: str
1748 Must be 'double' or 'float'.
1749 fmt: str
1750 Must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian',
1751 and in addition can only be one of the latter two if it appears to
1752 match the underlying C reality.
1753 /
1754
1755You probably don't want to use this function.
1756
1757It exists mainly to be used in Python's test suite.
1758
1759Override the automatic determination of C-level floating point type.
1760This affects how floats are converted to and from binary strings.
1761[clinic start generated code]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001762
1763static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001764float___set_format___impl(PyTypeObject *type, const char *typestr,
1765 const char *fmt)
1766/*[clinic end generated code: output=504460f5dc85acbd input=5306fa2b81a997e4]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 float_format_type f;
1769 float_format_type detected;
1770 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 if (strcmp(typestr, "double") == 0) {
1773 p = &double_format;
1774 detected = detected_double_format;
1775 }
1776 else if (strcmp(typestr, "float") == 0) {
1777 p = &float_format;
1778 detected = detected_float_format;
1779 }
1780 else {
1781 PyErr_SetString(PyExc_ValueError,
1782 "__setformat__() argument 1 must "
1783 "be 'double' or 'float'");
1784 return NULL;
1785 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001786
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001787 if (strcmp(fmt, "unknown") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 f = unknown_format;
1789 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001790 else if (strcmp(fmt, "IEEE, little-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 f = ieee_little_endian_format;
1792 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001793 else if (strcmp(fmt, "IEEE, big-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 f = ieee_big_endian_format;
1795 }
1796 else {
1797 PyErr_SetString(PyExc_ValueError,
1798 "__setformat__() argument 2 must be "
1799 "'unknown', 'IEEE, little-endian' or "
1800 "'IEEE, big-endian'");
1801 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 if (f != unknown_format && f != detected) {
1806 PyErr_Format(PyExc_ValueError,
1807 "can only set %s format to 'unknown' or the "
1808 "detected platform value", typestr);
1809 return NULL;
1810 }
1811
1812 *p = f;
1813 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001814}
1815
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001816static PyObject *
1817float_getreal(PyObject *v, void *closure)
1818{
1819 return float_float(v);
1820}
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001821
Guido van Rossumb43daf72007-08-01 18:08:08 +00001822static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001823float_getimag(PyObject *v, void *closure)
Guido van Rossumb43daf72007-08-01 18:08:08 +00001824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001826}
1827
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001828/*[clinic input]
1829float.__format__
1830
1831 format_spec: unicode
1832 /
1833
1834Formats the float according to format_spec.
1835[clinic start generated code]*/
1836
Eric Smith8c663262007-08-25 02:26:07 +00001837static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001838float___format___impl(PyObject *self, PyObject *format_spec)
1839/*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/
Eric Smith8c663262007-08-25 02:26:07 +00001840{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001841 _PyUnicodeWriter writer;
1842 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001843
Victor Stinner8f674cc2013-04-17 23:02:17 +02001844 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001845 ret = _PyFloat_FormatAdvancedWriter(
1846 &writer,
1847 self,
1848 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1849 if (ret == -1) {
1850 _PyUnicodeWriter_Dealloc(&writer);
1851 return NULL;
1852 }
1853 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001854}
1855
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001856static PyMethodDef float_methods[] = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001857 FLOAT_CONJUGATE_METHODDEF
1858 FLOAT___TRUNC___METHODDEF
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +03001859 FLOAT___FLOOR___METHODDEF
1860 FLOAT___CEIL___METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001861 FLOAT___ROUND___METHODDEF
1862 FLOAT_AS_INTEGER_RATIO_METHODDEF
1863 FLOAT_FROMHEX_METHODDEF
1864 FLOAT_HEX_METHODDEF
1865 FLOAT_IS_INTEGER_METHODDEF
Christian Heimes53876d92008-04-19 00:31:39 +00001866#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001868 "Return True if the float is positive or negative infinite."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001870 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001872 "Return True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001873#endif
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001874 FLOAT___GETNEWARGS___METHODDEF
1875 FLOAT___GETFORMAT___METHODDEF
1876 FLOAT___SET_FORMAT___METHODDEF
1877 FLOAT___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001879};
1880
Guido van Rossumb43daf72007-08-01 18:08:08 +00001881static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 {"real",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001883 float_getreal, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001884 "the real part of a complex number",
1885 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 {"imag",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001887 float_getimag, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001888 "the imaginary part of a complex number",
1889 NULL},
1890 {NULL} /* Sentinel */
1891};
1892
Tim Peters6d6c1a32001-08-02 04:15:00 +00001893
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001894static PyNumberMethods float_as_number = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001895 float_add, /* nb_add */
1896 float_sub, /* nb_subtract */
1897 float_mul, /* nb_multiply */
1898 float_rem, /* nb_remainder */
1899 float_divmod, /* nb_divmod */
1900 float_pow, /* nb_power */
1901 (unaryfunc)float_neg, /* nb_negative */
1902 float_float, /* nb_positive */
1903 (unaryfunc)float_abs, /* nb_absolute */
1904 (inquiry)float_bool, /* nb_bool */
1905 0, /* nb_invert */
1906 0, /* nb_lshift */
1907 0, /* nb_rshift */
1908 0, /* nb_and */
1909 0, /* nb_xor */
1910 0, /* nb_or */
1911 float___trunc___impl, /* nb_int */
1912 0, /* nb_reserved */
1913 float_float, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 0, /* nb_inplace_add */
1915 0, /* nb_inplace_subtract */
1916 0, /* nb_inplace_multiply */
1917 0, /* nb_inplace_remainder */
1918 0, /* nb_inplace_power */
1919 0, /* nb_inplace_lshift */
1920 0, /* nb_inplace_rshift */
1921 0, /* nb_inplace_and */
1922 0, /* nb_inplace_xor */
1923 0, /* nb_inplace_or */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001924 float_floor_div, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 float_div, /* nb_true_divide */
1926 0, /* nb_inplace_floor_divide */
1927 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001928};
1929
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001930PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1932 "float",
1933 sizeof(PyFloatObject),
1934 0,
1935 (destructor)float_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001936 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 0, /* tp_getattr */
1938 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001939 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 (reprfunc)float_repr, /* tp_repr */
1941 &float_as_number, /* tp_as_number */
1942 0, /* tp_as_sequence */
1943 0, /* tp_as_mapping */
1944 (hashfunc)float_hash, /* tp_hash */
1945 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001946 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 PyObject_GenericGetAttr, /* tp_getattro */
1948 0, /* tp_setattro */
1949 0, /* tp_as_buffer */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001950 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001951 float_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 0, /* tp_traverse */
1953 0, /* tp_clear */
1954 float_richcompare, /* tp_richcompare */
1955 0, /* tp_weaklistoffset */
1956 0, /* tp_iter */
1957 0, /* tp_iternext */
1958 float_methods, /* tp_methods */
1959 0, /* tp_members */
1960 float_getset, /* tp_getset */
1961 0, /* tp_base */
1962 0, /* tp_dict */
1963 0, /* tp_descr_get */
1964 0, /* tp_descr_set */
1965 0, /* tp_dictoffset */
1966 0, /* tp_init */
1967 0, /* tp_alloc */
1968 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001969};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001970
Victor Stinner1c8f0592013-07-22 22:24:54 +02001971int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001972_PyFloat_Init(void)
1973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 /* We attempt to determine if this machine is using IEEE
1975 floating point formats by peering at the bits of some
1976 carefully chosen values. If it looks like we are on an
1977 IEEE platform, the float packing/unpacking routines can
1978 just copy bits, if not they resort to arithmetic & shifts
1979 and masks. The shifts & masks approach works on all finite
1980 values, but what happens to infinities, NaNs and signed
1981 zeroes on packing is an accident, and attempting to unpack
1982 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 Note that if we're on some whacked-out platform which uses
1985 IEEE formats but isn't strictly little-endian or big-
1986 endian, we will fall back to the portable shifts & masks
1987 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001988
1989#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 {
1991 double x = 9006104071832581.0;
1992 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1993 detected_double_format = ieee_big_endian_format;
1994 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1995 detected_double_format = ieee_little_endian_format;
1996 else
1997 detected_double_format = unknown_format;
1998 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001999#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002001#endif
2002
2003#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 {
2005 float y = 16711938.0;
2006 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
2007 detected_float_format = ieee_big_endian_format;
2008 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
2009 detected_float_format = ieee_little_endian_format;
2010 else
2011 detected_float_format = unknown_format;
2012 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002013#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002015#endif
2016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 double_format = detected_double_format;
2018 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002021 if (FloatInfoType.tp_name == NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01002022 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02002023 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01002024 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002025 }
2026 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002027}
2028
Georg Brandl2ee470f2008-07-16 12:55:28 +00002029int
2030PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002031{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002032 PyFloatObject *f = free_list, *next;
2033 int i = numfree;
2034 while (f) {
2035 next = (PyFloatObject*) Py_TYPE(f);
2036 PyObject_FREE(f);
2037 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002039 free_list = NULL;
2040 numfree = 0;
2041 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00002042}
2043
2044void
Victor Stinnerbed48172019-08-27 00:12:32 +02002045_PyFloat_Fini(void)
Christian Heimes15ebc882008-02-04 18:48:49 +00002046{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002047 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002048}
Tim Peters9905b942003-03-20 20:53:32 +00002049
David Malcolm49526f42012-06-22 14:55:41 -04002050/* Print summary info about the state of the optimized allocator */
2051void
2052_PyFloat_DebugMallocStats(FILE *out)
2053{
2054 _PyDebugAllocatorStats(out,
2055 "free PyFloatObject",
2056 numfree, sizeof(PyFloatObject));
2057}
2058
2059
Tim Peters9905b942003-03-20 20:53:32 +00002060/*----------------------------------------------------------------------------
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002061 * _PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h.
2062 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
2063 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
2064 * We use:
2065 * bits = (unsigned short)f; Note the truncation
2066 * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
2067 * bits++;
2068 * }
Tim Peters9905b942003-03-20 20:53:32 +00002069 */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002070
2071int
2072_PyFloat_Pack2(double x, unsigned char *p, int le)
2073{
2074 unsigned char sign;
2075 int e;
2076 double f;
2077 unsigned short bits;
2078 int incr = 1;
2079
2080 if (x == 0.0) {
2081 sign = (copysign(1.0, x) == -1.0);
2082 e = 0;
2083 bits = 0;
2084 }
2085 else if (Py_IS_INFINITY(x)) {
2086 sign = (x < 0.0);
2087 e = 0x1f;
2088 bits = 0;
2089 }
2090 else if (Py_IS_NAN(x)) {
2091 /* There are 2046 distinct half-precision NaNs (1022 signaling and
2092 1024 quiet), but there are only two quiet NaNs that don't arise by
2093 quieting a signaling NaN; we get those by setting the topmost bit
2094 of the fraction field and clearing all other fraction bits. We
2095 choose the one with the appropriate sign. */
2096 sign = (copysign(1.0, x) == -1.0);
2097 e = 0x1f;
2098 bits = 512;
2099 }
2100 else {
2101 sign = (x < 0.0);
2102 if (sign) {
2103 x = -x;
2104 }
2105
2106 f = frexp(x, &e);
2107 if (f < 0.5 || f >= 1.0) {
2108 PyErr_SetString(PyExc_SystemError,
2109 "frexp() result out of range");
2110 return -1;
2111 }
2112
2113 /* Normalize f to be in the range [1.0, 2.0) */
2114 f *= 2.0;
2115 e--;
2116
2117 if (e >= 16) {
2118 goto Overflow;
2119 }
2120 else if (e < -25) {
2121 /* |x| < 2**-25. Underflow to zero. */
2122 f = 0.0;
2123 e = 0;
2124 }
2125 else if (e < -14) {
2126 /* |x| < 2**-14. Gradual underflow */
2127 f = ldexp(f, 14 + e);
2128 e = 0;
2129 }
2130 else /* if (!(e == 0 && f == 0.0)) */ {
2131 e += 15;
2132 f -= 1.0; /* Get rid of leading 1 */
2133 }
2134
2135 f *= 1024.0; /* 2**10 */
2136 /* Round to even */
2137 bits = (unsigned short)f; /* Note the truncation */
2138 assert(bits < 1024);
2139 assert(e < 31);
2140 if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2141 ++bits;
2142 if (bits == 1024) {
2143 /* The carry propagated out of a string of 10 1 bits. */
2144 bits = 0;
2145 ++e;
2146 if (e == 31)
2147 goto Overflow;
2148 }
2149 }
2150 }
2151
2152 bits |= (e << 10) | (sign << 15);
2153
2154 /* Write out result. */
2155 if (le) {
2156 p += 1;
2157 incr = -1;
2158 }
2159
2160 /* First byte */
2161 *p = (unsigned char)((bits >> 8) & 0xFF);
2162 p += incr;
2163
2164 /* Second byte */
2165 *p = (unsigned char)(bits & 0xFF);
2166
2167 return 0;
2168
2169 Overflow:
2170 PyErr_SetString(PyExc_OverflowError,
2171 "float too large to pack with e format");
2172 return -1;
2173}
2174
Tim Peters9905b942003-03-20 20:53:32 +00002175int
2176_PyFloat_Pack4(double x, unsigned char *p, int le)
2177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 if (float_format == unknown_format) {
2179 unsigned char sign;
2180 int e;
2181 double f;
2182 unsigned int fbits;
2183 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 if (le) {
2186 p += 3;
2187 incr = -1;
2188 }
Tim Peters9905b942003-03-20 20:53:32 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 if (x < 0) {
2191 sign = 1;
2192 x = -x;
2193 }
2194 else
2195 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 /* Normalize f to be in the range [1.0, 2.0) */
2200 if (0.5 <= f && f < 1.0) {
2201 f *= 2.0;
2202 e--;
2203 }
2204 else if (f == 0.0)
2205 e = 0;
2206 else {
2207 PyErr_SetString(PyExc_SystemError,
2208 "frexp() result out of range");
2209 return -1;
2210 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 if (e >= 128)
2213 goto Overflow;
2214 else if (e < -126) {
2215 /* Gradual underflow */
2216 f = ldexp(f, 126 + e);
2217 e = 0;
2218 }
2219 else if (!(e == 0 && f == 0.0)) {
2220 e += 127;
2221 f -= 1.0; /* Get rid of leading 1 */
2222 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 f *= 8388608.0; /* 2**23 */
2225 fbits = (unsigned int)(f + 0.5); /* Round */
2226 assert(fbits <= 8388608);
2227 if (fbits >> 23) {
2228 /* The carry propagated out of a string of 23 1 bits. */
2229 fbits = 0;
2230 ++e;
2231 if (e >= 255)
2232 goto Overflow;
2233 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 /* First byte */
2236 *p = (sign << 7) | (e >> 1);
2237 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 /* Second byte */
2240 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2241 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 /* Third byte */
2244 *p = (fbits >> 8) & 0xFF;
2245 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 /* Fourth byte */
2248 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 /* Done */
2251 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 }
2254 else {
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002255 float y = (float)x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002257
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002258 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002260
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002261 unsigned char s[sizeof(float)];
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002262 memcpy(s, &y, sizeof(float));
2263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if ((float_format == ieee_little_endian_format && !le)
2265 || (float_format == ieee_big_endian_format && le)) {
2266 p += 3;
2267 incr = -1;
2268 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 for (i = 0; i < 4; i++) {
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002271 *p = s[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 p += incr;
2273 }
2274 return 0;
2275 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002276 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 PyErr_SetString(PyExc_OverflowError,
2278 "float too large to pack with f format");
2279 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002280}
2281
2282int
2283_PyFloat_Pack8(double x, unsigned char *p, int le)
2284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 if (double_format == unknown_format) {
2286 unsigned char sign;
2287 int e;
2288 double f;
2289 unsigned int fhi, flo;
2290 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 if (le) {
2293 p += 7;
2294 incr = -1;
2295 }
Tim Peters9905b942003-03-20 20:53:32 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 if (x < 0) {
2298 sign = 1;
2299 x = -x;
2300 }
2301 else
2302 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 /* Normalize f to be in the range [1.0, 2.0) */
2307 if (0.5 <= f && f < 1.0) {
2308 f *= 2.0;
2309 e--;
2310 }
2311 else if (f == 0.0)
2312 e = 0;
2313 else {
2314 PyErr_SetString(PyExc_SystemError,
2315 "frexp() result out of range");
2316 return -1;
2317 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 if (e >= 1024)
2320 goto Overflow;
2321 else if (e < -1022) {
2322 /* Gradual underflow */
2323 f = ldexp(f, 1022 + e);
2324 e = 0;
2325 }
2326 else if (!(e == 0 && f == 0.0)) {
2327 e += 1023;
2328 f -= 1.0; /* Get rid of leading 1 */
2329 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2332 f *= 268435456.0; /* 2**28 */
2333 fhi = (unsigned int)f; /* Truncate */
2334 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 f -= (double)fhi;
2337 f *= 16777216.0; /* 2**24 */
2338 flo = (unsigned int)(f + 0.5); /* Round */
2339 assert(flo <= 16777216);
2340 if (flo >> 24) {
2341 /* The carry propagated out of a string of 24 1 bits. */
2342 flo = 0;
2343 ++fhi;
2344 if (fhi >> 28) {
2345 /* And it also progagated out of the next 28 bits. */
2346 fhi = 0;
2347 ++e;
2348 if (e >= 2047)
2349 goto Overflow;
2350 }
2351 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 /* First byte */
2354 *p = (sign << 7) | (e >> 4);
2355 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 /* Second byte */
2358 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2359 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 /* Third byte */
2362 *p = (fhi >> 16) & 0xFF;
2363 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 /* Fourth byte */
2366 *p = (fhi >> 8) & 0xFF;
2367 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 /* Fifth byte */
2370 *p = fhi & 0xFF;
2371 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 /* Sixth byte */
2374 *p = (flo >> 16) & 0xFF;
2375 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 /* Seventh byte */
2378 *p = (flo >> 8) & 0xFF;
2379 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 /* Eighth byte */
2382 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002383 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 /* Done */
2386 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 Overflow:
2389 PyErr_SetString(PyExc_OverflowError,
2390 "float too large to pack with d format");
2391 return -1;
2392 }
2393 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002394 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 if ((double_format == ieee_little_endian_format && !le)
2398 || (double_format == ieee_big_endian_format && le)) {
2399 p += 7;
2400 incr = -1;
2401 }
2402
2403 for (i = 0; i < 8; i++) {
2404 *p = *s++;
2405 p += incr;
2406 }
2407 return 0;
2408 }
Tim Peters9905b942003-03-20 20:53:32 +00002409}
2410
2411double
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002412_PyFloat_Unpack2(const unsigned char *p, int le)
2413{
2414 unsigned char sign;
2415 int e;
2416 unsigned int f;
2417 double x;
2418 int incr = 1;
2419
2420 if (le) {
2421 p += 1;
2422 incr = -1;
2423 }
2424
2425 /* First byte */
2426 sign = (*p >> 7) & 1;
2427 e = (*p & 0x7C) >> 2;
2428 f = (*p & 0x03) << 8;
2429 p += incr;
2430
2431 /* Second byte */
2432 f |= *p;
2433
2434 if (e == 0x1f) {
2435#ifdef PY_NO_SHORT_FLOAT_REPR
2436 if (f == 0) {
2437 /* Infinity */
2438 return sign ? -Py_HUGE_VAL : Py_HUGE_VAL;
2439 }
2440 else {
2441 /* NaN */
2442#ifdef Py_NAN
2443 return sign ? -Py_NAN : Py_NAN;
2444#else
2445 PyErr_SetString(
2446 PyExc_ValueError,
2447 "can't unpack IEEE 754 NaN "
2448 "on platform that does not support NaNs");
2449 return -1;
2450#endif /* #ifdef Py_NAN */
2451 }
2452#else
2453 if (f == 0) {
2454 /* Infinity */
2455 return _Py_dg_infinity(sign);
2456 }
2457 else {
2458 /* NaN */
2459 return _Py_dg_stdnan(sign);
2460 }
2461#endif /* #ifdef PY_NO_SHORT_FLOAT_REPR */
2462 }
2463
2464 x = (double)f / 1024.0;
2465
2466 if (e == 0) {
2467 e = -14;
2468 }
2469 else {
2470 x += 1.0;
2471 e -= 15;
2472 }
2473 x = ldexp(x, e);
2474
2475 if (sign)
2476 x = -x;
2477
2478 return x;
2479}
2480
2481double
Tim Peters9905b942003-03-20 20:53:32 +00002482_PyFloat_Unpack4(const unsigned char *p, int le)
2483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 if (float_format == unknown_format) {
2485 unsigned char sign;
2486 int e;
2487 unsigned int f;
2488 double x;
2489 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 if (le) {
2492 p += 3;
2493 incr = -1;
2494 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 /* First byte */
2497 sign = (*p >> 7) & 1;
2498 e = (*p & 0x7F) << 1;
2499 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 /* Second byte */
2502 e |= (*p >> 7) & 1;
2503 f = (*p & 0x7F) << 16;
2504 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 if (e == 255) {
2507 PyErr_SetString(
2508 PyExc_ValueError,
2509 "can't unpack IEEE 754 special value "
2510 "on non-IEEE platform");
2511 return -1;
2512 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 /* Third byte */
2515 f |= *p << 8;
2516 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 /* Fourth byte */
2519 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 /* XXX This sadly ignores Inf/NaN issues */
2524 if (e == 0)
2525 e = -126;
2526 else {
2527 x += 1.0;
2528 e -= 127;
2529 }
2530 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 if (sign)
2533 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 return x;
2536 }
2537 else {
2538 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 if ((float_format == ieee_little_endian_format && !le)
2541 || (float_format == ieee_big_endian_format && le)) {
2542 char buf[4];
2543 char *d = &buf[3];
2544 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 for (i = 0; i < 4; i++) {
2547 *d-- = *p++;
2548 }
2549 memcpy(&x, buf, 4);
2550 }
2551 else {
2552 memcpy(&x, p, 4);
2553 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 return x;
2556 }
Tim Peters9905b942003-03-20 20:53:32 +00002557}
2558
2559double
2560_PyFloat_Unpack8(const unsigned char *p, int le)
2561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 if (double_format == unknown_format) {
2563 unsigned char sign;
2564 int e;
2565 unsigned int fhi, flo;
2566 double x;
2567 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 if (le) {
2570 p += 7;
2571 incr = -1;
2572 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 /* First byte */
2575 sign = (*p >> 7) & 1;
2576 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 /* Second byte */
2581 e |= (*p >> 4) & 0xF;
2582 fhi = (*p & 0xF) << 24;
2583 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 if (e == 2047) {
2586 PyErr_SetString(
2587 PyExc_ValueError,
2588 "can't unpack IEEE 754 special value "
2589 "on non-IEEE platform");
2590 return -1.0;
2591 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 /* Third byte */
2594 fhi |= *p << 16;
2595 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 /* Fourth byte */
2598 fhi |= *p << 8;
2599 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 /* Fifth byte */
2602 fhi |= *p;
2603 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 /* Sixth byte */
2606 flo = *p << 16;
2607 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 /* Seventh byte */
2610 flo |= *p << 8;
2611 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 /* Eighth byte */
2614 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2617 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 if (e == 0)
2620 e = -1022;
2621 else {
2622 x += 1.0;
2623 e -= 1023;
2624 }
2625 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 if (sign)
2628 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 return x;
2631 }
2632 else {
2633 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 if ((double_format == ieee_little_endian_format && !le)
2636 || (double_format == ieee_big_endian_format && le)) {
2637 char buf[8];
2638 char *d = &buf[7];
2639 int i;
2640
2641 for (i = 0; i < 8; i++) {
2642 *d-- = *p++;
2643 }
2644 memcpy(&x, buf, 8);
2645 }
2646 else {
2647 memcpy(&x, p, 8);
2648 }
2649
2650 return x;
2651 }
Tim Peters9905b942003-03-20 20:53:32 +00002652}