blob: cc0ae8ce819086d92114f93592681cfbaffe0337 [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"
Victor Stinnere9e7d282020-02-12 22:54:42 +01007#include "pycore_dtoa.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Guido van Rossum3f5da241990-12-20 15:06:42 +00009#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000010#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Serhiy Storchakab5c51d32017-03-11 09:21:05 +020012/*[clinic input]
13class float "PyObject *" "&PyFloat_Type"
14[clinic start generated code]*/
15/*[clinic end generated code: output=da39a3ee5e6b4b0d input=dd0003f68f144284]*/
16
17#include "clinic/floatobject.c.h"
Guido van Rossum6923e131990-11-02 17:50:43 +000018
Mark Dickinsond19052c2010-06-27 18:19:09 +000019/* Special free list
Mark Dickinsond19052c2010-06-27 18:19:09 +000020 free_list is a singly-linked list of available PyFloatObjects, linked
21 via abuse of their ob_type members.
22*/
23
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000024#ifndef PyFloat_MAXFREELIST
25#define PyFloat_MAXFREELIST 100
26#endif
27static int numfree = 0;
Guido van Rossum3fce8831999-03-12 19:43:17 +000028static PyFloatObject *free_list = NULL;
29
Christian Heimes93852662007-12-01 12:22:32 +000030double
31PyFloat_GetMax(void)
32{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000034}
35
36double
37PyFloat_GetMin(void)
38{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000040}
41
Christian Heimesd32ed6f2008-01-14 18:49:24 +000042static PyTypeObject FloatInfoType;
43
44PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000045"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000046\n\
Raymond Hettinger71170742019-09-11 07:17:32 -070047A named tuple holding information about the float type. It contains low level\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000048information about the precision and internal representation. Please study\n\
49your system's :file:`float.h` for more information.");
50
51static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 {"max", "DBL_MAX -- maximum representable finite float"},
53 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
54 "is representable"},
55 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
56 "is representable"},
Stefano Taschini0301c9b2018-03-26 11:41:30 +020057 {"min", "DBL_MIN -- Minimum positive normalized float"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
59 "is a normalized float"},
60 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
61 "a normalized"},
Zackery Spytzfdc5a942020-05-24 04:03:52 -060062 {"dig", "DBL_DIG -- maximum number of decimal digits that "
63 "can be faithfully represented in a float"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
65 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
66 "representable float"},
67 {"radix", "FLT_RADIX -- radix of exponent"},
Zackery Spytzfdc5a942020-05-24 04:03:52 -060068 {"rounds", "FLT_ROUNDS -- rounding mode used for arithmetic "
69 "operations"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +000071};
72
73static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 "sys.float_info", /* name */
75 floatinfo__doc__, /* doc */
76 floatinfo_fields, /* fields */
77 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +000078};
79
Christian Heimes93852662007-12-01 12:22:32 +000080PyObject *
81PyFloat_GetInfo(void)
82{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 PyObject* floatinfo;
84 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +000085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 floatinfo = PyStructSequence_New(&FloatInfoType);
87 if (floatinfo == NULL) {
88 return NULL;
89 }
Christian Heimes93852662007-12-01 12:22:32 +000090
Christian Heimesd32ed6f2008-01-14 18:49:24 +000091#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +000093#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +000095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 SetDblFlag(DBL_MAX);
97 SetIntFlag(DBL_MAX_EXP);
98 SetIntFlag(DBL_MAX_10_EXP);
99 SetDblFlag(DBL_MIN);
100 SetIntFlag(DBL_MIN_EXP);
101 SetIntFlag(DBL_MIN_10_EXP);
102 SetIntFlag(DBL_DIG);
103 SetIntFlag(DBL_MANT_DIG);
104 SetDblFlag(DBL_EPSILON);
105 SetIntFlag(FLT_RADIX);
106 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000107#undef SetIntFlag
108#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109
110 if (PyErr_Occurred()) {
111 Py_CLEAR(floatinfo);
112 return NULL;
113 }
114 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000115}
116
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000117PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000118PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000119{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200120 PyFloatObject *op = free_list;
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000121 if (op != NULL) {
122 free_list = (PyFloatObject *) Py_TYPE(op);
123 numfree--;
124 } else {
125 op = (PyFloatObject*) PyObject_MALLOC(sizeof(PyFloatObject));
126 if (!op)
127 return PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 }
129 /* Inline PyObject_New */
Victor Stinnerb509d522018-11-23 14:27:38 +0100130 (void)PyObject_INIT(op, &PyFloat_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 op->ob_fval = fval;
132 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000133}
134
Brett Cannona721aba2016-09-09 14:57:09 -0700135static PyObject *
136float_from_string_inner(const char *s, Py_ssize_t len, void *obj)
137{
138 double x;
139 const char *end;
140 const char *last = s + len;
141 /* strip space */
142 while (s < last && Py_ISSPACE(*s)) {
143 s++;
144 }
145
146 while (s < last - 1 && Py_ISSPACE(last[-1])) {
147 last--;
148 }
149
150 /* We don't care about overflow or underflow. If the platform
151 * supports them, infinities and signed zeroes (on underflow) are
152 * fine. */
153 x = PyOS_string_to_double(s, (char **)&end, NULL);
154 if (end != last) {
155 PyErr_Format(PyExc_ValueError,
156 "could not convert string to float: "
157 "%R", obj);
158 return NULL;
159 }
160 else if (x == -1.0 && PyErr_Occurred()) {
161 return NULL;
162 }
163 else {
164 return PyFloat_FromDouble(x);
165 }
166}
167
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000168PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000169PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000170{
Brett Cannona721aba2016-09-09 14:57:09 -0700171 const char *s;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000172 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 Py_ssize_t len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200174 Py_buffer view = {NULL, NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200178 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000180 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200181 assert(PyUnicode_IS_ASCII(s_buffer));
182 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200183 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200184 assert(s != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000186 else if (PyBytes_Check(v)) {
187 s = PyBytes_AS_STRING(v);
188 len = PyBytes_GET_SIZE(v);
189 }
190 else if (PyByteArray_Check(v)) {
191 s = PyByteArray_AS_STRING(v);
192 len = PyByteArray_GET_SIZE(v);
193 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200194 else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
195 s = (const char *)view.buf;
196 len = view.len;
Martin Pantereeb896c2015-11-07 02:32:21 +0000197 /* Copy to NUL-terminated buffer. */
198 s_buffer = PyBytes_FromStringAndSize(s, len);
199 if (s_buffer == NULL) {
200 PyBuffer_Release(&view);
201 return NULL;
202 }
203 s = PyBytes_AS_STRING(s_buffer);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200204 }
205 else {
Ezio Melottia5b95992013-11-07 19:18:34 +0200206 PyErr_Format(PyExc_TypeError,
207 "float() argument must be a string or a number, not '%.200s'",
208 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 return NULL;
210 }
Brett Cannona721aba2016-09-09 14:57:09 -0700211 result = _Py_string_to_number_with_underscores(s, len, "float", v, v,
212 float_from_string_inner);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200213 PyBuffer_Release(&view);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000214 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000216}
217
Guido van Rossum234f9421993-06-17 12:35:49 +0000218static void
Fred Drakefd99de62000-07-09 05:02:18 +0000219float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 if (PyFloat_CheckExact(op)) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000222 if (numfree >= PyFloat_MAXFREELIST) {
223 PyObject_FREE(op);
224 return;
225 }
226 numfree++;
Victor Stinnerd2ec81a2020-02-07 09:17:07 +0100227 Py_SET_TYPE(op, (PyTypeObject *)free_list);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 free_list = op;
229 }
230 else
231 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000232}
233
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000234double
Fred Drakefd99de62000-07-09 05:02:18 +0000235PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 PyNumberMethods *nb;
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300238 PyObject *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 if (op == NULL) {
242 PyErr_BadArgument();
243 return -1;
244 }
Tim Petersd2364e82001-11-01 20:09:42 +0000245
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300246 if (PyFloat_Check(op)) {
247 return PyFloat_AS_DOUBLE(op);
248 }
249
250 nb = Py_TYPE(op)->tp_as_number;
251 if (nb == NULL || nb->nb_float == NULL) {
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300252 if (nb && nb->nb_index) {
253 PyObject *res = PyNumber_Index(op);
254 if (!res) {
255 return -1;
256 }
257 double val = PyLong_AsDouble(res);
258 Py_DECREF(res);
259 return val;
260 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300261 PyErr_Format(PyExc_TypeError, "must be real number, not %.50s",
Victor Stinner58ac7002020-02-07 03:04:21 +0100262 Py_TYPE(op)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 return -1;
264 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000265
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300266 res = (*nb->nb_float) (op);
267 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 return -1;
269 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300270 if (!PyFloat_CheckExact(res)) {
271 if (!PyFloat_Check(res)) {
272 PyErr_Format(PyExc_TypeError,
273 "%.50s.__float__ returned non-float (type %.50s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100274 Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name);
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300275 Py_DECREF(res);
276 return -1;
277 }
278 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
279 "%.50s.__float__ returned non-float (type %.50s). "
280 "The ability to return an instance of a strict subclass of float "
281 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner58ac7002020-02-07 03:04:21 +0100282 Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name)) {
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300283 Py_DECREF(res);
284 return -1;
285 }
286 }
Tim Petersd2364e82001-11-01 20:09:42 +0000287
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300288 val = PyFloat_AS_DOUBLE(res);
289 Py_DECREF(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000291}
292
Neil Schemenauer32117e52001-01-04 01:44:34 +0000293/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000294 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000295 set to NULL, and the function invoking this macro returns NULL. If
Serhiy Storchaka95949422013-08-27 19:40:23 +0300296 obj is not of float or int type, Py_NotImplemented is incref'ed,
Tim Peters77d8a4f2001-12-11 20:31:34 +0000297 stored in obj, and returned from the function invoking this macro.
298*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299#define CONVERT_TO_DOUBLE(obj, dbl) \
300 if (PyFloat_Check(obj)) \
301 dbl = PyFloat_AS_DOUBLE(obj); \
302 else if (convert_to_double(&(obj), &(dbl)) < 0) \
303 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000304
Eric Smith0923d1d2009-04-16 20:16:10 +0000305/* Methods */
306
Neil Schemenauer32117e52001-01-04 01:44:34 +0000307static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000308convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000309{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200310 PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 if (PyLong_Check(obj)) {
313 *dbl = PyLong_AsDouble(obj);
314 if (*dbl == -1.0 && PyErr_Occurred()) {
315 *v = NULL;
316 return -1;
317 }
318 }
319 else {
320 Py_INCREF(Py_NotImplemented);
321 *v = Py_NotImplemented;
322 return -1;
323 }
324 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000325}
326
Eric Smith0923d1d2009-04-16 20:16:10 +0000327static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000328float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000329{
330 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200331 char *buf;
332
333 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
334 'r', 0,
335 Py_DTSF_ADD_DOT_0,
336 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000337 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000338 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200339 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000340 PyMem_Free(buf);
341 return result;
342}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000343
Tim Peters307fa782004-09-23 08:06:40 +0000344/* Comparison is pretty much a nightmare. When comparing float to float,
345 * we do it as straightforwardly (and long-windedly) as conceivable, so
346 * that, e.g., Python x == y delivers the same result as the platform
347 * C x == y when x and/or y is a NaN.
348 * When mixing float with an integer type, there's no good *uniform* approach.
349 * Converting the double to an integer obviously doesn't work, since we
350 * may lose info from fractional bits. Converting the integer to a double
Serhiy Storchaka95949422013-08-27 19:40:23 +0300351 * also has two failure modes: (1) an int may trigger overflow (too
Tim Peters307fa782004-09-23 08:06:40 +0000352 * 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 +0200353 * 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 +0000354 * 63 bits of precision, but a C double probably has only 53), and then
355 * we can falsely claim equality when low-order integer bits are lost by
356 * coercion to double. So this part is painful too.
357 */
358
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000359static PyObject*
360float_richcompare(PyObject *v, PyObject *w, int op)
361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 double i, j;
363 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 assert(PyFloat_Check(v));
366 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 /* Switch on the type of w. Set i and j to doubles to be compared,
369 * and op to the richcomp to use.
370 */
371 if (PyFloat_Check(w))
372 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 else if (!Py_IS_FINITE(i)) {
375 if (PyLong_Check(w))
376 /* If i is an infinity, its magnitude exceeds any
377 * finite integer, so it doesn't matter which int we
378 * compare i with. If i is a NaN, similarly.
379 */
380 j = 0.0;
381 else
382 goto Unimplemented;
383 }
Tim Peters307fa782004-09-23 08:06:40 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 else if (PyLong_Check(w)) {
386 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
387 int wsign = _PyLong_Sign(w);
388 size_t nbits;
389 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 if (vsign != wsign) {
392 /* Magnitudes are irrelevant -- the signs alone
393 * determine the outcome.
394 */
395 i = (double)vsign;
396 j = (double)wsign;
397 goto Compare;
398 }
399 /* The signs are the same. */
400 /* Convert w to a double if it fits. In particular, 0 fits. */
401 nbits = _PyLong_NumBits(w);
402 if (nbits == (size_t)-1 && PyErr_Occurred()) {
403 /* This long is so large that size_t isn't big enough
404 * to hold the # of bits. Replace with little doubles
405 * that give the same outcome -- w is so large that
406 * its magnitude must exceed the magnitude of any
407 * finite float.
408 */
409 PyErr_Clear();
410 i = (double)vsign;
411 assert(wsign != 0);
412 j = wsign * 2.0;
413 goto Compare;
414 }
415 if (nbits <= 48) {
416 j = PyLong_AsDouble(w);
417 /* It's impossible that <= 48 bits overflowed. */
418 assert(j != -1.0 || ! PyErr_Occurred());
419 goto Compare;
420 }
421 assert(wsign != 0); /* else nbits was 0 */
422 assert(vsign != 0); /* if vsign were 0, then since wsign is
423 * not 0, we would have taken the
424 * vsign != wsign branch at the start */
425 /* We want to work with non-negative numbers. */
426 if (vsign < 0) {
427 /* "Multiply both sides" by -1; this also swaps the
428 * comparator.
429 */
430 i = -i;
431 op = _Py_SwappedOp[op];
432 }
433 assert(i > 0.0);
434 (void) frexp(i, &exponent);
435 /* exponent is the # of bits in v before the radix point;
436 * we know that nbits (the # of bits in w) > 48 at this point
437 */
438 if (exponent < 0 || (size_t)exponent < nbits) {
439 i = 1.0;
440 j = 2.0;
441 goto Compare;
442 }
443 if ((size_t)exponent > nbits) {
444 i = 2.0;
445 j = 1.0;
446 goto Compare;
447 }
448 /* v and w have the same number of bits before the radix
Serhiy Storchaka95949422013-08-27 19:40:23 +0300449 * point. Construct two ints that have the same comparison
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 * outcome.
451 */
452 {
453 double fracpart;
454 double intpart;
455 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 PyObject *vv = NULL;
457 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (wsign < 0) {
460 ww = PyNumber_Negative(w);
461 if (ww == NULL)
462 goto Error;
463 }
464 else
465 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 fracpart = modf(i, &intpart);
468 vv = PyLong_FromDouble(intpart);
469 if (vv == NULL)
470 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 if (fracpart != 0.0) {
473 /* Shift left, and or a 1 bit into vv
474 * to represent the lost fraction.
475 */
476 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000477
Serhiy Storchakaa5119e72019-05-19 14:14:38 +0300478 temp = _PyLong_Lshift(ww, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 if (temp == NULL)
480 goto Error;
481 Py_DECREF(ww);
482 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000483
Serhiy Storchakaa5119e72019-05-19 14:14:38 +0300484 temp = _PyLong_Lshift(vv, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 if (temp == NULL)
486 goto Error;
487 Py_DECREF(vv);
488 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000489
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300490 temp = PyNumber_Or(vv, _PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 if (temp == NULL)
492 goto Error;
493 Py_DECREF(vv);
494 vv = temp;
495 }
Tim Peters307fa782004-09-23 08:06:40 +0000496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 r = PyObject_RichCompareBool(vv, ww, op);
498 if (r < 0)
499 goto Error;
500 result = PyBool_FromLong(r);
501 Error:
502 Py_XDECREF(vv);
503 Py_XDECREF(ww);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 return result;
505 }
506 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000507
Serhiy Storchaka95949422013-08-27 19:40:23 +0300508 else /* w isn't float or int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000510
511 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 switch (op) {
513 case Py_EQ:
514 r = i == j;
515 break;
516 case Py_NE:
517 r = i != j;
518 break;
519 case Py_LE:
520 r = i <= j;
521 break;
522 case Py_GE:
523 r = i >= j;
524 break;
525 case Py_LT:
526 r = i < j;
527 break;
528 case Py_GT:
529 r = i > j;
530 break;
531 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000533
534 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500535 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000536}
537
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000538static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000539float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000542}
543
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000544static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000545float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 double a,b;
548 CONVERT_TO_DOUBLE(v, a);
549 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 a = a + b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000552}
553
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000554static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000555float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 double a,b;
558 CONVERT_TO_DOUBLE(v, a);
559 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 a = a - b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562}
563
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000564static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000565float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 double a,b;
568 CONVERT_TO_DOUBLE(v, a);
569 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 a = a * b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000572}
573
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000574static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000575float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 double a,b;
578 CONVERT_TO_DOUBLE(v, a);
579 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (b == 0.0) {
581 PyErr_SetString(PyExc_ZeroDivisionError,
582 "float division by zero");
583 return NULL;
584 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 a = a / b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000587}
588
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000589static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000590float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 double vx, wx;
593 double mod;
594 CONVERT_TO_DOUBLE(v, vx);
595 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (wx == 0.0) {
597 PyErr_SetString(PyExc_ZeroDivisionError,
598 "float modulo");
599 return NULL;
600 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000602 if (mod) {
603 /* ensure the remainder has the same sign as the denominator */
604 if ((wx < 0) != (mod < 0)) {
605 mod += wx;
606 }
607 }
608 else {
609 /* the remainder is zero, and in the presence of signed zeroes
610 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000611 it has the same sign as the denominator. */
612 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000615}
616
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900617static void
618_float_div_mod(double vx, double wx, double *floordiv, double *mod)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000619{
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900620 double div;
621 *mod = fmod(vx, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 /* fmod is typically exact, so vx-mod is *mathematically* an
623 exact multiple of wx. But this is fp arithmetic, and fp
624 vx - mod is an approximation; the result is that div may
625 not be an exact integral value after the division, although
626 it will always be very close to one.
627 */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900628 div = (vx - *mod) / wx;
629 if (*mod) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 /* ensure the remainder has the same sign as the denominator */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900631 if ((wx < 0) != (*mod < 0)) {
632 *mod += wx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 div -= 1.0;
634 }
635 }
636 else {
637 /* the remainder is zero, and in the presence of signed zeroes
638 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000639 it has the same sign as the denominator. */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900640 *mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 }
642 /* snap quotient to nearest integral value */
643 if (div) {
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900644 *floordiv = floor(div);
645 if (div - *floordiv > 0.5) {
646 *floordiv += 1.0;
Mark Dickinsonbe8147b2020-02-02 11:37:02 +0000647 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 }
649 else {
650 /* div is zero - get the same sign as the true quotient */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900651 *floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 }
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900653}
654
655static PyObject *
656float_divmod(PyObject *v, PyObject *w)
657{
Mark Dickinsonbe8147b2020-02-02 11:37:02 +0000658 double vx, wx;
659 double mod, floordiv;
660 CONVERT_TO_DOUBLE(v, vx);
661 CONVERT_TO_DOUBLE(w, wx);
662 if (wx == 0.0) {
663 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
664 return NULL;
665 }
666 _float_div_mod(vx, wx, &floordiv, &mod);
667 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000668}
669
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000670static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000671float_floor_div(PyObject *v, PyObject *w)
672{
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900673 double vx, wx;
674 double mod, floordiv;
675 CONVERT_TO_DOUBLE(v, vx);
676 CONVERT_TO_DOUBLE(w, wx);
677 if (wx == 0.0) {
678 PyErr_SetString(PyExc_ZeroDivisionError, "float floor division by zero");
679 return NULL;
680 }
681 _float_div_mod(vx, wx, &floordiv, &mod);
682 return PyFloat_FromDouble(floordiv);
Tim Peters63a35712001-12-11 19:57:24 +0000683}
684
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000685/* determine whether x is an odd integer or not; assumes that
686 x is not an infinity or nan. */
687#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
688
Tim Peters63a35712001-12-11 19:57:24 +0000689static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000690float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 double iv, iw, ix;
693 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 if ((PyObject *)z != Py_None) {
696 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
697 "allowed unless all arguments are integers");
698 return NULL;
699 }
Tim Peters32f453e2001-09-03 08:35:41 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 CONVERT_TO_DOUBLE(v, iv);
702 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 /* Sort out special cases here instead of relying on pow() */
705 if (iw == 0) { /* v**0 is 1, even 0**0 */
706 return PyFloat_FromDouble(1.0);
707 }
708 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
709 return PyFloat_FromDouble(iv);
710 }
711 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
712 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
713 }
714 if (Py_IS_INFINITY(iw)) {
715 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
716 * abs(v) > 1 (including case where v infinite)
717 *
718 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
719 * abs(v) > 1 (including case where v infinite)
720 */
721 iv = fabs(iv);
722 if (iv == 1.0)
723 return PyFloat_FromDouble(1.0);
724 else if ((iw > 0.0) == (iv > 1.0))
725 return PyFloat_FromDouble(fabs(iw)); /* return inf */
726 else
727 return PyFloat_FromDouble(0.0);
728 }
729 if (Py_IS_INFINITY(iv)) {
730 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
731 * both cases, we need to add the appropriate sign if w is
732 * an odd integer.
733 */
734 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
735 if (iw > 0.0)
736 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
737 else
738 return PyFloat_FromDouble(iw_is_odd ?
739 copysign(0.0, iv) : 0.0);
740 }
741 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
742 (already dealt with above), and an error
743 if w is negative. */
744 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
745 if (iw < 0.0) {
746 PyErr_SetString(PyExc_ZeroDivisionError,
747 "0.0 cannot be raised to a "
748 "negative power");
749 return NULL;
750 }
751 /* use correct sign if iw is odd */
752 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
753 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 if (iv < 0.0) {
756 /* Whether this is an error is a mess, and bumps into libm
757 * bugs so we have to figure it out ourselves.
758 */
759 if (iw != floor(iw)) {
760 /* Negative numbers raised to fractional powers
761 * become complex.
762 */
763 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
764 }
765 /* iw is an exact integer, albeit perhaps a very large
766 * one. Replace iv by its absolute value and remember
767 * to negate the pow result if iw is odd.
768 */
769 iv = -iv;
770 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
771 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
774 /* (-1) ** large_integer also ends up here. Here's an
775 * extract from the comments for the previous
776 * implementation explaining why this special case is
777 * necessary:
778 *
779 * -1 raised to an exact integer should never be exceptional.
780 * Alas, some libms (chiefly glibc as of early 2003) return
781 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
782 * happen to be representable in a *C* integer. That's a
783 * bug.
784 */
785 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
786 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 /* Now iv and iw are finite, iw is nonzero, and iv is
789 * positive and not equal to 1.0. We finally allow
790 * the platform pow to step in and do the rest.
791 */
792 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 ix = pow(iv, iw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 Py_ADJUST_ERANGE1(ix);
795 if (negate_result)
796 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 if (errno != 0) {
799 /* We don't expect any errno value other than ERANGE, but
800 * the range of libm bugs appears unbounded.
801 */
802 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
803 PyExc_ValueError);
804 return NULL;
805 }
806 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000807}
808
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000809#undef DOUBLE_IS_ODD_INTEGER
810
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000811static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000812float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000815}
816
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000817static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000818float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000821}
822
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000823static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000824float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000827}
828
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200829/*[clinic input]
830float.is_integer
831
832Return True if the float is an integer.
833[clinic start generated code]*/
834
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000835static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200836float_is_integer_impl(PyObject *self)
837/*[clinic end generated code: output=7112acf95a4d31ea input=311810d3f777e10d]*/
Christian Heimes53876d92008-04-19 00:31:39 +0000838{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200839 double x = PyFloat_AsDouble(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 PyObject *o;
841
842 if (x == -1.0 && PyErr_Occurred())
843 return NULL;
844 if (!Py_IS_FINITE(x))
845 Py_RETURN_FALSE;
846 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 o = (floor(x) == x) ? Py_True : Py_False;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 if (errno != 0) {
849 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
850 PyExc_ValueError);
851 return NULL;
852 }
853 Py_INCREF(o);
854 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000855}
856
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200857/*[clinic input]
858float.__trunc__
859
860Return the Integral closest to x between 0 and x.
861[clinic start generated code]*/
862
Christian Heimes53876d92008-04-19 00:31:39 +0000863static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200864float___trunc___impl(PyObject *self)
865/*[clinic end generated code: output=dd3e289dd4c6b538 input=591b9ba0d650fdff]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000866{
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500867 return PyLong_FromDouble(PyFloat_AS_DOUBLE(self));
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000868}
869
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +0300870/*[clinic input]
871float.__floor__
872
873Return the floor as an Integral.
874[clinic start generated code]*/
875
876static PyObject *
877float___floor___impl(PyObject *self)
878/*[clinic end generated code: output=e0551dbaea8c01d1 input=77bb13eb12e268df]*/
879{
880 double x = PyFloat_AS_DOUBLE(self);
881 return PyLong_FromDouble(floor(x));
882}
883
884/*[clinic input]
885float.__ceil__
886
887Return the ceiling as an Integral.
888[clinic start generated code]*/
889
890static PyObject *
891float___ceil___impl(PyObject *self)
892/*[clinic end generated code: output=a2fd8858f73736f9 input=79e41ae94aa0a516]*/
893{
894 double x = PyFloat_AS_DOUBLE(self);
895 return PyLong_FromDouble(ceil(x));
896}
897
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000898/* double_round: rounds a finite double to the closest multiple of
899 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
900 ndigits <= 323). Returns a Python float, or sets a Python error and
901 returns NULL on failure (OverflowError and memory errors are possible). */
902
903#ifndef PY_NO_SHORT_FLOAT_REPR
904/* version of double_round that uses the correctly-rounded string<->double
905 conversions from Python/dtoa.c */
906
907static PyObject *
908double_round(double x, int ndigits) {
909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 double rounded;
911 Py_ssize_t buflen, mybuflen=100;
912 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
913 int decpt, sign;
914 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000915 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000918 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000920 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 if (buf == NULL) {
922 PyErr_NoMemory();
923 return NULL;
924 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
927 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
928 buflen = buf_end - buf;
929 if (buflen + 8 > mybuflen) {
930 mybuflen = buflen+8;
931 mybuf = (char *)PyMem_Malloc(mybuflen);
932 if (mybuf == NULL) {
933 PyErr_NoMemory();
934 goto exit;
935 }
936 }
937 /* copy buf to mybuf, adding exponent, sign and leading 0 */
938 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
939 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* and convert the resulting string back to a double */
942 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000943 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000945 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 if (errno == ERANGE && fabs(rounded) >= 1.)
947 PyErr_SetString(PyExc_OverflowError,
948 "rounded value too large to represent");
949 else
950 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 /* done computing value; now clean up */
953 if (mybuf != shortbuf)
954 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000955 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 _Py_dg_freedtoa(buf);
957 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000958}
959
960#else /* PY_NO_SHORT_FLOAT_REPR */
961
962/* fallback version, to be used when correctly rounded binary<->decimal
963 conversions aren't available */
964
965static PyObject *
966double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 double pow1, pow2, y, z;
968 if (ndigits >= 0) {
969 if (ndigits > 22) {
970 /* pow1 and pow2 are each safe from overflow, but
971 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
972 pow1 = pow(10.0, (double)(ndigits-22));
973 pow2 = 1e22;
974 }
975 else {
976 pow1 = pow(10.0, (double)ndigits);
977 pow2 = 1.0;
978 }
979 y = (x*pow1)*pow2;
980 /* if y overflows, then rounded value is exactly x */
981 if (!Py_IS_FINITE(y))
982 return PyFloat_FromDouble(x);
983 }
984 else {
985 pow1 = pow(10.0, (double)-ndigits);
986 pow2 = 1.0; /* unused; silences a gcc compiler warning */
987 y = x / pow1;
988 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 z = round(y);
991 if (fabs(y-z) == 0.5)
992 /* halfway between two integers; use round-half-even */
993 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 if (ndigits >= 0)
996 z = (z / pow2) / pow1;
997 else
998 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 /* if computation resulted in overflow, raise OverflowError */
1001 if (!Py_IS_FINITE(z)) {
1002 PyErr_SetString(PyExc_OverflowError,
1003 "overflow occurred during round");
1004 return NULL;
1005 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001008}
1009
1010#endif /* PY_NO_SHORT_FLOAT_REPR */
1011
1012/* round a Python float v to the closest multiple of 10**-ndigits */
1013
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001014/*[clinic input]
1015float.__round__
1016
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001017 ndigits as o_ndigits: object = None
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001018 /
1019
1020Return the Integral closest to x, rounding half toward even.
1021
1022When an argument is passed, work like built-in round(x, ndigits).
1023[clinic start generated code]*/
1024
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001025static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001026float___round___impl(PyObject *self, PyObject *o_ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001027/*[clinic end generated code: output=374c36aaa0f13980 input=fc0fe25924fbc9ed]*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 double x, rounded;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001031
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001032 x = PyFloat_AsDouble(self);
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001033 if (o_ndigits == Py_None) {
Steve Dowercb39d1f2015-04-15 16:10:59 -04001034 /* single-argument round or with None ndigits:
1035 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 rounded = round(x);
1037 if (fabs(x-rounded) == 0.5)
1038 /* halfway case: round to even */
1039 rounded = 2.0*round(x/2.0);
1040 return PyLong_FromDouble(rounded);
1041 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 /* interpret second argument as a Py_ssize_t; clips on overflow */
1044 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1045 if (ndigits == -1 && PyErr_Occurred())
1046 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 /* nans and infinities round to themselves */
1049 if (!Py_IS_FINITE(x))
1050 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1053 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1054 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001055#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1056#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 if (ndigits > NDIGITS_MAX)
1058 /* return x */
1059 return PyFloat_FromDouble(x);
1060 else if (ndigits < NDIGITS_MIN)
1061 /* return 0.0, but with sign of x */
1062 return PyFloat_FromDouble(0.0*x);
1063 else
1064 /* finite x, and ndigits is not unreasonably large */
1065 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001066#undef NDIGITS_MAX
1067#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001068}
1069
1070static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001071float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 if (PyFloat_CheckExact(v))
1074 Py_INCREF(v);
1075 else
1076 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1077 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001078}
1079
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001080/*[clinic input]
1081float.conjugate
1082
1083Return self, the complex conjugate of any float.
1084[clinic start generated code]*/
1085
1086static PyObject *
1087float_conjugate_impl(PyObject *self)
1088/*[clinic end generated code: output=8ca292c2479194af input=82ba6f37a9ff91dd]*/
1089{
1090 return float_float(self);
1091}
1092
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001093/* turn ASCII hex characters into integer values and vice versa */
1094
1095static char
1096char_from_hex(int x)
1097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001099 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001100}
1101
1102static int
1103hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 int x;
1105 switch(c) {
1106 case '0':
1107 x = 0;
1108 break;
1109 case '1':
1110 x = 1;
1111 break;
1112 case '2':
1113 x = 2;
1114 break;
1115 case '3':
1116 x = 3;
1117 break;
1118 case '4':
1119 x = 4;
1120 break;
1121 case '5':
1122 x = 5;
1123 break;
1124 case '6':
1125 x = 6;
1126 break;
1127 case '7':
1128 x = 7;
1129 break;
1130 case '8':
1131 x = 8;
1132 break;
1133 case '9':
1134 x = 9;
1135 break;
1136 case 'a':
1137 case 'A':
1138 x = 10;
1139 break;
1140 case 'b':
1141 case 'B':
1142 x = 11;
1143 break;
1144 case 'c':
1145 case 'C':
1146 x = 12;
1147 break;
1148 case 'd':
1149 case 'D':
1150 x = 13;
1151 break;
1152 case 'e':
1153 case 'E':
1154 x = 14;
1155 break;
1156 case 'f':
1157 case 'F':
1158 x = 15;
1159 break;
1160 default:
1161 x = -1;
1162 break;
1163 }
1164 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001165}
1166
1167/* convert a float to a hexadecimal string */
1168
1169/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1170 of the form 4k+1. */
1171#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1172
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001173/*[clinic input]
1174float.hex
1175
1176Return a hexadecimal representation of a floating-point number.
1177
1178>>> (-0.1).hex()
1179'-0x1.999999999999ap-4'
1180>>> 3.14159.hex()
1181'0x1.921f9f01b866ep+1'
1182[clinic start generated code]*/
1183
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001184static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001185float_hex_impl(PyObject *self)
1186/*[clinic end generated code: output=0ebc9836e4d302d4 input=bec1271a33d47e67]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 double x, m;
1189 int e, shift, i, si, esign;
1190 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1191 trailing NUL byte. */
1192 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001193
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001194 CONVERT_TO_DOUBLE(self, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001197 return float_repr((PyFloatObject *)self);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001200 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 return PyUnicode_FromString("-0x0.0p+0");
1202 else
1203 return PyUnicode_FromString("0x0.0p+0");
1204 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001207 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 m = ldexp(m, shift);
1209 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 si = 0;
1212 s[si] = char_from_hex((int)m);
1213 si++;
1214 m -= (int)m;
1215 s[si] = '.';
1216 si++;
1217 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1218 m *= 16.0;
1219 s[si] = char_from_hex((int)m);
1220 si++;
1221 m -= (int)m;
1222 }
1223 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 if (e < 0) {
1226 esign = (int)'-';
1227 e = -e;
1228 }
1229 else
1230 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (x < 0.0)
1233 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1234 else
1235 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001236}
1237
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001238/* Convert a hexadecimal string to a float. */
1239
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001240/*[clinic input]
1241@classmethod
1242float.fromhex
1243
1244 string: object
1245 /
1246
1247Create a floating-point number from a hexadecimal string.
1248
1249>>> float.fromhex('0x1.ffffp10')
12502047.984375
1251>>> float.fromhex('-0x1p-1074')
1252-5e-324
1253[clinic start generated code]*/
1254
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001255static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001256float_fromhex(PyTypeObject *type, PyObject *string)
1257/*[clinic end generated code: output=46c0274d22b78e82 input=0407bebd354bca89]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001258{
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001259 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 double x;
1261 long exp, top_exp, lsb, key_digit;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001262 const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 int half_eps, digit, round_up, negate=0;
1264 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 /*
1267 * For the sake of simplicity and correctness, we impose an artificial
1268 * limit on ndigits, the total number of hex digits in the coefficient
1269 * The limit is chosen to ensure that, writing exp for the exponent,
1270 *
1271 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1272 * guaranteed to overflow (provided it's nonzero)
1273 *
1274 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1275 * guaranteed to underflow to 0.
1276 *
1277 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1278 * overflow in the calculation of exp and top_exp below.
1279 *
1280 * More specifically, ndigits is assumed to satisfy the following
1281 * inequalities:
1282 *
1283 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1284 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1285 *
1286 * If either of these inequalities is not satisfied, a ValueError is
1287 * raised. Otherwise, write x for the value of the hex string, and
1288 * assume x is nonzero. Then
1289 *
1290 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1291 *
1292 * Now if exp > LONG_MAX/2 then:
1293 *
1294 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1295 * = DBL_MAX_EXP
1296 *
1297 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1298 * double, so overflows. If exp < LONG_MIN/2, then
1299 *
1300 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1301 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1302 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1303 *
1304 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1305 * when converted to a C double.
1306 *
1307 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1308 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1309 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001310
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001311 s = PyUnicode_AsUTF8AndSize(string, &length);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 if (s == NULL)
1313 return NULL;
1314 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 /********************
1317 * Parse the string *
1318 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 /* leading whitespace */
1321 while (Py_ISSPACE(*s))
1322 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 /* infinities and nans */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001325 x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 if (coeff_end != s) {
1327 s = coeff_end;
1328 goto finished;
1329 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /* optional sign */
1332 if (*s == '-') {
1333 s++;
1334 negate = 1;
1335 }
1336 else if (*s == '+')
1337 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 /* [0x] */
1340 s_store = s;
1341 if (*s == '0') {
1342 s++;
1343 if (*s == 'x' || *s == 'X')
1344 s++;
1345 else
1346 s = s_store;
1347 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 /* coefficient: <integer> [. <fraction>] */
1350 coeff_start = s;
1351 while (hex_from_char(*s) >= 0)
1352 s++;
1353 s_store = s;
1354 if (*s == '.') {
1355 s++;
1356 while (hex_from_char(*s) >= 0)
1357 s++;
1358 coeff_end = s-1;
1359 }
1360 else
1361 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 /* ndigits = total # of hex digits; fdigits = # after point */
1364 ndigits = coeff_end - coeff_start;
1365 fdigits = coeff_end - s_store;
1366 if (ndigits == 0)
1367 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001368 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1369 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 /* [p <exponent>] */
1373 if (*s == 'p' || *s == 'P') {
1374 s++;
1375 exp_start = s;
1376 if (*s == '-' || *s == '+')
1377 s++;
1378 if (!('0' <= *s && *s <= '9'))
1379 goto parse_error;
1380 s++;
1381 while ('0' <= *s && *s <= '9')
1382 s++;
1383 exp = strtol(exp_start, NULL, 10);
1384 }
1385 else
1386 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001387
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001388/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1390 coeff_end-(j) : \
1391 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 /*******************************************
1394 * Compute rounded value of the hex string *
1395 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 /* Discard leading zeros, and catch extreme overflow and underflow */
1398 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1399 ndigits--;
1400 if (ndigits == 0 || exp < LONG_MIN/2) {
1401 x = 0.0;
1402 goto finished;
1403 }
1404 if (exp > LONG_MAX/2)
1405 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 /* Adjust exponent for fractional part. */
1408 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1411 top_exp = exp + 4*((long)ndigits - 1);
1412 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1413 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 /* catch almost all nonextreme cases of overflow and underflow here */
1416 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1417 x = 0.0;
1418 goto finished;
1419 }
1420 if (top_exp > DBL_MAX_EXP)
1421 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 /* lsb = exponent of least significant bit of the *rounded* value.
1424 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001425 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 x = 0.0;
1428 if (exp >= lsb) {
1429 /* no rounding required */
1430 for (i = ndigits-1; i >= 0; i--)
1431 x = 16.0*x + HEX_DIGIT(i);
1432 x = ldexp(x, (int)(exp));
1433 goto finished;
1434 }
1435 /* rounding required. key_digit is the index of the hex digit
1436 containing the first bit to be rounded away. */
1437 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1438 key_digit = (lsb - exp - 1) / 4;
1439 for (i = ndigits-1; i > key_digit; i--)
1440 x = 16.0*x + HEX_DIGIT(i);
1441 digit = HEX_DIGIT(key_digit);
1442 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1445 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1446 if ((digit & half_eps) != 0) {
1447 round_up = 0;
1448 if ((digit & (3*half_eps-1)) != 0 ||
1449 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1450 round_up = 1;
1451 else
1452 for (i = key_digit-1; i >= 0; i--)
1453 if (HEX_DIGIT(i) != 0) {
1454 round_up = 1;
1455 break;
1456 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001457 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 x += 2*half_eps;
1459 if (top_exp == DBL_MAX_EXP &&
1460 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1461 /* overflow corner case: pre-rounded value <
1462 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1463 goto overflow_error;
1464 }
1465 }
1466 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001467
1468 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 /* optional trailing whitespace leading to the end of the string */
1470 while (Py_ISSPACE(*s))
1471 s++;
1472 if (s != s_end)
1473 goto parse_error;
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001474 result = PyFloat_FromDouble(negate ? -x : x);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001475 if (type != &PyFloat_Type && result != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001476 Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001477 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001479
1480 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 PyErr_SetString(PyExc_OverflowError,
1482 "hexadecimal value too large to represent as a float");
1483 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001484
1485 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 PyErr_SetString(PyExc_ValueError,
1487 "invalid hexadecimal floating-point string");
1488 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001489
1490 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 PyErr_SetString(PyExc_ValueError,
1492 "hexadecimal string too long to convert");
1493 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001494}
1495
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001496/*[clinic input]
1497float.as_integer_ratio
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001498
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001499Return integer ratio.
1500
1501Return a pair of integers, whose ratio is exactly equal to the original float
1502and with a positive denominator.
1503
1504Raise OverflowError on infinities and a ValueError on NaNs.
1505
1506>>> (10.0).as_integer_ratio()
1507(10, 1)
1508>>> (0.0).as_integer_ratio()
1509(0, 1)
1510>>> (-.25).as_integer_ratio()
1511(-1, 4)
1512[clinic start generated code]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001513
Christian Heimes26855632008-01-27 23:50:43 +00001514static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001515float_as_integer_ratio_impl(PyObject *self)
1516/*[clinic end generated code: output=65f25f0d8d30a712 input=e21d08b4630c2e44]*/
Christian Heimes26855632008-01-27 23:50:43 +00001517{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001518 double self_double;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 double float_part;
1520 int exponent;
1521 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 PyObject *py_exponent = NULL;
1524 PyObject *numerator = NULL;
1525 PyObject *denominator = NULL;
1526 PyObject *result_pair = NULL;
1527 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001528
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001529 CONVERT_TO_DOUBLE(self, self_double);
Christian Heimes26855632008-01-27 23:50:43 +00001530
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001531 if (Py_IS_INFINITY(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001532 PyErr_SetString(PyExc_OverflowError,
1533 "cannot convert Infinity to integer ratio");
1534 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001536 if (Py_IS_NAN(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001537 PyErr_SetString(PyExc_ValueError,
1538 "cannot convert NaN to integer ratio");
1539 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 }
Christian Heimes26855632008-01-27 23:50:43 +00001541
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001542 float_part = frexp(self_double, &exponent); /* self_double == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1545 float_part *= 2.0;
1546 exponent--;
1547 }
1548 /* self == float_part * 2**exponent exactly and float_part is integral.
1549 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1550 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 numerator = PyLong_FromDouble(float_part);
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001553 if (numerator == NULL)
1554 goto error;
1555 denominator = PyLong_FromLong(1);
1556 if (denominator == NULL)
1557 goto error;
1558 py_exponent = PyLong_FromLong(Py_ABS(exponent));
1559 if (py_exponent == NULL)
1560 goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 /* fold in 2**exponent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 if (exponent > 0) {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001564 Py_SETREF(numerator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001565 long_methods->nb_lshift(numerator, py_exponent));
1566 if (numerator == NULL)
1567 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 }
1569 else {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001570 Py_SETREF(denominator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001571 long_methods->nb_lshift(denominator, py_exponent));
1572 if (denominator == NULL)
1573 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 }
1575
1576 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001577
Christian Heimes26855632008-01-27 23:50:43 +00001578error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 Py_XDECREF(py_exponent);
1580 Py_XDECREF(denominator);
1581 Py_XDECREF(numerator);
1582 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001583}
1584
Jeremy Hylton938ace62002-07-17 16:30:39 +00001585static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001586float_subtype_new(PyTypeObject *type, PyObject *x);
1587
1588/*[clinic input]
1589@classmethod
1590float.__new__ as float_new
Serhiy Storchakaba85d692017-03-30 09:09:41 +03001591 x: object(c_default="_PyLong_Zero") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001592 /
1593
1594Convert a string or number to a floating point number, if possible.
1595[clinic start generated code]*/
Guido van Rossumbef14172001-08-29 15:47:46 +00001596
Tim Peters6d6c1a32001-08-02 04:15:00 +00001597static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001598float_new_impl(PyTypeObject *type, PyObject *x)
Serhiy Storchakabae68812017-04-05 12:00:42 +03001599/*[clinic end generated code: output=ccf1e8dc460ba6ba input=540ee77c204ff87a]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00001600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 if (type != &PyFloat_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001602 return float_subtype_new(type, x); /* Wimp out */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 /* If it's a string, but not a string subclass, use
1604 PyFloat_FromString. */
1605 if (PyUnicode_CheckExact(x))
1606 return PyFloat_FromString(x);
1607 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001608}
1609
Guido van Rossumbef14172001-08-29 15:47:46 +00001610/* Wimpy, slow approach to tp_new calls for subtypes of float:
1611 first create a regular float from whatever arguments we got,
1612 then allocate a subtype instance and initialize its ob_fval
1613 from the regular float. The regular float is then thrown away.
1614*/
1615static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001616float_subtype_new(PyTypeObject *type, PyObject *x)
Guido van Rossumbef14172001-08-29 15:47:46 +00001617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 assert(PyType_IsSubtype(type, &PyFloat_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001621 tmp = float_new_impl(&PyFloat_Type, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 if (tmp == NULL)
1623 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001624 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 newobj = type->tp_alloc(type, 0);
1626 if (newobj == NULL) {
1627 Py_DECREF(tmp);
1628 return NULL;
1629 }
1630 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1631 Py_DECREF(tmp);
1632 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001633}
1634
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001635/*[clinic input]
1636float.__getnewargs__
1637[clinic start generated code]*/
1638
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001639static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001640float___getnewargs___impl(PyObject *self)
1641/*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001642{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001643 return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001644}
1645
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001646/* this is for the benefit of the pack/unpack routines below */
1647
1648typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001650} float_format_type;
1651
1652static float_format_type double_format, float_format;
1653static float_format_type detected_double_format, detected_float_format;
1654
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001655/*[clinic input]
1656@classmethod
1657float.__getformat__
1658
1659 typestr: str
1660 Must be 'double' or 'float'.
1661 /
1662
1663You probably don't want to use this function.
1664
1665It exists mainly to be used in Python's test suite.
1666
1667This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
1668little-endian' best describes the format of floating point numbers used by the
1669C type named by typestr.
1670[clinic start generated code]*/
1671
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001672static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001673float___getformat___impl(PyTypeObject *type, const char *typestr)
1674/*[clinic end generated code: output=2bfb987228cc9628 input=d5a52600f835ad67]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001677
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001678 if (strcmp(typestr, "double") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 r = double_format;
1680 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001681 else if (strcmp(typestr, "float") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 r = float_format;
1683 }
1684 else {
1685 PyErr_SetString(PyExc_ValueError,
1686 "__getformat__() argument 1 must be "
1687 "'double' or 'float'");
1688 return NULL;
1689 }
1690
1691 switch (r) {
1692 case unknown_format:
1693 return PyUnicode_FromString("unknown");
1694 case ieee_little_endian_format:
1695 return PyUnicode_FromString("IEEE, little-endian");
1696 case ieee_big_endian_format:
1697 return PyUnicode_FromString("IEEE, big-endian");
1698 default:
Victor Stinner04394df2019-11-18 17:39:48 +01001699 PyErr_SetString(PyExc_RuntimeError,
1700 "insane float_format or double_format");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 return NULL;
1702 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001703}
1704
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001705/*[clinic input]
1706@classmethod
1707float.__set_format__
1708
1709 typestr: str
1710 Must be 'double' or 'float'.
1711 fmt: str
1712 Must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian',
1713 and in addition can only be one of the latter two if it appears to
1714 match the underlying C reality.
1715 /
1716
1717You probably don't want to use this function.
1718
1719It exists mainly to be used in Python's test suite.
1720
1721Override the automatic determination of C-level floating point type.
1722This affects how floats are converted to and from binary strings.
1723[clinic start generated code]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001724
1725static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001726float___set_format___impl(PyTypeObject *type, const char *typestr,
1727 const char *fmt)
1728/*[clinic end generated code: output=504460f5dc85acbd input=5306fa2b81a997e4]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 float_format_type f;
1731 float_format_type detected;
1732 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 if (strcmp(typestr, "double") == 0) {
1735 p = &double_format;
1736 detected = detected_double_format;
1737 }
1738 else if (strcmp(typestr, "float") == 0) {
1739 p = &float_format;
1740 detected = detected_float_format;
1741 }
1742 else {
1743 PyErr_SetString(PyExc_ValueError,
1744 "__setformat__() argument 1 must "
1745 "be 'double' or 'float'");
1746 return NULL;
1747 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001748
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001749 if (strcmp(fmt, "unknown") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 f = unknown_format;
1751 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001752 else if (strcmp(fmt, "IEEE, little-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 f = ieee_little_endian_format;
1754 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001755 else if (strcmp(fmt, "IEEE, big-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 f = ieee_big_endian_format;
1757 }
1758 else {
1759 PyErr_SetString(PyExc_ValueError,
1760 "__setformat__() argument 2 must be "
1761 "'unknown', 'IEEE, little-endian' or "
1762 "'IEEE, big-endian'");
1763 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 if (f != unknown_format && f != detected) {
1768 PyErr_Format(PyExc_ValueError,
1769 "can only set %s format to 'unknown' or the "
1770 "detected platform value", typestr);
1771 return NULL;
1772 }
1773
1774 *p = f;
1775 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001776}
1777
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001778static PyObject *
1779float_getreal(PyObject *v, void *closure)
1780{
1781 return float_float(v);
1782}
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001783
Guido van Rossumb43daf72007-08-01 18:08:08 +00001784static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001785float_getimag(PyObject *v, void *closure)
Guido van Rossumb43daf72007-08-01 18:08:08 +00001786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001788}
1789
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001790/*[clinic input]
1791float.__format__
1792
1793 format_spec: unicode
1794 /
1795
1796Formats the float according to format_spec.
1797[clinic start generated code]*/
1798
Eric Smith8c663262007-08-25 02:26:07 +00001799static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001800float___format___impl(PyObject *self, PyObject *format_spec)
1801/*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/
Eric Smith8c663262007-08-25 02:26:07 +00001802{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001803 _PyUnicodeWriter writer;
1804 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001805
Victor Stinner8f674cc2013-04-17 23:02:17 +02001806 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001807 ret = _PyFloat_FormatAdvancedWriter(
1808 &writer,
1809 self,
1810 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1811 if (ret == -1) {
1812 _PyUnicodeWriter_Dealloc(&writer);
1813 return NULL;
1814 }
1815 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001816}
1817
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001818static PyMethodDef float_methods[] = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001819 FLOAT_CONJUGATE_METHODDEF
1820 FLOAT___TRUNC___METHODDEF
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +03001821 FLOAT___FLOOR___METHODDEF
1822 FLOAT___CEIL___METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001823 FLOAT___ROUND___METHODDEF
1824 FLOAT_AS_INTEGER_RATIO_METHODDEF
1825 FLOAT_FROMHEX_METHODDEF
1826 FLOAT_HEX_METHODDEF
1827 FLOAT_IS_INTEGER_METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001828 FLOAT___GETNEWARGS___METHODDEF
1829 FLOAT___GETFORMAT___METHODDEF
1830 FLOAT___SET_FORMAT___METHODDEF
1831 FLOAT___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001833};
1834
Guido van Rossumb43daf72007-08-01 18:08:08 +00001835static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 {"real",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001837 float_getreal, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001838 "the real part of a complex number",
1839 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 {"imag",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001841 float_getimag, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001842 "the imaginary part of a complex number",
1843 NULL},
1844 {NULL} /* Sentinel */
1845};
1846
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001848static PyNumberMethods float_as_number = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001849 float_add, /* nb_add */
1850 float_sub, /* nb_subtract */
1851 float_mul, /* nb_multiply */
1852 float_rem, /* nb_remainder */
1853 float_divmod, /* nb_divmod */
1854 float_pow, /* nb_power */
1855 (unaryfunc)float_neg, /* nb_negative */
1856 float_float, /* nb_positive */
1857 (unaryfunc)float_abs, /* nb_absolute */
1858 (inquiry)float_bool, /* nb_bool */
1859 0, /* nb_invert */
1860 0, /* nb_lshift */
1861 0, /* nb_rshift */
1862 0, /* nb_and */
1863 0, /* nb_xor */
1864 0, /* nb_or */
1865 float___trunc___impl, /* nb_int */
1866 0, /* nb_reserved */
1867 float_float, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 0, /* nb_inplace_add */
1869 0, /* nb_inplace_subtract */
1870 0, /* nb_inplace_multiply */
1871 0, /* nb_inplace_remainder */
1872 0, /* nb_inplace_power */
1873 0, /* nb_inplace_lshift */
1874 0, /* nb_inplace_rshift */
1875 0, /* nb_inplace_and */
1876 0, /* nb_inplace_xor */
1877 0, /* nb_inplace_or */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001878 float_floor_div, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 float_div, /* nb_true_divide */
1880 0, /* nb_inplace_floor_divide */
1881 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001882};
1883
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001884PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1886 "float",
1887 sizeof(PyFloatObject),
1888 0,
1889 (destructor)float_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001890 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 0, /* tp_getattr */
1892 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001893 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 (reprfunc)float_repr, /* tp_repr */
1895 &float_as_number, /* tp_as_number */
1896 0, /* tp_as_sequence */
1897 0, /* tp_as_mapping */
1898 (hashfunc)float_hash, /* tp_hash */
1899 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001900 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 PyObject_GenericGetAttr, /* tp_getattro */
1902 0, /* tp_setattro */
1903 0, /* tp_as_buffer */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001904 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001905 float_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 0, /* tp_traverse */
1907 0, /* tp_clear */
1908 float_richcompare, /* tp_richcompare */
1909 0, /* tp_weaklistoffset */
1910 0, /* tp_iter */
1911 0, /* tp_iternext */
1912 float_methods, /* tp_methods */
1913 0, /* tp_members */
1914 float_getset, /* tp_getset */
1915 0, /* tp_base */
1916 0, /* tp_dict */
1917 0, /* tp_descr_get */
1918 0, /* tp_descr_set */
1919 0, /* tp_dictoffset */
1920 0, /* tp_init */
1921 0, /* tp_alloc */
1922 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001923};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001924
Victor Stinner1c8f0592013-07-22 22:24:54 +02001925int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001926_PyFloat_Init(void)
1927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 /* We attempt to determine if this machine is using IEEE
1929 floating point formats by peering at the bits of some
1930 carefully chosen values. If it looks like we are on an
1931 IEEE platform, the float packing/unpacking routines can
1932 just copy bits, if not they resort to arithmetic & shifts
1933 and masks. The shifts & masks approach works on all finite
1934 values, but what happens to infinities, NaNs and signed
1935 zeroes on packing is an accident, and attempting to unpack
1936 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 Note that if we're on some whacked-out platform which uses
1939 IEEE formats but isn't strictly little-endian or big-
1940 endian, we will fall back to the portable shifts & masks
1941 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001942
1943#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 {
1945 double x = 9006104071832581.0;
1946 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1947 detected_double_format = ieee_big_endian_format;
1948 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1949 detected_double_format = ieee_little_endian_format;
1950 else
1951 detected_double_format = unknown_format;
1952 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001953#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001955#endif
1956
1957#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 {
1959 float y = 16711938.0;
1960 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1961 detected_float_format = ieee_big_endian_format;
1962 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1963 detected_float_format = ieee_little_endian_format;
1964 else
1965 detected_float_format = unknown_format;
1966 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001967#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001969#endif
1970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 double_format = detected_double_format;
1972 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001975 if (FloatInfoType.tp_name == NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001976 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001977 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001978 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02001979 }
1980 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001981}
1982
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001983void
1984_PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001985{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001986 PyFloatObject *f = free_list, *next;
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001987 for (; f; f = next) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001988 next = (PyFloatObject*) Py_TYPE(f);
1989 PyObject_FREE(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001991 free_list = NULL;
1992 numfree = 0;
Christian Heimes15ebc882008-02-04 18:48:49 +00001993}
1994
1995void
Victor Stinnerbed48172019-08-27 00:12:32 +02001996_PyFloat_Fini(void)
Christian Heimes15ebc882008-02-04 18:48:49 +00001997{
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001998 _PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001999}
Tim Peters9905b942003-03-20 20:53:32 +00002000
David Malcolm49526f42012-06-22 14:55:41 -04002001/* Print summary info about the state of the optimized allocator */
2002void
2003_PyFloat_DebugMallocStats(FILE *out)
2004{
2005 _PyDebugAllocatorStats(out,
2006 "free PyFloatObject",
2007 numfree, sizeof(PyFloatObject));
2008}
2009
2010
Tim Peters9905b942003-03-20 20:53:32 +00002011/*----------------------------------------------------------------------------
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002012 * _PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h.
2013 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
2014 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
2015 * We use:
2016 * bits = (unsigned short)f; Note the truncation
2017 * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
2018 * bits++;
2019 * }
Tim Peters9905b942003-03-20 20:53:32 +00002020 */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002021
2022int
2023_PyFloat_Pack2(double x, unsigned char *p, int le)
2024{
2025 unsigned char sign;
2026 int e;
2027 double f;
2028 unsigned short bits;
2029 int incr = 1;
2030
2031 if (x == 0.0) {
2032 sign = (copysign(1.0, x) == -1.0);
2033 e = 0;
2034 bits = 0;
2035 }
2036 else if (Py_IS_INFINITY(x)) {
2037 sign = (x < 0.0);
2038 e = 0x1f;
2039 bits = 0;
2040 }
2041 else if (Py_IS_NAN(x)) {
2042 /* There are 2046 distinct half-precision NaNs (1022 signaling and
2043 1024 quiet), but there are only two quiet NaNs that don't arise by
2044 quieting a signaling NaN; we get those by setting the topmost bit
2045 of the fraction field and clearing all other fraction bits. We
2046 choose the one with the appropriate sign. */
2047 sign = (copysign(1.0, x) == -1.0);
2048 e = 0x1f;
2049 bits = 512;
2050 }
2051 else {
2052 sign = (x < 0.0);
2053 if (sign) {
2054 x = -x;
2055 }
2056
2057 f = frexp(x, &e);
2058 if (f < 0.5 || f >= 1.0) {
2059 PyErr_SetString(PyExc_SystemError,
2060 "frexp() result out of range");
2061 return -1;
2062 }
2063
2064 /* Normalize f to be in the range [1.0, 2.0) */
2065 f *= 2.0;
2066 e--;
2067
2068 if (e >= 16) {
2069 goto Overflow;
2070 }
2071 else if (e < -25) {
2072 /* |x| < 2**-25. Underflow to zero. */
2073 f = 0.0;
2074 e = 0;
2075 }
2076 else if (e < -14) {
2077 /* |x| < 2**-14. Gradual underflow */
2078 f = ldexp(f, 14 + e);
2079 e = 0;
2080 }
2081 else /* if (!(e == 0 && f == 0.0)) */ {
2082 e += 15;
2083 f -= 1.0; /* Get rid of leading 1 */
2084 }
2085
2086 f *= 1024.0; /* 2**10 */
2087 /* Round to even */
2088 bits = (unsigned short)f; /* Note the truncation */
2089 assert(bits < 1024);
2090 assert(e < 31);
2091 if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2092 ++bits;
2093 if (bits == 1024) {
2094 /* The carry propagated out of a string of 10 1 bits. */
2095 bits = 0;
2096 ++e;
2097 if (e == 31)
2098 goto Overflow;
2099 }
2100 }
2101 }
2102
2103 bits |= (e << 10) | (sign << 15);
2104
2105 /* Write out result. */
2106 if (le) {
2107 p += 1;
2108 incr = -1;
2109 }
2110
2111 /* First byte */
2112 *p = (unsigned char)((bits >> 8) & 0xFF);
2113 p += incr;
2114
2115 /* Second byte */
2116 *p = (unsigned char)(bits & 0xFF);
2117
2118 return 0;
2119
2120 Overflow:
2121 PyErr_SetString(PyExc_OverflowError,
2122 "float too large to pack with e format");
2123 return -1;
2124}
2125
Tim Peters9905b942003-03-20 20:53:32 +00002126int
2127_PyFloat_Pack4(double x, unsigned char *p, int le)
2128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 if (float_format == unknown_format) {
2130 unsigned char sign;
2131 int e;
2132 double f;
2133 unsigned int fbits;
2134 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 if (le) {
2137 p += 3;
2138 incr = -1;
2139 }
Tim Peters9905b942003-03-20 20:53:32 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 if (x < 0) {
2142 sign = 1;
2143 x = -x;
2144 }
2145 else
2146 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 /* Normalize f to be in the range [1.0, 2.0) */
2151 if (0.5 <= f && f < 1.0) {
2152 f *= 2.0;
2153 e--;
2154 }
2155 else if (f == 0.0)
2156 e = 0;
2157 else {
2158 PyErr_SetString(PyExc_SystemError,
2159 "frexp() result out of range");
2160 return -1;
2161 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (e >= 128)
2164 goto Overflow;
2165 else if (e < -126) {
2166 /* Gradual underflow */
2167 f = ldexp(f, 126 + e);
2168 e = 0;
2169 }
2170 else if (!(e == 0 && f == 0.0)) {
2171 e += 127;
2172 f -= 1.0; /* Get rid of leading 1 */
2173 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 f *= 8388608.0; /* 2**23 */
2176 fbits = (unsigned int)(f + 0.5); /* Round */
2177 assert(fbits <= 8388608);
2178 if (fbits >> 23) {
2179 /* The carry propagated out of a string of 23 1 bits. */
2180 fbits = 0;
2181 ++e;
2182 if (e >= 255)
2183 goto Overflow;
2184 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 /* First byte */
2187 *p = (sign << 7) | (e >> 1);
2188 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 /* Second byte */
2191 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2192 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 /* Third byte */
2195 *p = (fbits >> 8) & 0xFF;
2196 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 /* Fourth byte */
2199 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 /* Done */
2202 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 }
2205 else {
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002206 float y = (float)x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002208
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002209 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002211
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002212 unsigned char s[sizeof(float)];
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002213 memcpy(s, &y, sizeof(float));
2214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 if ((float_format == ieee_little_endian_format && !le)
2216 || (float_format == ieee_big_endian_format && le)) {
2217 p += 3;
2218 incr = -1;
2219 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 for (i = 0; i < 4; i++) {
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002222 *p = s[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 p += incr;
2224 }
2225 return 0;
2226 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002227 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 PyErr_SetString(PyExc_OverflowError,
2229 "float too large to pack with f format");
2230 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002231}
2232
2233int
2234_PyFloat_Pack8(double x, unsigned char *p, int le)
2235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 if (double_format == unknown_format) {
2237 unsigned char sign;
2238 int e;
2239 double f;
2240 unsigned int fhi, flo;
2241 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 if (le) {
2244 p += 7;
2245 incr = -1;
2246 }
Tim Peters9905b942003-03-20 20:53:32 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 if (x < 0) {
2249 sign = 1;
2250 x = -x;
2251 }
2252 else
2253 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 /* Normalize f to be in the range [1.0, 2.0) */
2258 if (0.5 <= f && f < 1.0) {
2259 f *= 2.0;
2260 e--;
2261 }
2262 else if (f == 0.0)
2263 e = 0;
2264 else {
2265 PyErr_SetString(PyExc_SystemError,
2266 "frexp() result out of range");
2267 return -1;
2268 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 if (e >= 1024)
2271 goto Overflow;
2272 else if (e < -1022) {
2273 /* Gradual underflow */
2274 f = ldexp(f, 1022 + e);
2275 e = 0;
2276 }
2277 else if (!(e == 0 && f == 0.0)) {
2278 e += 1023;
2279 f -= 1.0; /* Get rid of leading 1 */
2280 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2283 f *= 268435456.0; /* 2**28 */
2284 fhi = (unsigned int)f; /* Truncate */
2285 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 f -= (double)fhi;
2288 f *= 16777216.0; /* 2**24 */
2289 flo = (unsigned int)(f + 0.5); /* Round */
2290 assert(flo <= 16777216);
2291 if (flo >> 24) {
2292 /* The carry propagated out of a string of 24 1 bits. */
2293 flo = 0;
2294 ++fhi;
2295 if (fhi >> 28) {
2296 /* And it also progagated out of the next 28 bits. */
2297 fhi = 0;
2298 ++e;
2299 if (e >= 2047)
2300 goto Overflow;
2301 }
2302 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 /* First byte */
2305 *p = (sign << 7) | (e >> 4);
2306 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 /* Second byte */
2309 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2310 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 /* Third byte */
2313 *p = (fhi >> 16) & 0xFF;
2314 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 /* Fourth byte */
2317 *p = (fhi >> 8) & 0xFF;
2318 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 /* Fifth byte */
2321 *p = fhi & 0xFF;
2322 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* Sixth byte */
2325 *p = (flo >> 16) & 0xFF;
2326 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 /* Seventh byte */
2329 *p = (flo >> 8) & 0xFF;
2330 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 /* Eighth byte */
2333 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002334 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 /* Done */
2337 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 Overflow:
2340 PyErr_SetString(PyExc_OverflowError,
2341 "float too large to pack with d format");
2342 return -1;
2343 }
2344 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002345 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 if ((double_format == ieee_little_endian_format && !le)
2349 || (double_format == ieee_big_endian_format && le)) {
2350 p += 7;
2351 incr = -1;
2352 }
2353
2354 for (i = 0; i < 8; i++) {
2355 *p = *s++;
2356 p += incr;
2357 }
2358 return 0;
2359 }
Tim Peters9905b942003-03-20 20:53:32 +00002360}
2361
2362double
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002363_PyFloat_Unpack2(const unsigned char *p, int le)
2364{
2365 unsigned char sign;
2366 int e;
2367 unsigned int f;
2368 double x;
2369 int incr = 1;
2370
2371 if (le) {
2372 p += 1;
2373 incr = -1;
2374 }
2375
2376 /* First byte */
2377 sign = (*p >> 7) & 1;
2378 e = (*p & 0x7C) >> 2;
2379 f = (*p & 0x03) << 8;
2380 p += incr;
2381
2382 /* Second byte */
2383 f |= *p;
2384
2385 if (e == 0x1f) {
2386#ifdef PY_NO_SHORT_FLOAT_REPR
2387 if (f == 0) {
2388 /* Infinity */
2389 return sign ? -Py_HUGE_VAL : Py_HUGE_VAL;
2390 }
2391 else {
2392 /* NaN */
2393#ifdef Py_NAN
2394 return sign ? -Py_NAN : Py_NAN;
2395#else
2396 PyErr_SetString(
2397 PyExc_ValueError,
2398 "can't unpack IEEE 754 NaN "
2399 "on platform that does not support NaNs");
2400 return -1;
2401#endif /* #ifdef Py_NAN */
2402 }
2403#else
2404 if (f == 0) {
2405 /* Infinity */
2406 return _Py_dg_infinity(sign);
2407 }
2408 else {
2409 /* NaN */
2410 return _Py_dg_stdnan(sign);
2411 }
2412#endif /* #ifdef PY_NO_SHORT_FLOAT_REPR */
2413 }
2414
2415 x = (double)f / 1024.0;
2416
2417 if (e == 0) {
2418 e = -14;
2419 }
2420 else {
2421 x += 1.0;
2422 e -= 15;
2423 }
2424 x = ldexp(x, e);
2425
2426 if (sign)
2427 x = -x;
2428
2429 return x;
2430}
2431
2432double
Tim Peters9905b942003-03-20 20:53:32 +00002433_PyFloat_Unpack4(const unsigned char *p, int le)
2434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 if (float_format == unknown_format) {
2436 unsigned char sign;
2437 int e;
2438 unsigned int f;
2439 double x;
2440 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 if (le) {
2443 p += 3;
2444 incr = -1;
2445 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 /* First byte */
2448 sign = (*p >> 7) & 1;
2449 e = (*p & 0x7F) << 1;
2450 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 /* Second byte */
2453 e |= (*p >> 7) & 1;
2454 f = (*p & 0x7F) << 16;
2455 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 if (e == 255) {
2458 PyErr_SetString(
2459 PyExc_ValueError,
2460 "can't unpack IEEE 754 special value "
2461 "on non-IEEE platform");
2462 return -1;
2463 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 /* Third byte */
2466 f |= *p << 8;
2467 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 /* Fourth byte */
2470 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 /* XXX This sadly ignores Inf/NaN issues */
2475 if (e == 0)
2476 e = -126;
2477 else {
2478 x += 1.0;
2479 e -= 127;
2480 }
2481 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 if (sign)
2484 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 return x;
2487 }
2488 else {
2489 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 if ((float_format == ieee_little_endian_format && !le)
2492 || (float_format == ieee_big_endian_format && le)) {
2493 char buf[4];
2494 char *d = &buf[3];
2495 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 for (i = 0; i < 4; i++) {
2498 *d-- = *p++;
2499 }
2500 memcpy(&x, buf, 4);
2501 }
2502 else {
2503 memcpy(&x, p, 4);
2504 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 return x;
2507 }
Tim Peters9905b942003-03-20 20:53:32 +00002508}
2509
2510double
2511_PyFloat_Unpack8(const unsigned char *p, int le)
2512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 if (double_format == unknown_format) {
2514 unsigned char sign;
2515 int e;
2516 unsigned int fhi, flo;
2517 double x;
2518 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 if (le) {
2521 p += 7;
2522 incr = -1;
2523 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 /* First byte */
2526 sign = (*p >> 7) & 1;
2527 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 /* Second byte */
2532 e |= (*p >> 4) & 0xF;
2533 fhi = (*p & 0xF) << 24;
2534 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 if (e == 2047) {
2537 PyErr_SetString(
2538 PyExc_ValueError,
2539 "can't unpack IEEE 754 special value "
2540 "on non-IEEE platform");
2541 return -1.0;
2542 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 /* Third byte */
2545 fhi |= *p << 16;
2546 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 /* Fourth byte */
2549 fhi |= *p << 8;
2550 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 /* Fifth byte */
2553 fhi |= *p;
2554 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 /* Sixth byte */
2557 flo = *p << 16;
2558 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 /* Seventh byte */
2561 flo |= *p << 8;
2562 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 /* Eighth byte */
2565 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2568 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 if (e == 0)
2571 e = -1022;
2572 else {
2573 x += 1.0;
2574 e -= 1023;
2575 }
2576 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 if (sign)
2579 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 return x;
2582 }
2583 else {
2584 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 if ((double_format == ieee_little_endian_format && !le)
2587 || (double_format == ieee_big_endian_format && le)) {
2588 char buf[8];
2589 char *d = &buf[7];
2590 int i;
2591
2592 for (i = 0; i < 8; i++) {
2593 *d-- = *p++;
2594 }
2595 memcpy(&x, buf, 8);
2596 }
2597 else {
2598 memcpy(&x, p, 8);
2599 }
2600
2601 return x;
2602 }
Tim Peters9905b942003-03-20 20:53:32 +00002603}