blob: 7ffd7eebe5a45c390f518d9fc305c4e71517c532 [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 Stinner04fc4f22020-06-16 01:28:07 +02007#include "pycore_dtoa.h" // _Py_dg_dtoa()
Victor Stinner2ba59372020-06-05 00:50:05 +02008#include "pycore_interp.h" // _PyInterpreterState.float_state
Victor Stinner04fc4f22020-06-16 01:28:07 +02009#include "pycore_object.h" // _PyObject_Init()
Victor Stinner2ba59372020-06-05 00:50:05 +020010#include "pycore_pystate.h" // _PyInterpreterState_GET()
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Guido van Rossum3f5da241990-12-20 15:06:42 +000012#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000013#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000014
Serhiy Storchakab5c51d32017-03-11 09:21:05 +020015/*[clinic input]
16class float "PyObject *" "&PyFloat_Type"
17[clinic start generated code]*/
18/*[clinic end generated code: output=da39a3ee5e6b4b0d input=dd0003f68f144284]*/
19
20#include "clinic/floatobject.c.h"
Guido van Rossum6923e131990-11-02 17:50:43 +000021
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000022#ifndef PyFloat_MAXFREELIST
Victor Stinner2ba59372020-06-05 00:50:05 +020023# define PyFloat_MAXFREELIST 100
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000024#endif
Guido van Rossum3fce8831999-03-12 19:43:17 +000025
Christian Heimes93852662007-12-01 12:22:32 +000026double
27PyFloat_GetMax(void)
28{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000030}
31
32double
33PyFloat_GetMin(void)
34{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000035 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000036}
37
Christian Heimesd32ed6f2008-01-14 18:49:24 +000038static PyTypeObject FloatInfoType;
39
40PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000041"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000042\n\
Raymond Hettinger71170742019-09-11 07:17:32 -070043A named tuple holding information about the float type. It contains low level\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000044information about the precision and internal representation. Please study\n\
45your system's :file:`float.h` for more information.");
46
47static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 {"max", "DBL_MAX -- maximum representable finite float"},
49 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
50 "is representable"},
51 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
52 "is representable"},
Stefano Taschini0301c9b2018-03-26 11:41:30 +020053 {"min", "DBL_MIN -- Minimum positive normalized float"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
55 "is a normalized float"},
56 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
57 "a normalized"},
Zackery Spytzfdc5a942020-05-24 04:03:52 -060058 {"dig", "DBL_DIG -- maximum number of decimal digits that "
59 "can be faithfully represented in a float"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
61 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
62 "representable float"},
63 {"radix", "FLT_RADIX -- radix of exponent"},
Zackery Spytzfdc5a942020-05-24 04:03:52 -060064 {"rounds", "FLT_ROUNDS -- rounding mode used for arithmetic "
65 "operations"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +000067};
68
69static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 "sys.float_info", /* name */
71 floatinfo__doc__, /* doc */
72 floatinfo_fields, /* fields */
73 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +000074};
75
Christian Heimes93852662007-12-01 12:22:32 +000076PyObject *
77PyFloat_GetInfo(void)
78{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 PyObject* floatinfo;
80 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +000081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 floatinfo = PyStructSequence_New(&FloatInfoType);
83 if (floatinfo == NULL) {
84 return NULL;
85 }
Christian Heimes93852662007-12-01 12:22:32 +000086
Christian Heimesd32ed6f2008-01-14 18:49:24 +000087#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +000089#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +000091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 SetDblFlag(DBL_MAX);
93 SetIntFlag(DBL_MAX_EXP);
94 SetIntFlag(DBL_MAX_10_EXP);
95 SetDblFlag(DBL_MIN);
96 SetIntFlag(DBL_MIN_EXP);
97 SetIntFlag(DBL_MIN_10_EXP);
98 SetIntFlag(DBL_DIG);
99 SetIntFlag(DBL_MANT_DIG);
100 SetDblFlag(DBL_EPSILON);
101 SetIntFlag(FLT_RADIX);
102 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000103#undef SetIntFlag
104#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105
106 if (PyErr_Occurred()) {
107 Py_CLEAR(floatinfo);
108 return NULL;
109 }
110 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000111}
112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000114PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000115{
Victor Stinner2ba59372020-06-05 00:50:05 +0200116 PyInterpreterState *interp = _PyInterpreterState_GET();
117 struct _Py_float_state *state = &interp->float_state;
118 PyFloatObject *op = state->free_list;
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000119 if (op != NULL) {
Victor Stinnerbcb19832020-06-08 02:14:47 +0200120#ifdef Py_DEBUG
121 // PyFloat_FromDouble() must not be called after _PyFloat_Fini()
122 assert(state->numfree != -1);
123#endif
Victor Stinner2ba59372020-06-05 00:50:05 +0200124 state->free_list = (PyFloatObject *) Py_TYPE(op);
125 state->numfree--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 }
Victor Stinner2ba59372020-06-05 00:50:05 +0200127 else {
128 op = PyObject_Malloc(sizeof(PyFloatObject));
129 if (!op) {
130 return PyErr_NoMemory();
131 }
132 }
Victor Stinner04fc4f22020-06-16 01:28:07 +0200133 _PyObject_Init((PyObject*)op, &PyFloat_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 op->ob_fval = fval;
135 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000136}
137
Brett Cannona721aba2016-09-09 14:57:09 -0700138static PyObject *
139float_from_string_inner(const char *s, Py_ssize_t len, void *obj)
140{
141 double x;
142 const char *end;
143 const char *last = s + len;
144 /* strip space */
145 while (s < last && Py_ISSPACE(*s)) {
146 s++;
147 }
148
149 while (s < last - 1 && Py_ISSPACE(last[-1])) {
150 last--;
151 }
152
153 /* We don't care about overflow or underflow. If the platform
154 * supports them, infinities and signed zeroes (on underflow) are
155 * fine. */
156 x = PyOS_string_to_double(s, (char **)&end, NULL);
157 if (end != last) {
158 PyErr_Format(PyExc_ValueError,
159 "could not convert string to float: "
160 "%R", obj);
161 return NULL;
162 }
163 else if (x == -1.0 && PyErr_Occurred()) {
164 return NULL;
165 }
166 else {
167 return PyFloat_FromDouble(x);
168 }
169}
170
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000172PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000173{
Brett Cannona721aba2016-09-09 14:57:09 -0700174 const char *s;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000175 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 Py_ssize_t len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200177 Py_buffer view = {NULL, NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200181 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000183 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200184 assert(PyUnicode_IS_ASCII(s_buffer));
185 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200186 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200187 assert(s != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000189 else if (PyBytes_Check(v)) {
190 s = PyBytes_AS_STRING(v);
191 len = PyBytes_GET_SIZE(v);
192 }
193 else if (PyByteArray_Check(v)) {
194 s = PyByteArray_AS_STRING(v);
195 len = PyByteArray_GET_SIZE(v);
196 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200197 else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
198 s = (const char *)view.buf;
199 len = view.len;
Martin Pantereeb896c2015-11-07 02:32:21 +0000200 /* Copy to NUL-terminated buffer. */
201 s_buffer = PyBytes_FromStringAndSize(s, len);
202 if (s_buffer == NULL) {
203 PyBuffer_Release(&view);
204 return NULL;
205 }
206 s = PyBytes_AS_STRING(s_buffer);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200207 }
208 else {
Ezio Melottia5b95992013-11-07 19:18:34 +0200209 PyErr_Format(PyExc_TypeError,
210 "float() argument must be a string or a number, not '%.200s'",
211 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 return NULL;
213 }
Brett Cannona721aba2016-09-09 14:57:09 -0700214 result = _Py_string_to_number_with_underscores(s, len, "float", v, v,
215 float_from_string_inner);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200216 PyBuffer_Release(&view);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000217 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000219}
220
Guido van Rossum234f9421993-06-17 12:35:49 +0000221static void
Fred Drakefd99de62000-07-09 05:02:18 +0000222float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 if (PyFloat_CheckExact(op)) {
Victor Stinner2ba59372020-06-05 00:50:05 +0200225 PyInterpreterState *interp = _PyInterpreterState_GET();
226 struct _Py_float_state *state = &interp->float_state;
Victor Stinnerbcb19832020-06-08 02:14:47 +0200227#ifdef Py_DEBUG
228 // float_dealloc() must not be called after _PyFloat_Fini()
229 assert(state->numfree != -1);
230#endif
Victor Stinner2ba59372020-06-05 00:50:05 +0200231 if (state->numfree >= PyFloat_MAXFREELIST) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000232 PyObject_FREE(op);
233 return;
234 }
Victor Stinner2ba59372020-06-05 00:50:05 +0200235 state->numfree++;
236 Py_SET_TYPE(op, (PyTypeObject *)state->free_list);
237 state->free_list = op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 }
239 else
240 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000241}
242
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000243double
Fred Drakefd99de62000-07-09 05:02:18 +0000244PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 PyNumberMethods *nb;
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300247 PyObject *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (op == NULL) {
251 PyErr_BadArgument();
252 return -1;
253 }
Tim Petersd2364e82001-11-01 20:09:42 +0000254
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300255 if (PyFloat_Check(op)) {
256 return PyFloat_AS_DOUBLE(op);
257 }
258
259 nb = Py_TYPE(op)->tp_as_number;
260 if (nb == NULL || nb->nb_float == NULL) {
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300261 if (nb && nb->nb_index) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300262 PyObject *res = _PyNumber_Index(op);
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300263 if (!res) {
264 return -1;
265 }
266 double val = PyLong_AsDouble(res);
267 Py_DECREF(res);
268 return val;
269 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300270 PyErr_Format(PyExc_TypeError, "must be real number, not %.50s",
Victor Stinner58ac7002020-02-07 03:04:21 +0100271 Py_TYPE(op)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 return -1;
273 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000274
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300275 res = (*nb->nb_float) (op);
276 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 return -1;
278 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300279 if (!PyFloat_CheckExact(res)) {
280 if (!PyFloat_Check(res)) {
281 PyErr_Format(PyExc_TypeError,
282 "%.50s.__float__ returned non-float (type %.50s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100283 Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name);
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300284 Py_DECREF(res);
285 return -1;
286 }
287 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
288 "%.50s.__float__ returned non-float (type %.50s). "
289 "The ability to return an instance of a strict subclass of float "
290 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner58ac7002020-02-07 03:04:21 +0100291 Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name)) {
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300292 Py_DECREF(res);
293 return -1;
294 }
295 }
Tim Petersd2364e82001-11-01 20:09:42 +0000296
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300297 val = PyFloat_AS_DOUBLE(res);
298 Py_DECREF(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000300}
301
Neil Schemenauer32117e52001-01-04 01:44:34 +0000302/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000303 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000304 set to NULL, and the function invoking this macro returns NULL. If
Serhiy Storchaka95949422013-08-27 19:40:23 +0300305 obj is not of float or int type, Py_NotImplemented is incref'ed,
Tim Peters77d8a4f2001-12-11 20:31:34 +0000306 stored in obj, and returned from the function invoking this macro.
307*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308#define CONVERT_TO_DOUBLE(obj, dbl) \
309 if (PyFloat_Check(obj)) \
310 dbl = PyFloat_AS_DOUBLE(obj); \
311 else if (convert_to_double(&(obj), &(dbl)) < 0) \
312 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000313
Eric Smith0923d1d2009-04-16 20:16:10 +0000314/* Methods */
315
Neil Schemenauer32117e52001-01-04 01:44:34 +0000316static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000317convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000318{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200319 PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (PyLong_Check(obj)) {
322 *dbl = PyLong_AsDouble(obj);
323 if (*dbl == -1.0 && PyErr_Occurred()) {
324 *v = NULL;
325 return -1;
326 }
327 }
328 else {
329 Py_INCREF(Py_NotImplemented);
330 *v = Py_NotImplemented;
331 return -1;
332 }
333 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000334}
335
Eric Smith0923d1d2009-04-16 20:16:10 +0000336static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000337float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000338{
339 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200340 char *buf;
341
342 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
343 'r', 0,
344 Py_DTSF_ADD_DOT_0,
345 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000346 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000347 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200348 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000349 PyMem_Free(buf);
350 return result;
351}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000352
Tim Peters307fa782004-09-23 08:06:40 +0000353/* Comparison is pretty much a nightmare. When comparing float to float,
354 * we do it as straightforwardly (and long-windedly) as conceivable, so
355 * that, e.g., Python x == y delivers the same result as the platform
356 * C x == y when x and/or y is a NaN.
357 * When mixing float with an integer type, there's no good *uniform* approach.
358 * Converting the double to an integer obviously doesn't work, since we
359 * may lose info from fractional bits. Converting the integer to a double
Serhiy Storchaka95949422013-08-27 19:40:23 +0300360 * also has two failure modes: (1) an int may trigger overflow (too
Tim Peters307fa782004-09-23 08:06:40 +0000361 * 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 +0200362 * 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 +0000363 * 63 bits of precision, but a C double probably has only 53), and then
364 * we can falsely claim equality when low-order integer bits are lost by
365 * coercion to double. So this part is painful too.
366 */
367
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000368static PyObject*
369float_richcompare(PyObject *v, PyObject *w, int op)
370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 double i, j;
372 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 assert(PyFloat_Check(v));
375 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 /* Switch on the type of w. Set i and j to doubles to be compared,
378 * and op to the richcomp to use.
379 */
380 if (PyFloat_Check(w))
381 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 else if (!Py_IS_FINITE(i)) {
384 if (PyLong_Check(w))
385 /* If i is an infinity, its magnitude exceeds any
386 * finite integer, so it doesn't matter which int we
387 * compare i with. If i is a NaN, similarly.
388 */
389 j = 0.0;
390 else
391 goto Unimplemented;
392 }
Tim Peters307fa782004-09-23 08:06:40 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 else if (PyLong_Check(w)) {
395 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
396 int wsign = _PyLong_Sign(w);
397 size_t nbits;
398 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 if (vsign != wsign) {
401 /* Magnitudes are irrelevant -- the signs alone
402 * determine the outcome.
403 */
404 i = (double)vsign;
405 j = (double)wsign;
406 goto Compare;
407 }
408 /* The signs are the same. */
409 /* Convert w to a double if it fits. In particular, 0 fits. */
410 nbits = _PyLong_NumBits(w);
411 if (nbits == (size_t)-1 && PyErr_Occurred()) {
412 /* This long is so large that size_t isn't big enough
413 * to hold the # of bits. Replace with little doubles
414 * that give the same outcome -- w is so large that
415 * its magnitude must exceed the magnitude of any
416 * finite float.
417 */
418 PyErr_Clear();
419 i = (double)vsign;
420 assert(wsign != 0);
421 j = wsign * 2.0;
422 goto Compare;
423 }
424 if (nbits <= 48) {
425 j = PyLong_AsDouble(w);
426 /* It's impossible that <= 48 bits overflowed. */
427 assert(j != -1.0 || ! PyErr_Occurred());
428 goto Compare;
429 }
430 assert(wsign != 0); /* else nbits was 0 */
431 assert(vsign != 0); /* if vsign were 0, then since wsign is
432 * not 0, we would have taken the
433 * vsign != wsign branch at the start */
434 /* We want to work with non-negative numbers. */
435 if (vsign < 0) {
436 /* "Multiply both sides" by -1; this also swaps the
437 * comparator.
438 */
439 i = -i;
440 op = _Py_SwappedOp[op];
441 }
442 assert(i > 0.0);
443 (void) frexp(i, &exponent);
444 /* exponent is the # of bits in v before the radix point;
445 * we know that nbits (the # of bits in w) > 48 at this point
446 */
447 if (exponent < 0 || (size_t)exponent < nbits) {
448 i = 1.0;
449 j = 2.0;
450 goto Compare;
451 }
452 if ((size_t)exponent > nbits) {
453 i = 2.0;
454 j = 1.0;
455 goto Compare;
456 }
457 /* v and w have the same number of bits before the radix
Serhiy Storchaka95949422013-08-27 19:40:23 +0300458 * point. Construct two ints that have the same comparison
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 * outcome.
460 */
461 {
462 double fracpart;
463 double intpart;
464 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 PyObject *vv = NULL;
466 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 if (wsign < 0) {
469 ww = PyNumber_Negative(w);
470 if (ww == NULL)
471 goto Error;
472 }
473 else
474 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 fracpart = modf(i, &intpart);
477 vv = PyLong_FromDouble(intpart);
478 if (vv == NULL)
479 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (fracpart != 0.0) {
482 /* Shift left, and or a 1 bit into vv
483 * to represent the lost fraction.
484 */
485 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000486
Serhiy Storchakaa5119e72019-05-19 14:14:38 +0300487 temp = _PyLong_Lshift(ww, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (temp == NULL)
489 goto Error;
490 Py_DECREF(ww);
491 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000492
Serhiy Storchakaa5119e72019-05-19 14:14:38 +0300493 temp = _PyLong_Lshift(vv, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (temp == NULL)
495 goto Error;
496 Py_DECREF(vv);
497 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000498
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300499 temp = PyNumber_Or(vv, _PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 if (temp == NULL)
501 goto Error;
502 Py_DECREF(vv);
503 vv = temp;
504 }
Tim Peters307fa782004-09-23 08:06:40 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 r = PyObject_RichCompareBool(vv, ww, op);
507 if (r < 0)
508 goto Error;
509 result = PyBool_FromLong(r);
510 Error:
511 Py_XDECREF(vv);
512 Py_XDECREF(ww);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 return result;
514 }
515 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000516
Serhiy Storchaka95949422013-08-27 19:40:23 +0300517 else /* w isn't float or int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000519
520 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 switch (op) {
522 case Py_EQ:
523 r = i == j;
524 break;
525 case Py_NE:
526 r = i != j;
527 break;
528 case Py_LE:
529 r = i <= j;
530 break;
531 case Py_GE:
532 r = i >= j;
533 break;
534 case Py_LT:
535 r = i < j;
536 break;
537 case Py_GT:
538 r = i > j;
539 break;
540 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000542
543 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500544 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000545}
546
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000547static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000548float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000551}
552
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000553static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000554float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 double a,b;
557 CONVERT_TO_DOUBLE(v, a);
558 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 a = a + b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000561}
562
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000563static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000564float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 double a,b;
567 CONVERT_TO_DOUBLE(v, a);
568 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 a = a - b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000571}
572
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000573static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000574float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 double a,b;
577 CONVERT_TO_DOUBLE(v, a);
578 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 a = a * b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000581}
582
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000583static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000584float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 double a,b;
587 CONVERT_TO_DOUBLE(v, a);
588 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (b == 0.0) {
590 PyErr_SetString(PyExc_ZeroDivisionError,
591 "float division by zero");
592 return NULL;
593 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 a = a / b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000596}
597
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000598static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000599float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 double vx, wx;
602 double mod;
603 CONVERT_TO_DOUBLE(v, vx);
604 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (wx == 0.0) {
606 PyErr_SetString(PyExc_ZeroDivisionError,
607 "float modulo");
608 return NULL;
609 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000611 if (mod) {
612 /* ensure the remainder has the same sign as the denominator */
613 if ((wx < 0) != (mod < 0)) {
614 mod += wx;
615 }
616 }
617 else {
618 /* the remainder is zero, and in the presence of signed zeroes
619 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000620 it has the same sign as the denominator. */
621 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000624}
625
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900626static void
627_float_div_mod(double vx, double wx, double *floordiv, double *mod)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000628{
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900629 double div;
630 *mod = fmod(vx, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 /* fmod is typically exact, so vx-mod is *mathematically* an
632 exact multiple of wx. But this is fp arithmetic, and fp
633 vx - mod is an approximation; the result is that div may
634 not be an exact integral value after the division, although
635 it will always be very close to one.
636 */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900637 div = (vx - *mod) / wx;
638 if (*mod) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 /* ensure the remainder has the same sign as the denominator */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900640 if ((wx < 0) != (*mod < 0)) {
641 *mod += wx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 div -= 1.0;
643 }
644 }
645 else {
646 /* the remainder is zero, and in the presence of signed zeroes
647 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000648 it has the same sign as the denominator. */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900649 *mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 }
651 /* snap quotient to nearest integral value */
652 if (div) {
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900653 *floordiv = floor(div);
654 if (div - *floordiv > 0.5) {
655 *floordiv += 1.0;
Mark Dickinsonbe8147b2020-02-02 11:37:02 +0000656 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 }
658 else {
659 /* div is zero - get the same sign as the true quotient */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900660 *floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 }
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900662}
663
664static PyObject *
665float_divmod(PyObject *v, PyObject *w)
666{
Mark Dickinsonbe8147b2020-02-02 11:37:02 +0000667 double vx, wx;
668 double mod, floordiv;
669 CONVERT_TO_DOUBLE(v, vx);
670 CONVERT_TO_DOUBLE(w, wx);
671 if (wx == 0.0) {
672 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
673 return NULL;
674 }
675 _float_div_mod(vx, wx, &floordiv, &mod);
676 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000677}
678
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000679static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000680float_floor_div(PyObject *v, PyObject *w)
681{
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900682 double vx, wx;
683 double mod, floordiv;
684 CONVERT_TO_DOUBLE(v, vx);
685 CONVERT_TO_DOUBLE(w, wx);
686 if (wx == 0.0) {
687 PyErr_SetString(PyExc_ZeroDivisionError, "float floor division by zero");
688 return NULL;
689 }
690 _float_div_mod(vx, wx, &floordiv, &mod);
691 return PyFloat_FromDouble(floordiv);
Tim Peters63a35712001-12-11 19:57:24 +0000692}
693
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000694/* determine whether x is an odd integer or not; assumes that
695 x is not an infinity or nan. */
696#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
697
Tim Peters63a35712001-12-11 19:57:24 +0000698static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000699float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 double iv, iw, ix;
702 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if ((PyObject *)z != Py_None) {
705 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
706 "allowed unless all arguments are integers");
707 return NULL;
708 }
Tim Peters32f453e2001-09-03 08:35:41 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 CONVERT_TO_DOUBLE(v, iv);
711 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 /* Sort out special cases here instead of relying on pow() */
714 if (iw == 0) { /* v**0 is 1, even 0**0 */
715 return PyFloat_FromDouble(1.0);
716 }
717 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
718 return PyFloat_FromDouble(iv);
719 }
720 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
721 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
722 }
723 if (Py_IS_INFINITY(iw)) {
724 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
725 * abs(v) > 1 (including case where v infinite)
726 *
727 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
728 * abs(v) > 1 (including case where v infinite)
729 */
730 iv = fabs(iv);
731 if (iv == 1.0)
732 return PyFloat_FromDouble(1.0);
733 else if ((iw > 0.0) == (iv > 1.0))
734 return PyFloat_FromDouble(fabs(iw)); /* return inf */
735 else
736 return PyFloat_FromDouble(0.0);
737 }
738 if (Py_IS_INFINITY(iv)) {
739 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
740 * both cases, we need to add the appropriate sign if w is
741 * an odd integer.
742 */
743 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
744 if (iw > 0.0)
745 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
746 else
747 return PyFloat_FromDouble(iw_is_odd ?
748 copysign(0.0, iv) : 0.0);
749 }
750 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
751 (already dealt with above), and an error
752 if w is negative. */
753 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
754 if (iw < 0.0) {
755 PyErr_SetString(PyExc_ZeroDivisionError,
756 "0.0 cannot be raised to a "
757 "negative power");
758 return NULL;
759 }
760 /* use correct sign if iw is odd */
761 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
762 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 if (iv < 0.0) {
765 /* Whether this is an error is a mess, and bumps into libm
766 * bugs so we have to figure it out ourselves.
767 */
768 if (iw != floor(iw)) {
769 /* Negative numbers raised to fractional powers
770 * become complex.
771 */
772 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
773 }
774 /* iw is an exact integer, albeit perhaps a very large
775 * one. Replace iv by its absolute value and remember
776 * to negate the pow result if iw is odd.
777 */
778 iv = -iv;
779 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
780 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
783 /* (-1) ** large_integer also ends up here. Here's an
784 * extract from the comments for the previous
785 * implementation explaining why this special case is
786 * necessary:
787 *
788 * -1 raised to an exact integer should never be exceptional.
789 * Alas, some libms (chiefly glibc as of early 2003) return
790 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
791 * happen to be representable in a *C* integer. That's a
792 * bug.
793 */
794 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
795 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 /* Now iv and iw are finite, iw is nonzero, and iv is
798 * positive and not equal to 1.0. We finally allow
799 * the platform pow to step in and do the rest.
800 */
801 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 ix = pow(iv, iw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 Py_ADJUST_ERANGE1(ix);
804 if (negate_result)
805 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 if (errno != 0) {
808 /* We don't expect any errno value other than ERANGE, but
809 * the range of libm bugs appears unbounded.
810 */
811 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
812 PyExc_ValueError);
813 return NULL;
814 }
815 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000816}
817
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000818#undef DOUBLE_IS_ODD_INTEGER
819
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000820static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000821float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000824}
825
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000826static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000827float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000830}
831
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000832static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000833float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000836}
837
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200838/*[clinic input]
839float.is_integer
840
841Return True if the float is an integer.
842[clinic start generated code]*/
843
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000844static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200845float_is_integer_impl(PyObject *self)
846/*[clinic end generated code: output=7112acf95a4d31ea input=311810d3f777e10d]*/
Christian Heimes53876d92008-04-19 00:31:39 +0000847{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200848 double x = PyFloat_AsDouble(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 PyObject *o;
850
851 if (x == -1.0 && PyErr_Occurred())
852 return NULL;
853 if (!Py_IS_FINITE(x))
854 Py_RETURN_FALSE;
855 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 o = (floor(x) == x) ? Py_True : Py_False;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 if (errno != 0) {
858 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
859 PyExc_ValueError);
860 return NULL;
861 }
862 Py_INCREF(o);
863 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000864}
865
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200866/*[clinic input]
867float.__trunc__
868
869Return the Integral closest to x between 0 and x.
870[clinic start generated code]*/
871
Christian Heimes53876d92008-04-19 00:31:39 +0000872static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200873float___trunc___impl(PyObject *self)
874/*[clinic end generated code: output=dd3e289dd4c6b538 input=591b9ba0d650fdff]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000875{
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500876 return PyLong_FromDouble(PyFloat_AS_DOUBLE(self));
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000877}
878
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +0300879/*[clinic input]
880float.__floor__
881
882Return the floor as an Integral.
883[clinic start generated code]*/
884
885static PyObject *
886float___floor___impl(PyObject *self)
887/*[clinic end generated code: output=e0551dbaea8c01d1 input=77bb13eb12e268df]*/
888{
889 double x = PyFloat_AS_DOUBLE(self);
890 return PyLong_FromDouble(floor(x));
891}
892
893/*[clinic input]
894float.__ceil__
895
896Return the ceiling as an Integral.
897[clinic start generated code]*/
898
899static PyObject *
900float___ceil___impl(PyObject *self)
901/*[clinic end generated code: output=a2fd8858f73736f9 input=79e41ae94aa0a516]*/
902{
903 double x = PyFloat_AS_DOUBLE(self);
904 return PyLong_FromDouble(ceil(x));
905}
906
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000907/* double_round: rounds a finite double to the closest multiple of
908 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
909 ndigits <= 323). Returns a Python float, or sets a Python error and
910 returns NULL on failure (OverflowError and memory errors are possible). */
911
912#ifndef PY_NO_SHORT_FLOAT_REPR
913/* version of double_round that uses the correctly-rounded string<->double
914 conversions from Python/dtoa.c */
915
916static PyObject *
917double_round(double x, int ndigits) {
918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 double rounded;
920 Py_ssize_t buflen, mybuflen=100;
921 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
922 int decpt, sign;
923 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000924 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000927 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000929 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 if (buf == NULL) {
931 PyErr_NoMemory();
932 return NULL;
933 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
936 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
937 buflen = buf_end - buf;
938 if (buflen + 8 > mybuflen) {
939 mybuflen = buflen+8;
940 mybuf = (char *)PyMem_Malloc(mybuflen);
941 if (mybuf == NULL) {
942 PyErr_NoMemory();
943 goto exit;
944 }
945 }
946 /* copy buf to mybuf, adding exponent, sign and leading 0 */
947 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
948 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 /* and convert the resulting string back to a double */
951 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000952 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000954 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 if (errno == ERANGE && fabs(rounded) >= 1.)
956 PyErr_SetString(PyExc_OverflowError,
957 "rounded value too large to represent");
958 else
959 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 /* done computing value; now clean up */
962 if (mybuf != shortbuf)
963 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000964 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 _Py_dg_freedtoa(buf);
966 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000967}
968
969#else /* PY_NO_SHORT_FLOAT_REPR */
970
971/* fallback version, to be used when correctly rounded binary<->decimal
972 conversions aren't available */
973
974static PyObject *
975double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 double pow1, pow2, y, z;
977 if (ndigits >= 0) {
978 if (ndigits > 22) {
979 /* pow1 and pow2 are each safe from overflow, but
980 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
981 pow1 = pow(10.0, (double)(ndigits-22));
982 pow2 = 1e22;
983 }
984 else {
985 pow1 = pow(10.0, (double)ndigits);
986 pow2 = 1.0;
987 }
988 y = (x*pow1)*pow2;
989 /* if y overflows, then rounded value is exactly x */
990 if (!Py_IS_FINITE(y))
991 return PyFloat_FromDouble(x);
992 }
993 else {
994 pow1 = pow(10.0, (double)-ndigits);
995 pow2 = 1.0; /* unused; silences a gcc compiler warning */
996 y = x / pow1;
997 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 z = round(y);
1000 if (fabs(y-z) == 0.5)
1001 /* halfway between two integers; use round-half-even */
1002 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 if (ndigits >= 0)
1005 z = (z / pow2) / pow1;
1006 else
1007 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 /* if computation resulted in overflow, raise OverflowError */
1010 if (!Py_IS_FINITE(z)) {
1011 PyErr_SetString(PyExc_OverflowError,
1012 "overflow occurred during round");
1013 return NULL;
1014 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001017}
1018
1019#endif /* PY_NO_SHORT_FLOAT_REPR */
1020
1021/* round a Python float v to the closest multiple of 10**-ndigits */
1022
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001023/*[clinic input]
1024float.__round__
1025
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001026 ndigits as o_ndigits: object = None
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001027 /
1028
1029Return the Integral closest to x, rounding half toward even.
1030
1031When an argument is passed, work like built-in round(x, ndigits).
1032[clinic start generated code]*/
1033
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001034static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001035float___round___impl(PyObject *self, PyObject *o_ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001036/*[clinic end generated code: output=374c36aaa0f13980 input=fc0fe25924fbc9ed]*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 double x, rounded;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001040
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001041 x = PyFloat_AsDouble(self);
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001042 if (o_ndigits == Py_None) {
Steve Dowercb39d1f2015-04-15 16:10:59 -04001043 /* single-argument round or with None ndigits:
1044 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 rounded = round(x);
1046 if (fabs(x-rounded) == 0.5)
1047 /* halfway case: round to even */
1048 rounded = 2.0*round(x/2.0);
1049 return PyLong_FromDouble(rounded);
1050 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 /* interpret second argument as a Py_ssize_t; clips on overflow */
1053 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1054 if (ndigits == -1 && PyErr_Occurred())
1055 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 /* nans and infinities round to themselves */
1058 if (!Py_IS_FINITE(x))
1059 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1062 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1063 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001064#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1065#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 if (ndigits > NDIGITS_MAX)
1067 /* return x */
1068 return PyFloat_FromDouble(x);
1069 else if (ndigits < NDIGITS_MIN)
1070 /* return 0.0, but with sign of x */
1071 return PyFloat_FromDouble(0.0*x);
1072 else
1073 /* finite x, and ndigits is not unreasonably large */
1074 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001075#undef NDIGITS_MAX
1076#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001077}
1078
1079static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001080float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 if (PyFloat_CheckExact(v))
1083 Py_INCREF(v);
1084 else
1085 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1086 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001087}
1088
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001089/*[clinic input]
1090float.conjugate
1091
1092Return self, the complex conjugate of any float.
1093[clinic start generated code]*/
1094
1095static PyObject *
1096float_conjugate_impl(PyObject *self)
1097/*[clinic end generated code: output=8ca292c2479194af input=82ba6f37a9ff91dd]*/
1098{
1099 return float_float(self);
1100}
1101
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001102/* turn ASCII hex characters into integer values and vice versa */
1103
1104static char
1105char_from_hex(int x)
1106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001108 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001109}
1110
1111static int
1112hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 int x;
1114 switch(c) {
1115 case '0':
1116 x = 0;
1117 break;
1118 case '1':
1119 x = 1;
1120 break;
1121 case '2':
1122 x = 2;
1123 break;
1124 case '3':
1125 x = 3;
1126 break;
1127 case '4':
1128 x = 4;
1129 break;
1130 case '5':
1131 x = 5;
1132 break;
1133 case '6':
1134 x = 6;
1135 break;
1136 case '7':
1137 x = 7;
1138 break;
1139 case '8':
1140 x = 8;
1141 break;
1142 case '9':
1143 x = 9;
1144 break;
1145 case 'a':
1146 case 'A':
1147 x = 10;
1148 break;
1149 case 'b':
1150 case 'B':
1151 x = 11;
1152 break;
1153 case 'c':
1154 case 'C':
1155 x = 12;
1156 break;
1157 case 'd':
1158 case 'D':
1159 x = 13;
1160 break;
1161 case 'e':
1162 case 'E':
1163 x = 14;
1164 break;
1165 case 'f':
1166 case 'F':
1167 x = 15;
1168 break;
1169 default:
1170 x = -1;
1171 break;
1172 }
1173 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001174}
1175
1176/* convert a float to a hexadecimal string */
1177
1178/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1179 of the form 4k+1. */
1180#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1181
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001182/*[clinic input]
1183float.hex
1184
1185Return a hexadecimal representation of a floating-point number.
1186
1187>>> (-0.1).hex()
1188'-0x1.999999999999ap-4'
1189>>> 3.14159.hex()
1190'0x1.921f9f01b866ep+1'
1191[clinic start generated code]*/
1192
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001193static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001194float_hex_impl(PyObject *self)
1195/*[clinic end generated code: output=0ebc9836e4d302d4 input=bec1271a33d47e67]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 double x, m;
1198 int e, shift, i, si, esign;
1199 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1200 trailing NUL byte. */
1201 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001202
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001203 CONVERT_TO_DOUBLE(self, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001206 return float_repr((PyFloatObject *)self);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001209 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 return PyUnicode_FromString("-0x0.0p+0");
1211 else
1212 return PyUnicode_FromString("0x0.0p+0");
1213 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001216 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 m = ldexp(m, shift);
1218 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 si = 0;
1221 s[si] = char_from_hex((int)m);
1222 si++;
1223 m -= (int)m;
1224 s[si] = '.';
1225 si++;
1226 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1227 m *= 16.0;
1228 s[si] = char_from_hex((int)m);
1229 si++;
1230 m -= (int)m;
1231 }
1232 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (e < 0) {
1235 esign = (int)'-';
1236 e = -e;
1237 }
1238 else
1239 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (x < 0.0)
1242 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1243 else
1244 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001245}
1246
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001247/* Convert a hexadecimal string to a float. */
1248
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001249/*[clinic input]
1250@classmethod
1251float.fromhex
1252
1253 string: object
1254 /
1255
1256Create a floating-point number from a hexadecimal string.
1257
1258>>> float.fromhex('0x1.ffffp10')
12592047.984375
1260>>> float.fromhex('-0x1p-1074')
1261-5e-324
1262[clinic start generated code]*/
1263
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001264static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001265float_fromhex(PyTypeObject *type, PyObject *string)
1266/*[clinic end generated code: output=46c0274d22b78e82 input=0407bebd354bca89]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001267{
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001268 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 double x;
1270 long exp, top_exp, lsb, key_digit;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001271 const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 int half_eps, digit, round_up, negate=0;
1273 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 /*
1276 * For the sake of simplicity and correctness, we impose an artificial
1277 * limit on ndigits, the total number of hex digits in the coefficient
1278 * The limit is chosen to ensure that, writing exp for the exponent,
1279 *
1280 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1281 * guaranteed to overflow (provided it's nonzero)
1282 *
1283 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1284 * guaranteed to underflow to 0.
1285 *
1286 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1287 * overflow in the calculation of exp and top_exp below.
1288 *
1289 * More specifically, ndigits is assumed to satisfy the following
1290 * inequalities:
1291 *
1292 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1293 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1294 *
1295 * If either of these inequalities is not satisfied, a ValueError is
1296 * raised. Otherwise, write x for the value of the hex string, and
1297 * assume x is nonzero. Then
1298 *
1299 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1300 *
1301 * Now if exp > LONG_MAX/2 then:
1302 *
1303 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1304 * = DBL_MAX_EXP
1305 *
1306 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1307 * double, so overflows. If exp < LONG_MIN/2, then
1308 *
1309 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1310 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1311 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1312 *
1313 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1314 * when converted to a C double.
1315 *
1316 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1317 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1318 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001319
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001320 s = PyUnicode_AsUTF8AndSize(string, &length);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 if (s == NULL)
1322 return NULL;
1323 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 /********************
1326 * Parse the string *
1327 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 /* leading whitespace */
1330 while (Py_ISSPACE(*s))
1331 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 /* infinities and nans */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001334 x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 if (coeff_end != s) {
1336 s = coeff_end;
1337 goto finished;
1338 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 /* optional sign */
1341 if (*s == '-') {
1342 s++;
1343 negate = 1;
1344 }
1345 else if (*s == '+')
1346 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 /* [0x] */
1349 s_store = s;
1350 if (*s == '0') {
1351 s++;
1352 if (*s == 'x' || *s == 'X')
1353 s++;
1354 else
1355 s = s_store;
1356 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 /* coefficient: <integer> [. <fraction>] */
1359 coeff_start = s;
1360 while (hex_from_char(*s) >= 0)
1361 s++;
1362 s_store = s;
1363 if (*s == '.') {
1364 s++;
1365 while (hex_from_char(*s) >= 0)
1366 s++;
1367 coeff_end = s-1;
1368 }
1369 else
1370 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 /* ndigits = total # of hex digits; fdigits = # after point */
1373 ndigits = coeff_end - coeff_start;
1374 fdigits = coeff_end - s_store;
1375 if (ndigits == 0)
1376 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001377 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1378 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 /* [p <exponent>] */
1382 if (*s == 'p' || *s == 'P') {
1383 s++;
1384 exp_start = s;
1385 if (*s == '-' || *s == '+')
1386 s++;
1387 if (!('0' <= *s && *s <= '9'))
1388 goto parse_error;
1389 s++;
1390 while ('0' <= *s && *s <= '9')
1391 s++;
1392 exp = strtol(exp_start, NULL, 10);
1393 }
1394 else
1395 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001396
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001397/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1399 coeff_end-(j) : \
1400 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 /*******************************************
1403 * Compute rounded value of the hex string *
1404 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 /* Discard leading zeros, and catch extreme overflow and underflow */
1407 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1408 ndigits--;
1409 if (ndigits == 0 || exp < LONG_MIN/2) {
1410 x = 0.0;
1411 goto finished;
1412 }
1413 if (exp > LONG_MAX/2)
1414 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 /* Adjust exponent for fractional part. */
1417 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1420 top_exp = exp + 4*((long)ndigits - 1);
1421 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1422 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 /* catch almost all nonextreme cases of overflow and underflow here */
1425 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1426 x = 0.0;
1427 goto finished;
1428 }
1429 if (top_exp > DBL_MAX_EXP)
1430 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 /* lsb = exponent of least significant bit of the *rounded* value.
1433 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001434 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 x = 0.0;
1437 if (exp >= lsb) {
1438 /* no rounding required */
1439 for (i = ndigits-1; i >= 0; i--)
1440 x = 16.0*x + HEX_DIGIT(i);
1441 x = ldexp(x, (int)(exp));
1442 goto finished;
1443 }
1444 /* rounding required. key_digit is the index of the hex digit
1445 containing the first bit to be rounded away. */
1446 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1447 key_digit = (lsb - exp - 1) / 4;
1448 for (i = ndigits-1; i > key_digit; i--)
1449 x = 16.0*x + HEX_DIGIT(i);
1450 digit = HEX_DIGIT(key_digit);
1451 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1454 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1455 if ((digit & half_eps) != 0) {
1456 round_up = 0;
1457 if ((digit & (3*half_eps-1)) != 0 ||
1458 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1459 round_up = 1;
1460 else
1461 for (i = key_digit-1; i >= 0; i--)
1462 if (HEX_DIGIT(i) != 0) {
1463 round_up = 1;
1464 break;
1465 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001466 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 x += 2*half_eps;
1468 if (top_exp == DBL_MAX_EXP &&
1469 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1470 /* overflow corner case: pre-rounded value <
1471 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1472 goto overflow_error;
1473 }
1474 }
1475 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001476
1477 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 /* optional trailing whitespace leading to the end of the string */
1479 while (Py_ISSPACE(*s))
1480 s++;
1481 if (s != s_end)
1482 goto parse_error;
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001483 result = PyFloat_FromDouble(negate ? -x : x);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001484 if (type != &PyFloat_Type && result != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001485 Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001486 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001488
1489 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 PyErr_SetString(PyExc_OverflowError,
1491 "hexadecimal value too large to represent as a float");
1492 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001493
1494 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 PyErr_SetString(PyExc_ValueError,
1496 "invalid hexadecimal floating-point string");
1497 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001498
1499 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 PyErr_SetString(PyExc_ValueError,
1501 "hexadecimal string too long to convert");
1502 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001503}
1504
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001505/*[clinic input]
1506float.as_integer_ratio
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001507
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001508Return integer ratio.
1509
1510Return a pair of integers, whose ratio is exactly equal to the original float
1511and with a positive denominator.
1512
1513Raise OverflowError on infinities and a ValueError on NaNs.
1514
1515>>> (10.0).as_integer_ratio()
1516(10, 1)
1517>>> (0.0).as_integer_ratio()
1518(0, 1)
1519>>> (-.25).as_integer_ratio()
1520(-1, 4)
1521[clinic start generated code]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001522
Christian Heimes26855632008-01-27 23:50:43 +00001523static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001524float_as_integer_ratio_impl(PyObject *self)
1525/*[clinic end generated code: output=65f25f0d8d30a712 input=e21d08b4630c2e44]*/
Christian Heimes26855632008-01-27 23:50:43 +00001526{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001527 double self_double;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 double float_part;
1529 int exponent;
1530 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 PyObject *py_exponent = NULL;
1533 PyObject *numerator = NULL;
1534 PyObject *denominator = NULL;
1535 PyObject *result_pair = NULL;
1536 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001537
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001538 CONVERT_TO_DOUBLE(self, self_double);
Christian Heimes26855632008-01-27 23:50:43 +00001539
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001540 if (Py_IS_INFINITY(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001541 PyErr_SetString(PyExc_OverflowError,
1542 "cannot convert Infinity to integer ratio");
1543 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001545 if (Py_IS_NAN(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001546 PyErr_SetString(PyExc_ValueError,
1547 "cannot convert NaN to integer ratio");
1548 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 }
Christian Heimes26855632008-01-27 23:50:43 +00001550
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001551 float_part = frexp(self_double, &exponent); /* self_double == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1554 float_part *= 2.0;
1555 exponent--;
1556 }
1557 /* self == float_part * 2**exponent exactly and float_part is integral.
1558 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1559 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 numerator = PyLong_FromDouble(float_part);
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001562 if (numerator == NULL)
1563 goto error;
1564 denominator = PyLong_FromLong(1);
1565 if (denominator == NULL)
1566 goto error;
1567 py_exponent = PyLong_FromLong(Py_ABS(exponent));
1568 if (py_exponent == NULL)
1569 goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 /* fold in 2**exponent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 if (exponent > 0) {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001573 Py_SETREF(numerator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001574 long_methods->nb_lshift(numerator, py_exponent));
1575 if (numerator == NULL)
1576 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 }
1578 else {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001579 Py_SETREF(denominator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001580 long_methods->nb_lshift(denominator, py_exponent));
1581 if (denominator == NULL)
1582 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 }
1584
1585 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001586
Christian Heimes26855632008-01-27 23:50:43 +00001587error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 Py_XDECREF(py_exponent);
1589 Py_XDECREF(denominator);
1590 Py_XDECREF(numerator);
1591 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001592}
1593
Jeremy Hylton938ace62002-07-17 16:30:39 +00001594static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001595float_subtype_new(PyTypeObject *type, PyObject *x);
1596
1597/*[clinic input]
1598@classmethod
1599float.__new__ as float_new
Serhiy Storchakaba85d692017-03-30 09:09:41 +03001600 x: object(c_default="_PyLong_Zero") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001601 /
1602
1603Convert a string or number to a floating point number, if possible.
1604[clinic start generated code]*/
Guido van Rossumbef14172001-08-29 15:47:46 +00001605
Tim Peters6d6c1a32001-08-02 04:15:00 +00001606static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001607float_new_impl(PyTypeObject *type, PyObject *x)
Serhiy Storchakabae68812017-04-05 12:00:42 +03001608/*[clinic end generated code: output=ccf1e8dc460ba6ba input=540ee77c204ff87a]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00001609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 if (type != &PyFloat_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001611 return float_subtype_new(type, x); /* Wimp out */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 /* If it's a string, but not a string subclass, use
1613 PyFloat_FromString. */
1614 if (PyUnicode_CheckExact(x))
1615 return PyFloat_FromString(x);
1616 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001617}
1618
Guido van Rossumbef14172001-08-29 15:47:46 +00001619/* Wimpy, slow approach to tp_new calls for subtypes of float:
1620 first create a regular float from whatever arguments we got,
1621 then allocate a subtype instance and initialize its ob_fval
1622 from the regular float. The regular float is then thrown away.
1623*/
1624static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001625float_subtype_new(PyTypeObject *type, PyObject *x)
Guido van Rossumbef14172001-08-29 15:47:46 +00001626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 assert(PyType_IsSubtype(type, &PyFloat_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001630 tmp = float_new_impl(&PyFloat_Type, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 if (tmp == NULL)
1632 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001633 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 newobj = type->tp_alloc(type, 0);
1635 if (newobj == NULL) {
1636 Py_DECREF(tmp);
1637 return NULL;
1638 }
1639 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1640 Py_DECREF(tmp);
1641 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001642}
1643
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001644/*[clinic input]
1645float.__getnewargs__
1646[clinic start generated code]*/
1647
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001648static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001649float___getnewargs___impl(PyObject *self)
1650/*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001651{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001652 return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001653}
1654
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001655/* this is for the benefit of the pack/unpack routines below */
1656
1657typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001659} float_format_type;
1660
1661static float_format_type double_format, float_format;
1662static float_format_type detected_double_format, detected_float_format;
1663
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001664/*[clinic input]
1665@classmethod
1666float.__getformat__
1667
1668 typestr: str
1669 Must be 'double' or 'float'.
1670 /
1671
1672You probably don't want to use this function.
1673
1674It exists mainly to be used in Python's test suite.
1675
1676This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
1677little-endian' best describes the format of floating point numbers used by the
1678C type named by typestr.
1679[clinic start generated code]*/
1680
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001681static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001682float___getformat___impl(PyTypeObject *type, const char *typestr)
1683/*[clinic end generated code: output=2bfb987228cc9628 input=d5a52600f835ad67]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001686
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001687 if (strcmp(typestr, "double") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 r = double_format;
1689 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001690 else if (strcmp(typestr, "float") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 r = float_format;
1692 }
1693 else {
1694 PyErr_SetString(PyExc_ValueError,
1695 "__getformat__() argument 1 must be "
1696 "'double' or 'float'");
1697 return NULL;
1698 }
1699
1700 switch (r) {
1701 case unknown_format:
1702 return PyUnicode_FromString("unknown");
1703 case ieee_little_endian_format:
1704 return PyUnicode_FromString("IEEE, little-endian");
1705 case ieee_big_endian_format:
1706 return PyUnicode_FromString("IEEE, big-endian");
1707 default:
Victor Stinner04394df2019-11-18 17:39:48 +01001708 PyErr_SetString(PyExc_RuntimeError,
1709 "insane float_format or double_format");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 return NULL;
1711 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001712}
1713
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001714/*[clinic input]
1715@classmethod
1716float.__set_format__
1717
1718 typestr: str
1719 Must be 'double' or 'float'.
1720 fmt: str
1721 Must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian',
1722 and in addition can only be one of the latter two if it appears to
1723 match the underlying C reality.
1724 /
1725
1726You probably don't want to use this function.
1727
1728It exists mainly to be used in Python's test suite.
1729
1730Override the automatic determination of C-level floating point type.
1731This affects how floats are converted to and from binary strings.
1732[clinic start generated code]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001733
1734static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001735float___set_format___impl(PyTypeObject *type, const char *typestr,
1736 const char *fmt)
1737/*[clinic end generated code: output=504460f5dc85acbd input=5306fa2b81a997e4]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 float_format_type f;
1740 float_format_type detected;
1741 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 if (strcmp(typestr, "double") == 0) {
1744 p = &double_format;
1745 detected = detected_double_format;
1746 }
1747 else if (strcmp(typestr, "float") == 0) {
1748 p = &float_format;
1749 detected = detected_float_format;
1750 }
1751 else {
1752 PyErr_SetString(PyExc_ValueError,
1753 "__setformat__() argument 1 must "
1754 "be 'double' or 'float'");
1755 return NULL;
1756 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001757
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001758 if (strcmp(fmt, "unknown") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 f = unknown_format;
1760 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001761 else if (strcmp(fmt, "IEEE, little-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 f = ieee_little_endian_format;
1763 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001764 else if (strcmp(fmt, "IEEE, big-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 f = ieee_big_endian_format;
1766 }
1767 else {
1768 PyErr_SetString(PyExc_ValueError,
1769 "__setformat__() argument 2 must be "
1770 "'unknown', 'IEEE, little-endian' or "
1771 "'IEEE, big-endian'");
1772 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 if (f != unknown_format && f != detected) {
1777 PyErr_Format(PyExc_ValueError,
1778 "can only set %s format to 'unknown' or the "
1779 "detected platform value", typestr);
1780 return NULL;
1781 }
1782
1783 *p = f;
1784 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001785}
1786
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001787static PyObject *
1788float_getreal(PyObject *v, void *closure)
1789{
1790 return float_float(v);
1791}
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001792
Guido van Rossumb43daf72007-08-01 18:08:08 +00001793static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001794float_getimag(PyObject *v, void *closure)
Guido van Rossumb43daf72007-08-01 18:08:08 +00001795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001797}
1798
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001799/*[clinic input]
1800float.__format__
1801
1802 format_spec: unicode
1803 /
1804
1805Formats the float according to format_spec.
1806[clinic start generated code]*/
1807
Eric Smith8c663262007-08-25 02:26:07 +00001808static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001809float___format___impl(PyObject *self, PyObject *format_spec)
1810/*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/
Eric Smith8c663262007-08-25 02:26:07 +00001811{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001812 _PyUnicodeWriter writer;
1813 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001814
Victor Stinner8f674cc2013-04-17 23:02:17 +02001815 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001816 ret = _PyFloat_FormatAdvancedWriter(
1817 &writer,
1818 self,
1819 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1820 if (ret == -1) {
1821 _PyUnicodeWriter_Dealloc(&writer);
1822 return NULL;
1823 }
1824 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001825}
1826
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001827static PyMethodDef float_methods[] = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001828 FLOAT_CONJUGATE_METHODDEF
1829 FLOAT___TRUNC___METHODDEF
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +03001830 FLOAT___FLOOR___METHODDEF
1831 FLOAT___CEIL___METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001832 FLOAT___ROUND___METHODDEF
1833 FLOAT_AS_INTEGER_RATIO_METHODDEF
1834 FLOAT_FROMHEX_METHODDEF
1835 FLOAT_HEX_METHODDEF
1836 FLOAT_IS_INTEGER_METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001837 FLOAT___GETNEWARGS___METHODDEF
1838 FLOAT___GETFORMAT___METHODDEF
1839 FLOAT___SET_FORMAT___METHODDEF
1840 FLOAT___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001842};
1843
Guido van Rossumb43daf72007-08-01 18:08:08 +00001844static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 {"real",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001846 float_getreal, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001847 "the real part of a complex number",
1848 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 {"imag",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001850 float_getimag, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001851 "the imaginary part of a complex number",
1852 NULL},
1853 {NULL} /* Sentinel */
1854};
1855
Tim Peters6d6c1a32001-08-02 04:15:00 +00001856
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001857static PyNumberMethods float_as_number = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001858 float_add, /* nb_add */
1859 float_sub, /* nb_subtract */
1860 float_mul, /* nb_multiply */
1861 float_rem, /* nb_remainder */
1862 float_divmod, /* nb_divmod */
1863 float_pow, /* nb_power */
1864 (unaryfunc)float_neg, /* nb_negative */
1865 float_float, /* nb_positive */
1866 (unaryfunc)float_abs, /* nb_absolute */
1867 (inquiry)float_bool, /* nb_bool */
1868 0, /* nb_invert */
1869 0, /* nb_lshift */
1870 0, /* nb_rshift */
1871 0, /* nb_and */
1872 0, /* nb_xor */
1873 0, /* nb_or */
1874 float___trunc___impl, /* nb_int */
1875 0, /* nb_reserved */
1876 float_float, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 0, /* nb_inplace_add */
1878 0, /* nb_inplace_subtract */
1879 0, /* nb_inplace_multiply */
1880 0, /* nb_inplace_remainder */
1881 0, /* nb_inplace_power */
1882 0, /* nb_inplace_lshift */
1883 0, /* nb_inplace_rshift */
1884 0, /* nb_inplace_and */
1885 0, /* nb_inplace_xor */
1886 0, /* nb_inplace_or */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001887 float_floor_div, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 float_div, /* nb_true_divide */
1889 0, /* nb_inplace_floor_divide */
1890 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001891};
1892
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001893PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1895 "float",
1896 sizeof(PyFloatObject),
1897 0,
1898 (destructor)float_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001899 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 0, /* tp_getattr */
1901 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001902 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 (reprfunc)float_repr, /* tp_repr */
1904 &float_as_number, /* tp_as_number */
1905 0, /* tp_as_sequence */
1906 0, /* tp_as_mapping */
1907 (hashfunc)float_hash, /* tp_hash */
1908 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001909 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 PyObject_GenericGetAttr, /* tp_getattro */
1911 0, /* tp_setattro */
1912 0, /* tp_as_buffer */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001913 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001914 float_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 0, /* tp_traverse */
1916 0, /* tp_clear */
1917 float_richcompare, /* tp_richcompare */
1918 0, /* tp_weaklistoffset */
1919 0, /* tp_iter */
1920 0, /* tp_iternext */
1921 float_methods, /* tp_methods */
1922 0, /* tp_members */
1923 float_getset, /* tp_getset */
1924 0, /* tp_base */
1925 0, /* tp_dict */
1926 0, /* tp_descr_get */
1927 0, /* tp_descr_set */
1928 0, /* tp_dictoffset */
1929 0, /* tp_init */
1930 0, /* tp_alloc */
1931 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001932};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001933
Victor Stinner1c8f0592013-07-22 22:24:54 +02001934int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001935_PyFloat_Init(void)
1936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 /* We attempt to determine if this machine is using IEEE
1938 floating point formats by peering at the bits of some
1939 carefully chosen values. If it looks like we are on an
1940 IEEE platform, the float packing/unpacking routines can
1941 just copy bits, if not they resort to arithmetic & shifts
1942 and masks. The shifts & masks approach works on all finite
1943 values, but what happens to infinities, NaNs and signed
1944 zeroes on packing is an accident, and attempting to unpack
1945 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 Note that if we're on some whacked-out platform which uses
1948 IEEE formats but isn't strictly little-endian or big-
1949 endian, we will fall back to the portable shifts & masks
1950 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001951
1952#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 {
1954 double x = 9006104071832581.0;
1955 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1956 detected_double_format = ieee_big_endian_format;
1957 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1958 detected_double_format = ieee_little_endian_format;
1959 else
1960 detected_double_format = unknown_format;
1961 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001962#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001964#endif
1965
1966#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 {
1968 float y = 16711938.0;
1969 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1970 detected_float_format = ieee_big_endian_format;
1971 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1972 detected_float_format = ieee_little_endian_format;
1973 else
1974 detected_float_format = unknown_format;
1975 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001976#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001978#endif
1979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 double_format = detected_double_format;
1981 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001984 if (FloatInfoType.tp_name == NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001985 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001986 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001987 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02001988 }
1989 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001990}
1991
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001992void
Victor Stinner2ba59372020-06-05 00:50:05 +02001993_PyFloat_ClearFreeList(PyThreadState *tstate)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001994{
Victor Stinner2ba59372020-06-05 00:50:05 +02001995 struct _Py_float_state *state = &tstate->interp->float_state;
Victor Stinnerbcb19832020-06-08 02:14:47 +02001996 PyFloatObject *f = state->free_list;
1997 while (f != NULL) {
1998 PyFloatObject *next = (PyFloatObject*) Py_TYPE(f);
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001999 PyObject_FREE(f);
Victor Stinnerbcb19832020-06-08 02:14:47 +02002000 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 }
Victor Stinner2ba59372020-06-05 00:50:05 +02002002 state->free_list = NULL;
2003 state->numfree = 0;
Christian Heimes15ebc882008-02-04 18:48:49 +00002004}
2005
2006void
Victor Stinner2ba59372020-06-05 00:50:05 +02002007_PyFloat_Fini(PyThreadState *tstate)
Christian Heimes15ebc882008-02-04 18:48:49 +00002008{
Victor Stinner2ba59372020-06-05 00:50:05 +02002009 _PyFloat_ClearFreeList(tstate);
Victor Stinnerbcb19832020-06-08 02:14:47 +02002010#ifdef Py_DEBUG
2011 struct _Py_float_state *state = &tstate->interp->float_state;
2012 state->numfree = -1;
2013#endif
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002014}
Tim Peters9905b942003-03-20 20:53:32 +00002015
David Malcolm49526f42012-06-22 14:55:41 -04002016/* Print summary info about the state of the optimized allocator */
2017void
2018_PyFloat_DebugMallocStats(FILE *out)
2019{
Victor Stinner2ba59372020-06-05 00:50:05 +02002020 PyInterpreterState *interp = _PyInterpreterState_GET();
2021 struct _Py_float_state *state = &interp->float_state;
David Malcolm49526f42012-06-22 14:55:41 -04002022 _PyDebugAllocatorStats(out,
2023 "free PyFloatObject",
Victor Stinner2ba59372020-06-05 00:50:05 +02002024 state->numfree, sizeof(PyFloatObject));
David Malcolm49526f42012-06-22 14:55:41 -04002025}
2026
2027
Tim Peters9905b942003-03-20 20:53:32 +00002028/*----------------------------------------------------------------------------
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002029 * _PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h.
2030 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
2031 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
2032 * We use:
2033 * bits = (unsigned short)f; Note the truncation
2034 * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
2035 * bits++;
2036 * }
Tim Peters9905b942003-03-20 20:53:32 +00002037 */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002038
2039int
2040_PyFloat_Pack2(double x, unsigned char *p, int le)
2041{
2042 unsigned char sign;
2043 int e;
2044 double f;
2045 unsigned short bits;
2046 int incr = 1;
2047
2048 if (x == 0.0) {
2049 sign = (copysign(1.0, x) == -1.0);
2050 e = 0;
2051 bits = 0;
2052 }
2053 else if (Py_IS_INFINITY(x)) {
2054 sign = (x < 0.0);
2055 e = 0x1f;
2056 bits = 0;
2057 }
2058 else if (Py_IS_NAN(x)) {
2059 /* There are 2046 distinct half-precision NaNs (1022 signaling and
2060 1024 quiet), but there are only two quiet NaNs that don't arise by
2061 quieting a signaling NaN; we get those by setting the topmost bit
2062 of the fraction field and clearing all other fraction bits. We
2063 choose the one with the appropriate sign. */
2064 sign = (copysign(1.0, x) == -1.0);
2065 e = 0x1f;
2066 bits = 512;
2067 }
2068 else {
2069 sign = (x < 0.0);
2070 if (sign) {
2071 x = -x;
2072 }
2073
2074 f = frexp(x, &e);
2075 if (f < 0.5 || f >= 1.0) {
2076 PyErr_SetString(PyExc_SystemError,
2077 "frexp() result out of range");
2078 return -1;
2079 }
2080
2081 /* Normalize f to be in the range [1.0, 2.0) */
2082 f *= 2.0;
2083 e--;
2084
2085 if (e >= 16) {
2086 goto Overflow;
2087 }
2088 else if (e < -25) {
2089 /* |x| < 2**-25. Underflow to zero. */
2090 f = 0.0;
2091 e = 0;
2092 }
2093 else if (e < -14) {
2094 /* |x| < 2**-14. Gradual underflow */
2095 f = ldexp(f, 14 + e);
2096 e = 0;
2097 }
2098 else /* if (!(e == 0 && f == 0.0)) */ {
2099 e += 15;
2100 f -= 1.0; /* Get rid of leading 1 */
2101 }
2102
2103 f *= 1024.0; /* 2**10 */
2104 /* Round to even */
2105 bits = (unsigned short)f; /* Note the truncation */
2106 assert(bits < 1024);
2107 assert(e < 31);
2108 if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2109 ++bits;
2110 if (bits == 1024) {
2111 /* The carry propagated out of a string of 10 1 bits. */
2112 bits = 0;
2113 ++e;
2114 if (e == 31)
2115 goto Overflow;
2116 }
2117 }
2118 }
2119
2120 bits |= (e << 10) | (sign << 15);
2121
2122 /* Write out result. */
2123 if (le) {
2124 p += 1;
2125 incr = -1;
2126 }
2127
2128 /* First byte */
2129 *p = (unsigned char)((bits >> 8) & 0xFF);
2130 p += incr;
2131
2132 /* Second byte */
2133 *p = (unsigned char)(bits & 0xFF);
2134
2135 return 0;
2136
2137 Overflow:
2138 PyErr_SetString(PyExc_OverflowError,
2139 "float too large to pack with e format");
2140 return -1;
2141}
2142
Tim Peters9905b942003-03-20 20:53:32 +00002143int
2144_PyFloat_Pack4(double x, unsigned char *p, int le)
2145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 if (float_format == unknown_format) {
2147 unsigned char sign;
2148 int e;
2149 double f;
2150 unsigned int fbits;
2151 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 if (le) {
2154 p += 3;
2155 incr = -1;
2156 }
Tim Peters9905b942003-03-20 20:53:32 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 if (x < 0) {
2159 sign = 1;
2160 x = -x;
2161 }
2162 else
2163 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 /* Normalize f to be in the range [1.0, 2.0) */
2168 if (0.5 <= f && f < 1.0) {
2169 f *= 2.0;
2170 e--;
2171 }
2172 else if (f == 0.0)
2173 e = 0;
2174 else {
2175 PyErr_SetString(PyExc_SystemError,
2176 "frexp() result out of range");
2177 return -1;
2178 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 if (e >= 128)
2181 goto Overflow;
2182 else if (e < -126) {
2183 /* Gradual underflow */
2184 f = ldexp(f, 126 + e);
2185 e = 0;
2186 }
2187 else if (!(e == 0 && f == 0.0)) {
2188 e += 127;
2189 f -= 1.0; /* Get rid of leading 1 */
2190 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 f *= 8388608.0; /* 2**23 */
2193 fbits = (unsigned int)(f + 0.5); /* Round */
2194 assert(fbits <= 8388608);
2195 if (fbits >> 23) {
2196 /* The carry propagated out of a string of 23 1 bits. */
2197 fbits = 0;
2198 ++e;
2199 if (e >= 255)
2200 goto Overflow;
2201 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 /* First byte */
2204 *p = (sign << 7) | (e >> 1);
2205 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 /* Second byte */
2208 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2209 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 /* Third byte */
2212 *p = (fbits >> 8) & 0xFF;
2213 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 /* Fourth byte */
2216 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 /* Done */
2219 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 }
2222 else {
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002223 float y = (float)x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002225
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002226 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002228
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002229 unsigned char s[sizeof(float)];
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002230 memcpy(s, &y, sizeof(float));
2231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 if ((float_format == ieee_little_endian_format && !le)
2233 || (float_format == ieee_big_endian_format && le)) {
2234 p += 3;
2235 incr = -1;
2236 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 for (i = 0; i < 4; i++) {
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002239 *p = s[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 p += incr;
2241 }
2242 return 0;
2243 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002244 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 PyErr_SetString(PyExc_OverflowError,
2246 "float too large to pack with f format");
2247 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002248}
2249
2250int
2251_PyFloat_Pack8(double x, unsigned char *p, int le)
2252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 if (double_format == unknown_format) {
2254 unsigned char sign;
2255 int e;
2256 double f;
2257 unsigned int fhi, flo;
2258 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 if (le) {
2261 p += 7;
2262 incr = -1;
2263 }
Tim Peters9905b942003-03-20 20:53:32 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 if (x < 0) {
2266 sign = 1;
2267 x = -x;
2268 }
2269 else
2270 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 /* Normalize f to be in the range [1.0, 2.0) */
2275 if (0.5 <= f && f < 1.0) {
2276 f *= 2.0;
2277 e--;
2278 }
2279 else if (f == 0.0)
2280 e = 0;
2281 else {
2282 PyErr_SetString(PyExc_SystemError,
2283 "frexp() result out of range");
2284 return -1;
2285 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 if (e >= 1024)
2288 goto Overflow;
2289 else if (e < -1022) {
2290 /* Gradual underflow */
2291 f = ldexp(f, 1022 + e);
2292 e = 0;
2293 }
2294 else if (!(e == 0 && f == 0.0)) {
2295 e += 1023;
2296 f -= 1.0; /* Get rid of leading 1 */
2297 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2300 f *= 268435456.0; /* 2**28 */
2301 fhi = (unsigned int)f; /* Truncate */
2302 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 f -= (double)fhi;
2305 f *= 16777216.0; /* 2**24 */
2306 flo = (unsigned int)(f + 0.5); /* Round */
2307 assert(flo <= 16777216);
2308 if (flo >> 24) {
2309 /* The carry propagated out of a string of 24 1 bits. */
2310 flo = 0;
2311 ++fhi;
2312 if (fhi >> 28) {
2313 /* And it also progagated out of the next 28 bits. */
2314 fhi = 0;
2315 ++e;
2316 if (e >= 2047)
2317 goto Overflow;
2318 }
2319 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 /* First byte */
2322 *p = (sign << 7) | (e >> 4);
2323 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 /* Second byte */
2326 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2327 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 /* Third byte */
2330 *p = (fhi >> 16) & 0xFF;
2331 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 /* Fourth byte */
2334 *p = (fhi >> 8) & 0xFF;
2335 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 /* Fifth byte */
2338 *p = fhi & 0xFF;
2339 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 /* Sixth byte */
2342 *p = (flo >> 16) & 0xFF;
2343 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 /* Seventh byte */
2346 *p = (flo >> 8) & 0xFF;
2347 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* Eighth byte */
2350 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002351 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 /* Done */
2354 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 Overflow:
2357 PyErr_SetString(PyExc_OverflowError,
2358 "float too large to pack with d format");
2359 return -1;
2360 }
2361 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002362 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 if ((double_format == ieee_little_endian_format && !le)
2366 || (double_format == ieee_big_endian_format && le)) {
2367 p += 7;
2368 incr = -1;
2369 }
2370
2371 for (i = 0; i < 8; i++) {
2372 *p = *s++;
2373 p += incr;
2374 }
2375 return 0;
2376 }
Tim Peters9905b942003-03-20 20:53:32 +00002377}
2378
2379double
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002380_PyFloat_Unpack2(const unsigned char *p, int le)
2381{
2382 unsigned char sign;
2383 int e;
2384 unsigned int f;
2385 double x;
2386 int incr = 1;
2387
2388 if (le) {
2389 p += 1;
2390 incr = -1;
2391 }
2392
2393 /* First byte */
2394 sign = (*p >> 7) & 1;
2395 e = (*p & 0x7C) >> 2;
2396 f = (*p & 0x03) << 8;
2397 p += incr;
2398
2399 /* Second byte */
2400 f |= *p;
2401
2402 if (e == 0x1f) {
2403#ifdef PY_NO_SHORT_FLOAT_REPR
2404 if (f == 0) {
2405 /* Infinity */
2406 return sign ? -Py_HUGE_VAL : Py_HUGE_VAL;
2407 }
2408 else {
2409 /* NaN */
2410#ifdef Py_NAN
2411 return sign ? -Py_NAN : Py_NAN;
2412#else
2413 PyErr_SetString(
2414 PyExc_ValueError,
2415 "can't unpack IEEE 754 NaN "
2416 "on platform that does not support NaNs");
2417 return -1;
2418#endif /* #ifdef Py_NAN */
2419 }
2420#else
2421 if (f == 0) {
2422 /* Infinity */
2423 return _Py_dg_infinity(sign);
2424 }
2425 else {
2426 /* NaN */
2427 return _Py_dg_stdnan(sign);
2428 }
2429#endif /* #ifdef PY_NO_SHORT_FLOAT_REPR */
2430 }
2431
2432 x = (double)f / 1024.0;
2433
2434 if (e == 0) {
2435 e = -14;
2436 }
2437 else {
2438 x += 1.0;
2439 e -= 15;
2440 }
2441 x = ldexp(x, e);
2442
2443 if (sign)
2444 x = -x;
2445
2446 return x;
2447}
2448
2449double
Tim Peters9905b942003-03-20 20:53:32 +00002450_PyFloat_Unpack4(const unsigned char *p, int le)
2451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 if (float_format == unknown_format) {
2453 unsigned char sign;
2454 int e;
2455 unsigned int f;
2456 double x;
2457 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 if (le) {
2460 p += 3;
2461 incr = -1;
2462 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 /* First byte */
2465 sign = (*p >> 7) & 1;
2466 e = (*p & 0x7F) << 1;
2467 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 /* Second byte */
2470 e |= (*p >> 7) & 1;
2471 f = (*p & 0x7F) << 16;
2472 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 if (e == 255) {
2475 PyErr_SetString(
2476 PyExc_ValueError,
2477 "can't unpack IEEE 754 special value "
2478 "on non-IEEE platform");
2479 return -1;
2480 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 /* Third byte */
2483 f |= *p << 8;
2484 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 /* Fourth byte */
2487 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 /* XXX This sadly ignores Inf/NaN issues */
2492 if (e == 0)
2493 e = -126;
2494 else {
2495 x += 1.0;
2496 e -= 127;
2497 }
2498 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 if (sign)
2501 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 return x;
2504 }
2505 else {
2506 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 if ((float_format == ieee_little_endian_format && !le)
2509 || (float_format == ieee_big_endian_format && le)) {
2510 char buf[4];
2511 char *d = &buf[3];
2512 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 for (i = 0; i < 4; i++) {
2515 *d-- = *p++;
2516 }
2517 memcpy(&x, buf, 4);
2518 }
2519 else {
2520 memcpy(&x, p, 4);
2521 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 return x;
2524 }
Tim Peters9905b942003-03-20 20:53:32 +00002525}
2526
2527double
2528_PyFloat_Unpack8(const unsigned char *p, int le)
2529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 if (double_format == unknown_format) {
2531 unsigned char sign;
2532 int e;
2533 unsigned int fhi, flo;
2534 double x;
2535 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 if (le) {
2538 p += 7;
2539 incr = -1;
2540 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 /* First byte */
2543 sign = (*p >> 7) & 1;
2544 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 /* Second byte */
2549 e |= (*p >> 4) & 0xF;
2550 fhi = (*p & 0xF) << 24;
2551 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 if (e == 2047) {
2554 PyErr_SetString(
2555 PyExc_ValueError,
2556 "can't unpack IEEE 754 special value "
2557 "on non-IEEE platform");
2558 return -1.0;
2559 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 /* Third byte */
2562 fhi |= *p << 16;
2563 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 /* Fourth byte */
2566 fhi |= *p << 8;
2567 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 /* Fifth byte */
2570 fhi |= *p;
2571 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 /* Sixth byte */
2574 flo = *p << 16;
2575 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 /* Seventh byte */
2578 flo |= *p << 8;
2579 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 /* Eighth byte */
2582 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2585 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 if (e == 0)
2588 e = -1022;
2589 else {
2590 x += 1.0;
2591 e -= 1023;
2592 }
2593 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 if (sign)
2596 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 return x;
2599 }
2600 else {
2601 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 if ((double_format == ieee_little_endian_format && !le)
2604 || (double_format == ieee_big_endian_format && le)) {
2605 char buf[8];
2606 char *d = &buf[7];
2607 int i;
2608
2609 for (i = 0; i < 8; i++) {
2610 *d-- = *p++;
2611 }
2612 memcpy(&x, buf, 8);
2613 }
2614 else {
2615 memcpy(&x, p, 8);
2616 }
2617
2618 return x;
2619 }
Tim Peters9905b942003-03-20 20:53:32 +00002620}