blob: 65625fe88cad868f37239e0b253d4d63bde7a783 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Float object implementation */
2
Guido van Rossum2a9096b1990-10-21 22:15:08 +00003/* XXX There should be overflow checks here, but it's hard to check
4 for any kind of float exception without losing portability. */
5
Guido van Rossumc0b618a1997-05-02 03:12:38 +00006#include "Python.h"
Victor Stinnere9e7d282020-02-12 22:54:42 +01007#include "pycore_dtoa.h"
Victor Stinner2ba59372020-06-05 00:50:05 +02008#include "pycore_interp.h" // _PyInterpreterState.float_state
9#include "pycore_pystate.h" // _PyInterpreterState_GET()
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Guido van Rossum3f5da241990-12-20 15:06:42 +000011#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000012#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013
Serhiy Storchakab5c51d32017-03-11 09:21:05 +020014/*[clinic input]
15class float "PyObject *" "&PyFloat_Type"
16[clinic start generated code]*/
17/*[clinic end generated code: output=da39a3ee5e6b4b0d input=dd0003f68f144284]*/
18
19#include "clinic/floatobject.c.h"
Guido van Rossum6923e131990-11-02 17:50:43 +000020
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000021#ifndef PyFloat_MAXFREELIST
Victor Stinner2ba59372020-06-05 00:50:05 +020022# define PyFloat_MAXFREELIST 100
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000023#endif
Guido van Rossum3fce8831999-03-12 19:43:17 +000024
Christian Heimes93852662007-12-01 12:22:32 +000025double
26PyFloat_GetMax(void)
27{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000029}
30
31double
32PyFloat_GetMin(void)
33{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000035}
36
Christian Heimesd32ed6f2008-01-14 18:49:24 +000037static PyTypeObject FloatInfoType;
38
39PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000040"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000041\n\
Raymond Hettinger71170742019-09-11 07:17:32 -070042A named tuple holding information about the float type. It contains low level\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000043information about the precision and internal representation. Please study\n\
44your system's :file:`float.h` for more information.");
45
46static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 {"max", "DBL_MAX -- maximum representable finite float"},
48 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
49 "is representable"},
50 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
51 "is representable"},
Stefano Taschini0301c9b2018-03-26 11:41:30 +020052 {"min", "DBL_MIN -- Minimum positive normalized float"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000053 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
54 "is a normalized float"},
55 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
56 "a normalized"},
Zackery Spytzfdc5a942020-05-24 04:03:52 -060057 {"dig", "DBL_DIG -- maximum number of decimal digits that "
58 "can be faithfully represented in a float"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
60 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
61 "representable float"},
62 {"radix", "FLT_RADIX -- radix of exponent"},
Zackery Spytzfdc5a942020-05-24 04:03:52 -060063 {"rounds", "FLT_ROUNDS -- rounding mode used for arithmetic "
64 "operations"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +000066};
67
68static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 "sys.float_info", /* name */
70 floatinfo__doc__, /* doc */
71 floatinfo_fields, /* fields */
72 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +000073};
74
Christian Heimes93852662007-12-01 12:22:32 +000075PyObject *
76PyFloat_GetInfo(void)
77{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 PyObject* floatinfo;
79 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +000080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 floatinfo = PyStructSequence_New(&FloatInfoType);
82 if (floatinfo == NULL) {
83 return NULL;
84 }
Christian Heimes93852662007-12-01 12:22:32 +000085
Christian Heimesd32ed6f2008-01-14 18:49:24 +000086#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +000088#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +000090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 SetDblFlag(DBL_MAX);
92 SetIntFlag(DBL_MAX_EXP);
93 SetIntFlag(DBL_MAX_10_EXP);
94 SetDblFlag(DBL_MIN);
95 SetIntFlag(DBL_MIN_EXP);
96 SetIntFlag(DBL_MIN_10_EXP);
97 SetIntFlag(DBL_DIG);
98 SetIntFlag(DBL_MANT_DIG);
99 SetDblFlag(DBL_EPSILON);
100 SetIntFlag(FLT_RADIX);
101 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000102#undef SetIntFlag
103#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104
105 if (PyErr_Occurred()) {
106 Py_CLEAR(floatinfo);
107 return NULL;
108 }
109 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000110}
111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114{
Victor Stinner2ba59372020-06-05 00:50:05 +0200115 PyInterpreterState *interp = _PyInterpreterState_GET();
116 struct _Py_float_state *state = &interp->float_state;
117 PyFloatObject *op = state->free_list;
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000118 if (op != NULL) {
Victor Stinnerbcb19832020-06-08 02:14:47 +0200119#ifdef Py_DEBUG
120 // PyFloat_FromDouble() must not be called after _PyFloat_Fini()
121 assert(state->numfree != -1);
122#endif
Victor Stinner2ba59372020-06-05 00:50:05 +0200123 state->free_list = (PyFloatObject *) Py_TYPE(op);
124 state->numfree--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 }
Victor Stinner2ba59372020-06-05 00:50:05 +0200126 else {
127 op = PyObject_Malloc(sizeof(PyFloatObject));
128 if (!op) {
129 return PyErr_NoMemory();
130 }
131 }
Victor Stinnerb509d522018-11-23 14:27:38 +0100132 (void)PyObject_INIT(op, &PyFloat_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 op->ob_fval = fval;
134 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000135}
136
Brett Cannona721aba2016-09-09 14:57:09 -0700137static PyObject *
138float_from_string_inner(const char *s, Py_ssize_t len, void *obj)
139{
140 double x;
141 const char *end;
142 const char *last = s + len;
143 /* strip space */
144 while (s < last && Py_ISSPACE(*s)) {
145 s++;
146 }
147
148 while (s < last - 1 && Py_ISSPACE(last[-1])) {
149 last--;
150 }
151
152 /* We don't care about overflow or underflow. If the platform
153 * supports them, infinities and signed zeroes (on underflow) are
154 * fine. */
155 x = PyOS_string_to_double(s, (char **)&end, NULL);
156 if (end != last) {
157 PyErr_Format(PyExc_ValueError,
158 "could not convert string to float: "
159 "%R", obj);
160 return NULL;
161 }
162 else if (x == -1.0 && PyErr_Occurred()) {
163 return NULL;
164 }
165 else {
166 return PyFloat_FromDouble(x);
167 }
168}
169
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000170PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000171PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000172{
Brett Cannona721aba2016-09-09 14:57:09 -0700173 const char *s;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000174 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 Py_ssize_t len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200176 Py_buffer view = {NULL, NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200180 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000182 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200183 assert(PyUnicode_IS_ASCII(s_buffer));
184 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200185 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200186 assert(s != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000188 else if (PyBytes_Check(v)) {
189 s = PyBytes_AS_STRING(v);
190 len = PyBytes_GET_SIZE(v);
191 }
192 else if (PyByteArray_Check(v)) {
193 s = PyByteArray_AS_STRING(v);
194 len = PyByteArray_GET_SIZE(v);
195 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200196 else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
197 s = (const char *)view.buf;
198 len = view.len;
Martin Pantereeb896c2015-11-07 02:32:21 +0000199 /* Copy to NUL-terminated buffer. */
200 s_buffer = PyBytes_FromStringAndSize(s, len);
201 if (s_buffer == NULL) {
202 PyBuffer_Release(&view);
203 return NULL;
204 }
205 s = PyBytes_AS_STRING(s_buffer);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200206 }
207 else {
Ezio Melottia5b95992013-11-07 19:18:34 +0200208 PyErr_Format(PyExc_TypeError,
209 "float() argument must be a string or a number, not '%.200s'",
210 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 return NULL;
212 }
Brett Cannona721aba2016-09-09 14:57:09 -0700213 result = _Py_string_to_number_with_underscores(s, len, "float", v, v,
214 float_from_string_inner);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200215 PyBuffer_Release(&view);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000216 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000218}
219
Guido van Rossum234f9421993-06-17 12:35:49 +0000220static void
Fred Drakefd99de62000-07-09 05:02:18 +0000221float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 if (PyFloat_CheckExact(op)) {
Victor Stinner2ba59372020-06-05 00:50:05 +0200224 PyInterpreterState *interp = _PyInterpreterState_GET();
225 struct _Py_float_state *state = &interp->float_state;
Victor Stinnerbcb19832020-06-08 02:14:47 +0200226#ifdef Py_DEBUG
227 // float_dealloc() must not be called after _PyFloat_Fini()
228 assert(state->numfree != -1);
229#endif
Victor Stinner2ba59372020-06-05 00:50:05 +0200230 if (state->numfree >= PyFloat_MAXFREELIST) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000231 PyObject_FREE(op);
232 return;
233 }
Victor Stinner2ba59372020-06-05 00:50:05 +0200234 state->numfree++;
235 Py_SET_TYPE(op, (PyTypeObject *)state->free_list);
236 state->free_list = op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 }
238 else
239 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000240}
241
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000242double
Fred Drakefd99de62000-07-09 05:02:18 +0000243PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 PyNumberMethods *nb;
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300246 PyObject *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (op == NULL) {
250 PyErr_BadArgument();
251 return -1;
252 }
Tim Petersd2364e82001-11-01 20:09:42 +0000253
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300254 if (PyFloat_Check(op)) {
255 return PyFloat_AS_DOUBLE(op);
256 }
257
258 nb = Py_TYPE(op)->tp_as_number;
259 if (nb == NULL || nb->nb_float == NULL) {
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300260 if (nb && nb->nb_index) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300261 PyObject *res = _PyNumber_Index(op);
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300262 if (!res) {
263 return -1;
264 }
265 double val = PyLong_AsDouble(res);
266 Py_DECREF(res);
267 return val;
268 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300269 PyErr_Format(PyExc_TypeError, "must be real number, not %.50s",
Victor Stinner58ac7002020-02-07 03:04:21 +0100270 Py_TYPE(op)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 return -1;
272 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000273
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300274 res = (*nb->nb_float) (op);
275 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 return -1;
277 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300278 if (!PyFloat_CheckExact(res)) {
279 if (!PyFloat_Check(res)) {
280 PyErr_Format(PyExc_TypeError,
281 "%.50s.__float__ returned non-float (type %.50s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100282 Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name);
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300283 Py_DECREF(res);
284 return -1;
285 }
286 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
287 "%.50s.__float__ returned non-float (type %.50s). "
288 "The ability to return an instance of a strict subclass of float "
289 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner58ac7002020-02-07 03:04:21 +0100290 Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name)) {
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300291 Py_DECREF(res);
292 return -1;
293 }
294 }
Tim Petersd2364e82001-11-01 20:09:42 +0000295
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300296 val = PyFloat_AS_DOUBLE(res);
297 Py_DECREF(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000299}
300
Neil Schemenauer32117e52001-01-04 01:44:34 +0000301/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000302 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000303 set to NULL, and the function invoking this macro returns NULL. If
Serhiy Storchaka95949422013-08-27 19:40:23 +0300304 obj is not of float or int type, Py_NotImplemented is incref'ed,
Tim Peters77d8a4f2001-12-11 20:31:34 +0000305 stored in obj, and returned from the function invoking this macro.
306*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307#define CONVERT_TO_DOUBLE(obj, dbl) \
308 if (PyFloat_Check(obj)) \
309 dbl = PyFloat_AS_DOUBLE(obj); \
310 else if (convert_to_double(&(obj), &(dbl)) < 0) \
311 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000312
Eric Smith0923d1d2009-04-16 20:16:10 +0000313/* Methods */
314
Neil Schemenauer32117e52001-01-04 01:44:34 +0000315static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000316convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000317{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200318 PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 if (PyLong_Check(obj)) {
321 *dbl = PyLong_AsDouble(obj);
322 if (*dbl == -1.0 && PyErr_Occurred()) {
323 *v = NULL;
324 return -1;
325 }
326 }
327 else {
328 Py_INCREF(Py_NotImplemented);
329 *v = Py_NotImplemented;
330 return -1;
331 }
332 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000333}
334
Eric Smith0923d1d2009-04-16 20:16:10 +0000335static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000336float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000337{
338 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200339 char *buf;
340
341 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
342 'r', 0,
343 Py_DTSF_ADD_DOT_0,
344 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000345 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000346 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200347 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000348 PyMem_Free(buf);
349 return result;
350}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000351
Tim Peters307fa782004-09-23 08:06:40 +0000352/* Comparison is pretty much a nightmare. When comparing float to float,
353 * we do it as straightforwardly (and long-windedly) as conceivable, so
354 * that, e.g., Python x == y delivers the same result as the platform
355 * C x == y when x and/or y is a NaN.
356 * When mixing float with an integer type, there's no good *uniform* approach.
357 * Converting the double to an integer obviously doesn't work, since we
358 * may lose info from fractional bits. Converting the integer to a double
Serhiy Storchaka95949422013-08-27 19:40:23 +0300359 * also has two failure modes: (1) an int may trigger overflow (too
Tim Peters307fa782004-09-23 08:06:40 +0000360 * 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 +0200361 * 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 +0000362 * 63 bits of precision, but a C double probably has only 53), and then
363 * we can falsely claim equality when low-order integer bits are lost by
364 * coercion to double. So this part is painful too.
365 */
366
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000367static PyObject*
368float_richcompare(PyObject *v, PyObject *w, int op)
369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 double i, j;
371 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 assert(PyFloat_Check(v));
374 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 /* Switch on the type of w. Set i and j to doubles to be compared,
377 * and op to the richcomp to use.
378 */
379 if (PyFloat_Check(w))
380 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 else if (!Py_IS_FINITE(i)) {
383 if (PyLong_Check(w))
384 /* If i is an infinity, its magnitude exceeds any
385 * finite integer, so it doesn't matter which int we
386 * compare i with. If i is a NaN, similarly.
387 */
388 j = 0.0;
389 else
390 goto Unimplemented;
391 }
Tim Peters307fa782004-09-23 08:06:40 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 else if (PyLong_Check(w)) {
394 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
395 int wsign = _PyLong_Sign(w);
396 size_t nbits;
397 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 if (vsign != wsign) {
400 /* Magnitudes are irrelevant -- the signs alone
401 * determine the outcome.
402 */
403 i = (double)vsign;
404 j = (double)wsign;
405 goto Compare;
406 }
407 /* The signs are the same. */
408 /* Convert w to a double if it fits. In particular, 0 fits. */
409 nbits = _PyLong_NumBits(w);
410 if (nbits == (size_t)-1 && PyErr_Occurred()) {
411 /* This long is so large that size_t isn't big enough
412 * to hold the # of bits. Replace with little doubles
413 * that give the same outcome -- w is so large that
414 * its magnitude must exceed the magnitude of any
415 * finite float.
416 */
417 PyErr_Clear();
418 i = (double)vsign;
419 assert(wsign != 0);
420 j = wsign * 2.0;
421 goto Compare;
422 }
423 if (nbits <= 48) {
424 j = PyLong_AsDouble(w);
425 /* It's impossible that <= 48 bits overflowed. */
426 assert(j != -1.0 || ! PyErr_Occurred());
427 goto Compare;
428 }
429 assert(wsign != 0); /* else nbits was 0 */
430 assert(vsign != 0); /* if vsign were 0, then since wsign is
431 * not 0, we would have taken the
432 * vsign != wsign branch at the start */
433 /* We want to work with non-negative numbers. */
434 if (vsign < 0) {
435 /* "Multiply both sides" by -1; this also swaps the
436 * comparator.
437 */
438 i = -i;
439 op = _Py_SwappedOp[op];
440 }
441 assert(i > 0.0);
442 (void) frexp(i, &exponent);
443 /* exponent is the # of bits in v before the radix point;
444 * we know that nbits (the # of bits in w) > 48 at this point
445 */
446 if (exponent < 0 || (size_t)exponent < nbits) {
447 i = 1.0;
448 j = 2.0;
449 goto Compare;
450 }
451 if ((size_t)exponent > nbits) {
452 i = 2.0;
453 j = 1.0;
454 goto Compare;
455 }
456 /* v and w have the same number of bits before the radix
Serhiy Storchaka95949422013-08-27 19:40:23 +0300457 * point. Construct two ints that have the same comparison
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 * outcome.
459 */
460 {
461 double fracpart;
462 double intpart;
463 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 PyObject *vv = NULL;
465 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 if (wsign < 0) {
468 ww = PyNumber_Negative(w);
469 if (ww == NULL)
470 goto Error;
471 }
472 else
473 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 fracpart = modf(i, &intpart);
476 vv = PyLong_FromDouble(intpart);
477 if (vv == NULL)
478 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 if (fracpart != 0.0) {
481 /* Shift left, and or a 1 bit into vv
482 * to represent the lost fraction.
483 */
484 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000485
Serhiy Storchakaa5119e72019-05-19 14:14:38 +0300486 temp = _PyLong_Lshift(ww, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 if (temp == NULL)
488 goto Error;
489 Py_DECREF(ww);
490 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000491
Serhiy Storchakaa5119e72019-05-19 14:14:38 +0300492 temp = _PyLong_Lshift(vv, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (temp == NULL)
494 goto Error;
495 Py_DECREF(vv);
496 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000497
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300498 temp = PyNumber_Or(vv, _PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 if (temp == NULL)
500 goto Error;
501 Py_DECREF(vv);
502 vv = temp;
503 }
Tim Peters307fa782004-09-23 08:06:40 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 r = PyObject_RichCompareBool(vv, ww, op);
506 if (r < 0)
507 goto Error;
508 result = PyBool_FromLong(r);
509 Error:
510 Py_XDECREF(vv);
511 Py_XDECREF(ww);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 return result;
513 }
514 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000515
Serhiy Storchaka95949422013-08-27 19:40:23 +0300516 else /* w isn't float or int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000518
519 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 switch (op) {
521 case Py_EQ:
522 r = i == j;
523 break;
524 case Py_NE:
525 r = i != j;
526 break;
527 case Py_LE:
528 r = i <= j;
529 break;
530 case Py_GE:
531 r = i >= j;
532 break;
533 case Py_LT:
534 r = i < j;
535 break;
536 case Py_GT:
537 r = i > j;
538 break;
539 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000541
542 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500543 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000544}
545
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000546static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000547float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000550}
551
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000552static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000553float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 double a,b;
556 CONVERT_TO_DOUBLE(v, a);
557 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 a = a + b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000560}
561
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000562static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000563float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 double a,b;
566 CONVERT_TO_DOUBLE(v, a);
567 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 a = a - b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000570}
571
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000572static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000573float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 double a,b;
576 CONVERT_TO_DOUBLE(v, a);
577 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 a = a * b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000580}
581
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000582static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000583float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 double a,b;
586 CONVERT_TO_DOUBLE(v, a);
587 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 if (b == 0.0) {
589 PyErr_SetString(PyExc_ZeroDivisionError,
590 "float division by zero");
591 return NULL;
592 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 a = a / b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000595}
596
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000597static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000598float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 double vx, wx;
601 double mod;
602 CONVERT_TO_DOUBLE(v, vx);
603 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 if (wx == 0.0) {
605 PyErr_SetString(PyExc_ZeroDivisionError,
606 "float modulo");
607 return NULL;
608 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000610 if (mod) {
611 /* ensure the remainder has the same sign as the denominator */
612 if ((wx < 0) != (mod < 0)) {
613 mod += wx;
614 }
615 }
616 else {
617 /* the remainder is zero, and in the presence of signed zeroes
618 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000619 it has the same sign as the denominator. */
620 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000623}
624
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900625static void
626_float_div_mod(double vx, double wx, double *floordiv, double *mod)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000627{
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900628 double div;
629 *mod = fmod(vx, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 /* fmod is typically exact, so vx-mod is *mathematically* an
631 exact multiple of wx. But this is fp arithmetic, and fp
632 vx - mod is an approximation; the result is that div may
633 not be an exact integral value after the division, although
634 it will always be very close to one.
635 */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900636 div = (vx - *mod) / wx;
637 if (*mod) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 /* ensure the remainder has the same sign as the denominator */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900639 if ((wx < 0) != (*mod < 0)) {
640 *mod += wx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 div -= 1.0;
642 }
643 }
644 else {
645 /* the remainder is zero, and in the presence of signed zeroes
646 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000647 it has the same sign as the denominator. */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900648 *mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 }
650 /* snap quotient to nearest integral value */
651 if (div) {
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900652 *floordiv = floor(div);
653 if (div - *floordiv > 0.5) {
654 *floordiv += 1.0;
Mark Dickinsonbe8147b2020-02-02 11:37:02 +0000655 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 }
657 else {
658 /* div is zero - get the same sign as the true quotient */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900659 *floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 }
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900661}
662
663static PyObject *
664float_divmod(PyObject *v, PyObject *w)
665{
Mark Dickinsonbe8147b2020-02-02 11:37:02 +0000666 double vx, wx;
667 double mod, floordiv;
668 CONVERT_TO_DOUBLE(v, vx);
669 CONVERT_TO_DOUBLE(w, wx);
670 if (wx == 0.0) {
671 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
672 return NULL;
673 }
674 _float_div_mod(vx, wx, &floordiv, &mod);
675 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000676}
677
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000678static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000679float_floor_div(PyObject *v, PyObject *w)
680{
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900681 double vx, wx;
682 double mod, floordiv;
683 CONVERT_TO_DOUBLE(v, vx);
684 CONVERT_TO_DOUBLE(w, wx);
685 if (wx == 0.0) {
686 PyErr_SetString(PyExc_ZeroDivisionError, "float floor division by zero");
687 return NULL;
688 }
689 _float_div_mod(vx, wx, &floordiv, &mod);
690 return PyFloat_FromDouble(floordiv);
Tim Peters63a35712001-12-11 19:57:24 +0000691}
692
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000693/* determine whether x is an odd integer or not; assumes that
694 x is not an infinity or nan. */
695#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
696
Tim Peters63a35712001-12-11 19:57:24 +0000697static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000698float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 double iv, iw, ix;
701 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 if ((PyObject *)z != Py_None) {
704 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
705 "allowed unless all arguments are integers");
706 return NULL;
707 }
Tim Peters32f453e2001-09-03 08:35:41 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 CONVERT_TO_DOUBLE(v, iv);
710 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 /* Sort out special cases here instead of relying on pow() */
713 if (iw == 0) { /* v**0 is 1, even 0**0 */
714 return PyFloat_FromDouble(1.0);
715 }
716 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
717 return PyFloat_FromDouble(iv);
718 }
719 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
720 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
721 }
722 if (Py_IS_INFINITY(iw)) {
723 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
724 * abs(v) > 1 (including case where v infinite)
725 *
726 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
727 * abs(v) > 1 (including case where v infinite)
728 */
729 iv = fabs(iv);
730 if (iv == 1.0)
731 return PyFloat_FromDouble(1.0);
732 else if ((iw > 0.0) == (iv > 1.0))
733 return PyFloat_FromDouble(fabs(iw)); /* return inf */
734 else
735 return PyFloat_FromDouble(0.0);
736 }
737 if (Py_IS_INFINITY(iv)) {
738 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
739 * both cases, we need to add the appropriate sign if w is
740 * an odd integer.
741 */
742 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
743 if (iw > 0.0)
744 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
745 else
746 return PyFloat_FromDouble(iw_is_odd ?
747 copysign(0.0, iv) : 0.0);
748 }
749 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
750 (already dealt with above), and an error
751 if w is negative. */
752 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
753 if (iw < 0.0) {
754 PyErr_SetString(PyExc_ZeroDivisionError,
755 "0.0 cannot be raised to a "
756 "negative power");
757 return NULL;
758 }
759 /* use correct sign if iw is odd */
760 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
761 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 if (iv < 0.0) {
764 /* Whether this is an error is a mess, and bumps into libm
765 * bugs so we have to figure it out ourselves.
766 */
767 if (iw != floor(iw)) {
768 /* Negative numbers raised to fractional powers
769 * become complex.
770 */
771 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
772 }
773 /* iw is an exact integer, albeit perhaps a very large
774 * one. Replace iv by its absolute value and remember
775 * to negate the pow result if iw is odd.
776 */
777 iv = -iv;
778 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
779 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
782 /* (-1) ** large_integer also ends up here. Here's an
783 * extract from the comments for the previous
784 * implementation explaining why this special case is
785 * necessary:
786 *
787 * -1 raised to an exact integer should never be exceptional.
788 * Alas, some libms (chiefly glibc as of early 2003) return
789 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
790 * happen to be representable in a *C* integer. That's a
791 * bug.
792 */
793 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
794 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 /* Now iv and iw are finite, iw is nonzero, and iv is
797 * positive and not equal to 1.0. We finally allow
798 * the platform pow to step in and do the rest.
799 */
800 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 ix = pow(iv, iw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 Py_ADJUST_ERANGE1(ix);
803 if (negate_result)
804 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 if (errno != 0) {
807 /* We don't expect any errno value other than ERANGE, but
808 * the range of libm bugs appears unbounded.
809 */
810 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
811 PyExc_ValueError);
812 return NULL;
813 }
814 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000815}
816
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000817#undef DOUBLE_IS_ODD_INTEGER
818
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000819static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000820float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000823}
824
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000825static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000826float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000829}
830
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000831static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000832float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000835}
836
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200837/*[clinic input]
838float.is_integer
839
840Return True if the float is an integer.
841[clinic start generated code]*/
842
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000843static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200844float_is_integer_impl(PyObject *self)
845/*[clinic end generated code: output=7112acf95a4d31ea input=311810d3f777e10d]*/
Christian Heimes53876d92008-04-19 00:31:39 +0000846{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200847 double x = PyFloat_AsDouble(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 PyObject *o;
849
850 if (x == -1.0 && PyErr_Occurred())
851 return NULL;
852 if (!Py_IS_FINITE(x))
853 Py_RETURN_FALSE;
854 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 o = (floor(x) == x) ? Py_True : Py_False;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 if (errno != 0) {
857 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
858 PyExc_ValueError);
859 return NULL;
860 }
861 Py_INCREF(o);
862 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000863}
864
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200865/*[clinic input]
866float.__trunc__
867
868Return the Integral closest to x between 0 and x.
869[clinic start generated code]*/
870
Christian Heimes53876d92008-04-19 00:31:39 +0000871static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200872float___trunc___impl(PyObject *self)
873/*[clinic end generated code: output=dd3e289dd4c6b538 input=591b9ba0d650fdff]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000874{
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500875 return PyLong_FromDouble(PyFloat_AS_DOUBLE(self));
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000876}
877
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +0300878/*[clinic input]
879float.__floor__
880
881Return the floor as an Integral.
882[clinic start generated code]*/
883
884static PyObject *
885float___floor___impl(PyObject *self)
886/*[clinic end generated code: output=e0551dbaea8c01d1 input=77bb13eb12e268df]*/
887{
888 double x = PyFloat_AS_DOUBLE(self);
889 return PyLong_FromDouble(floor(x));
890}
891
892/*[clinic input]
893float.__ceil__
894
895Return the ceiling as an Integral.
896[clinic start generated code]*/
897
898static PyObject *
899float___ceil___impl(PyObject *self)
900/*[clinic end generated code: output=a2fd8858f73736f9 input=79e41ae94aa0a516]*/
901{
902 double x = PyFloat_AS_DOUBLE(self);
903 return PyLong_FromDouble(ceil(x));
904}
905
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000906/* double_round: rounds a finite double to the closest multiple of
907 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
908 ndigits <= 323). Returns a Python float, or sets a Python error and
909 returns NULL on failure (OverflowError and memory errors are possible). */
910
911#ifndef PY_NO_SHORT_FLOAT_REPR
912/* version of double_round that uses the correctly-rounded string<->double
913 conversions from Python/dtoa.c */
914
915static PyObject *
916double_round(double x, int ndigits) {
917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 double rounded;
919 Py_ssize_t buflen, mybuflen=100;
920 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
921 int decpt, sign;
922 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000923 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000926 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000928 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 if (buf == NULL) {
930 PyErr_NoMemory();
931 return NULL;
932 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
935 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
936 buflen = buf_end - buf;
937 if (buflen + 8 > mybuflen) {
938 mybuflen = buflen+8;
939 mybuf = (char *)PyMem_Malloc(mybuflen);
940 if (mybuf == NULL) {
941 PyErr_NoMemory();
942 goto exit;
943 }
944 }
945 /* copy buf to mybuf, adding exponent, sign and leading 0 */
946 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
947 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 /* and convert the resulting string back to a double */
950 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000951 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000953 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (errno == ERANGE && fabs(rounded) >= 1.)
955 PyErr_SetString(PyExc_OverflowError,
956 "rounded value too large to represent");
957 else
958 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* done computing value; now clean up */
961 if (mybuf != shortbuf)
962 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000963 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 _Py_dg_freedtoa(buf);
965 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000966}
967
968#else /* PY_NO_SHORT_FLOAT_REPR */
969
970/* fallback version, to be used when correctly rounded binary<->decimal
971 conversions aren't available */
972
973static PyObject *
974double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 double pow1, pow2, y, z;
976 if (ndigits >= 0) {
977 if (ndigits > 22) {
978 /* pow1 and pow2 are each safe from overflow, but
979 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
980 pow1 = pow(10.0, (double)(ndigits-22));
981 pow2 = 1e22;
982 }
983 else {
984 pow1 = pow(10.0, (double)ndigits);
985 pow2 = 1.0;
986 }
987 y = (x*pow1)*pow2;
988 /* if y overflows, then rounded value is exactly x */
989 if (!Py_IS_FINITE(y))
990 return PyFloat_FromDouble(x);
991 }
992 else {
993 pow1 = pow(10.0, (double)-ndigits);
994 pow2 = 1.0; /* unused; silences a gcc compiler warning */
995 y = x / pow1;
996 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 z = round(y);
999 if (fabs(y-z) == 0.5)
1000 /* halfway between two integers; use round-half-even */
1001 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 if (ndigits >= 0)
1004 z = (z / pow2) / pow1;
1005 else
1006 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 /* if computation resulted in overflow, raise OverflowError */
1009 if (!Py_IS_FINITE(z)) {
1010 PyErr_SetString(PyExc_OverflowError,
1011 "overflow occurred during round");
1012 return NULL;
1013 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001016}
1017
1018#endif /* PY_NO_SHORT_FLOAT_REPR */
1019
1020/* round a Python float v to the closest multiple of 10**-ndigits */
1021
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001022/*[clinic input]
1023float.__round__
1024
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001025 ndigits as o_ndigits: object = None
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001026 /
1027
1028Return the Integral closest to x, rounding half toward even.
1029
1030When an argument is passed, work like built-in round(x, ndigits).
1031[clinic start generated code]*/
1032
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001033static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001034float___round___impl(PyObject *self, PyObject *o_ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001035/*[clinic end generated code: output=374c36aaa0f13980 input=fc0fe25924fbc9ed]*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 double x, rounded;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001039
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001040 x = PyFloat_AsDouble(self);
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001041 if (o_ndigits == Py_None) {
Steve Dowercb39d1f2015-04-15 16:10:59 -04001042 /* single-argument round or with None ndigits:
1043 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 rounded = round(x);
1045 if (fabs(x-rounded) == 0.5)
1046 /* halfway case: round to even */
1047 rounded = 2.0*round(x/2.0);
1048 return PyLong_FromDouble(rounded);
1049 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 /* interpret second argument as a Py_ssize_t; clips on overflow */
1052 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1053 if (ndigits == -1 && PyErr_Occurred())
1054 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 /* nans and infinities round to themselves */
1057 if (!Py_IS_FINITE(x))
1058 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1061 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1062 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001063#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1064#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 if (ndigits > NDIGITS_MAX)
1066 /* return x */
1067 return PyFloat_FromDouble(x);
1068 else if (ndigits < NDIGITS_MIN)
1069 /* return 0.0, but with sign of x */
1070 return PyFloat_FromDouble(0.0*x);
1071 else
1072 /* finite x, and ndigits is not unreasonably large */
1073 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001074#undef NDIGITS_MAX
1075#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001076}
1077
1078static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001079float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 if (PyFloat_CheckExact(v))
1082 Py_INCREF(v);
1083 else
1084 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1085 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001086}
1087
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001088/*[clinic input]
1089float.conjugate
1090
1091Return self, the complex conjugate of any float.
1092[clinic start generated code]*/
1093
1094static PyObject *
1095float_conjugate_impl(PyObject *self)
1096/*[clinic end generated code: output=8ca292c2479194af input=82ba6f37a9ff91dd]*/
1097{
1098 return float_float(self);
1099}
1100
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001101/* turn ASCII hex characters into integer values and vice versa */
1102
1103static char
1104char_from_hex(int x)
1105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001107 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001108}
1109
1110static int
1111hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 int x;
1113 switch(c) {
1114 case '0':
1115 x = 0;
1116 break;
1117 case '1':
1118 x = 1;
1119 break;
1120 case '2':
1121 x = 2;
1122 break;
1123 case '3':
1124 x = 3;
1125 break;
1126 case '4':
1127 x = 4;
1128 break;
1129 case '5':
1130 x = 5;
1131 break;
1132 case '6':
1133 x = 6;
1134 break;
1135 case '7':
1136 x = 7;
1137 break;
1138 case '8':
1139 x = 8;
1140 break;
1141 case '9':
1142 x = 9;
1143 break;
1144 case 'a':
1145 case 'A':
1146 x = 10;
1147 break;
1148 case 'b':
1149 case 'B':
1150 x = 11;
1151 break;
1152 case 'c':
1153 case 'C':
1154 x = 12;
1155 break;
1156 case 'd':
1157 case 'D':
1158 x = 13;
1159 break;
1160 case 'e':
1161 case 'E':
1162 x = 14;
1163 break;
1164 case 'f':
1165 case 'F':
1166 x = 15;
1167 break;
1168 default:
1169 x = -1;
1170 break;
1171 }
1172 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001173}
1174
1175/* convert a float to a hexadecimal string */
1176
1177/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1178 of the form 4k+1. */
1179#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1180
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001181/*[clinic input]
1182float.hex
1183
1184Return a hexadecimal representation of a floating-point number.
1185
1186>>> (-0.1).hex()
1187'-0x1.999999999999ap-4'
1188>>> 3.14159.hex()
1189'0x1.921f9f01b866ep+1'
1190[clinic start generated code]*/
1191
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001192static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001193float_hex_impl(PyObject *self)
1194/*[clinic end generated code: output=0ebc9836e4d302d4 input=bec1271a33d47e67]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 double x, m;
1197 int e, shift, i, si, esign;
1198 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1199 trailing NUL byte. */
1200 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001201
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001202 CONVERT_TO_DOUBLE(self, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001205 return float_repr((PyFloatObject *)self);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001208 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 return PyUnicode_FromString("-0x0.0p+0");
1210 else
1211 return PyUnicode_FromString("0x0.0p+0");
1212 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001215 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 m = ldexp(m, shift);
1217 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 si = 0;
1220 s[si] = char_from_hex((int)m);
1221 si++;
1222 m -= (int)m;
1223 s[si] = '.';
1224 si++;
1225 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1226 m *= 16.0;
1227 s[si] = char_from_hex((int)m);
1228 si++;
1229 m -= (int)m;
1230 }
1231 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (e < 0) {
1234 esign = (int)'-';
1235 e = -e;
1236 }
1237 else
1238 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 if (x < 0.0)
1241 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1242 else
1243 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001244}
1245
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001246/* Convert a hexadecimal string to a float. */
1247
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001248/*[clinic input]
1249@classmethod
1250float.fromhex
1251
1252 string: object
1253 /
1254
1255Create a floating-point number from a hexadecimal string.
1256
1257>>> float.fromhex('0x1.ffffp10')
12582047.984375
1259>>> float.fromhex('-0x1p-1074')
1260-5e-324
1261[clinic start generated code]*/
1262
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001263static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001264float_fromhex(PyTypeObject *type, PyObject *string)
1265/*[clinic end generated code: output=46c0274d22b78e82 input=0407bebd354bca89]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001266{
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001267 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 double x;
1269 long exp, top_exp, lsb, key_digit;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001270 const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 int half_eps, digit, round_up, negate=0;
1272 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 /*
1275 * For the sake of simplicity and correctness, we impose an artificial
1276 * limit on ndigits, the total number of hex digits in the coefficient
1277 * The limit is chosen to ensure that, writing exp for the exponent,
1278 *
1279 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1280 * guaranteed to overflow (provided it's nonzero)
1281 *
1282 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1283 * guaranteed to underflow to 0.
1284 *
1285 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1286 * overflow in the calculation of exp and top_exp below.
1287 *
1288 * More specifically, ndigits is assumed to satisfy the following
1289 * inequalities:
1290 *
1291 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1292 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1293 *
1294 * If either of these inequalities is not satisfied, a ValueError is
1295 * raised. Otherwise, write x for the value of the hex string, and
1296 * assume x is nonzero. Then
1297 *
1298 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1299 *
1300 * Now if exp > LONG_MAX/2 then:
1301 *
1302 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1303 * = DBL_MAX_EXP
1304 *
1305 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1306 * double, so overflows. If exp < LONG_MIN/2, then
1307 *
1308 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1309 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1310 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1311 *
1312 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1313 * when converted to a C double.
1314 *
1315 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1316 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1317 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001318
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001319 s = PyUnicode_AsUTF8AndSize(string, &length);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 if (s == NULL)
1321 return NULL;
1322 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 /********************
1325 * Parse the string *
1326 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 /* leading whitespace */
1329 while (Py_ISSPACE(*s))
1330 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 /* infinities and nans */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001333 x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 if (coeff_end != s) {
1335 s = coeff_end;
1336 goto finished;
1337 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 /* optional sign */
1340 if (*s == '-') {
1341 s++;
1342 negate = 1;
1343 }
1344 else if (*s == '+')
1345 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 /* [0x] */
1348 s_store = s;
1349 if (*s == '0') {
1350 s++;
1351 if (*s == 'x' || *s == 'X')
1352 s++;
1353 else
1354 s = s_store;
1355 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 /* coefficient: <integer> [. <fraction>] */
1358 coeff_start = s;
1359 while (hex_from_char(*s) >= 0)
1360 s++;
1361 s_store = s;
1362 if (*s == '.') {
1363 s++;
1364 while (hex_from_char(*s) >= 0)
1365 s++;
1366 coeff_end = s-1;
1367 }
1368 else
1369 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 /* ndigits = total # of hex digits; fdigits = # after point */
1372 ndigits = coeff_end - coeff_start;
1373 fdigits = coeff_end - s_store;
1374 if (ndigits == 0)
1375 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001376 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1377 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 /* [p <exponent>] */
1381 if (*s == 'p' || *s == 'P') {
1382 s++;
1383 exp_start = s;
1384 if (*s == '-' || *s == '+')
1385 s++;
1386 if (!('0' <= *s && *s <= '9'))
1387 goto parse_error;
1388 s++;
1389 while ('0' <= *s && *s <= '9')
1390 s++;
1391 exp = strtol(exp_start, NULL, 10);
1392 }
1393 else
1394 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001395
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001396/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1398 coeff_end-(j) : \
1399 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 /*******************************************
1402 * Compute rounded value of the hex string *
1403 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 /* Discard leading zeros, and catch extreme overflow and underflow */
1406 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1407 ndigits--;
1408 if (ndigits == 0 || exp < LONG_MIN/2) {
1409 x = 0.0;
1410 goto finished;
1411 }
1412 if (exp > LONG_MAX/2)
1413 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 /* Adjust exponent for fractional part. */
1416 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1419 top_exp = exp + 4*((long)ndigits - 1);
1420 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1421 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 /* catch almost all nonextreme cases of overflow and underflow here */
1424 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1425 x = 0.0;
1426 goto finished;
1427 }
1428 if (top_exp > DBL_MAX_EXP)
1429 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 /* lsb = exponent of least significant bit of the *rounded* value.
1432 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001433 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 x = 0.0;
1436 if (exp >= lsb) {
1437 /* no rounding required */
1438 for (i = ndigits-1; i >= 0; i--)
1439 x = 16.0*x + HEX_DIGIT(i);
1440 x = ldexp(x, (int)(exp));
1441 goto finished;
1442 }
1443 /* rounding required. key_digit is the index of the hex digit
1444 containing the first bit to be rounded away. */
1445 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1446 key_digit = (lsb - exp - 1) / 4;
1447 for (i = ndigits-1; i > key_digit; i--)
1448 x = 16.0*x + HEX_DIGIT(i);
1449 digit = HEX_DIGIT(key_digit);
1450 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1453 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1454 if ((digit & half_eps) != 0) {
1455 round_up = 0;
1456 if ((digit & (3*half_eps-1)) != 0 ||
1457 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1458 round_up = 1;
1459 else
1460 for (i = key_digit-1; i >= 0; i--)
1461 if (HEX_DIGIT(i) != 0) {
1462 round_up = 1;
1463 break;
1464 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001465 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 x += 2*half_eps;
1467 if (top_exp == DBL_MAX_EXP &&
1468 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1469 /* overflow corner case: pre-rounded value <
1470 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1471 goto overflow_error;
1472 }
1473 }
1474 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001475
1476 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 /* optional trailing whitespace leading to the end of the string */
1478 while (Py_ISSPACE(*s))
1479 s++;
1480 if (s != s_end)
1481 goto parse_error;
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001482 result = PyFloat_FromDouble(negate ? -x : x);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001483 if (type != &PyFloat_Type && result != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001484 Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001485 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001487
1488 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 PyErr_SetString(PyExc_OverflowError,
1490 "hexadecimal value too large to represent as a float");
1491 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001492
1493 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 PyErr_SetString(PyExc_ValueError,
1495 "invalid hexadecimal floating-point string");
1496 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001497
1498 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 PyErr_SetString(PyExc_ValueError,
1500 "hexadecimal string too long to convert");
1501 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001502}
1503
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001504/*[clinic input]
1505float.as_integer_ratio
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001506
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001507Return integer ratio.
1508
1509Return a pair of integers, whose ratio is exactly equal to the original float
1510and with a positive denominator.
1511
1512Raise OverflowError on infinities and a ValueError on NaNs.
1513
1514>>> (10.0).as_integer_ratio()
1515(10, 1)
1516>>> (0.0).as_integer_ratio()
1517(0, 1)
1518>>> (-.25).as_integer_ratio()
1519(-1, 4)
1520[clinic start generated code]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001521
Christian Heimes26855632008-01-27 23:50:43 +00001522static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001523float_as_integer_ratio_impl(PyObject *self)
1524/*[clinic end generated code: output=65f25f0d8d30a712 input=e21d08b4630c2e44]*/
Christian Heimes26855632008-01-27 23:50:43 +00001525{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001526 double self_double;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 double float_part;
1528 int exponent;
1529 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 PyObject *py_exponent = NULL;
1532 PyObject *numerator = NULL;
1533 PyObject *denominator = NULL;
1534 PyObject *result_pair = NULL;
1535 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001536
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001537 CONVERT_TO_DOUBLE(self, self_double);
Christian Heimes26855632008-01-27 23:50:43 +00001538
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001539 if (Py_IS_INFINITY(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001540 PyErr_SetString(PyExc_OverflowError,
1541 "cannot convert Infinity to integer ratio");
1542 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001544 if (Py_IS_NAN(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001545 PyErr_SetString(PyExc_ValueError,
1546 "cannot convert NaN to integer ratio");
1547 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 }
Christian Heimes26855632008-01-27 23:50:43 +00001549
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001550 float_part = frexp(self_double, &exponent); /* self_double == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1553 float_part *= 2.0;
1554 exponent--;
1555 }
1556 /* self == float_part * 2**exponent exactly and float_part is integral.
1557 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1558 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 numerator = PyLong_FromDouble(float_part);
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001561 if (numerator == NULL)
1562 goto error;
1563 denominator = PyLong_FromLong(1);
1564 if (denominator == NULL)
1565 goto error;
1566 py_exponent = PyLong_FromLong(Py_ABS(exponent));
1567 if (py_exponent == NULL)
1568 goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 /* fold in 2**exponent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 if (exponent > 0) {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001572 Py_SETREF(numerator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001573 long_methods->nb_lshift(numerator, py_exponent));
1574 if (numerator == NULL)
1575 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 }
1577 else {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001578 Py_SETREF(denominator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001579 long_methods->nb_lshift(denominator, py_exponent));
1580 if (denominator == NULL)
1581 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 }
1583
1584 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001585
Christian Heimes26855632008-01-27 23:50:43 +00001586error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 Py_XDECREF(py_exponent);
1588 Py_XDECREF(denominator);
1589 Py_XDECREF(numerator);
1590 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001591}
1592
Jeremy Hylton938ace62002-07-17 16:30:39 +00001593static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001594float_subtype_new(PyTypeObject *type, PyObject *x);
1595
1596/*[clinic input]
1597@classmethod
1598float.__new__ as float_new
Serhiy Storchakaba85d692017-03-30 09:09:41 +03001599 x: object(c_default="_PyLong_Zero") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001600 /
1601
1602Convert a string or number to a floating point number, if possible.
1603[clinic start generated code]*/
Guido van Rossumbef14172001-08-29 15:47:46 +00001604
Tim Peters6d6c1a32001-08-02 04:15:00 +00001605static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001606float_new_impl(PyTypeObject *type, PyObject *x)
Serhiy Storchakabae68812017-04-05 12:00:42 +03001607/*[clinic end generated code: output=ccf1e8dc460ba6ba input=540ee77c204ff87a]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00001608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 if (type != &PyFloat_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001610 return float_subtype_new(type, x); /* Wimp out */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 /* If it's a string, but not a string subclass, use
1612 PyFloat_FromString. */
1613 if (PyUnicode_CheckExact(x))
1614 return PyFloat_FromString(x);
1615 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001616}
1617
Guido van Rossumbef14172001-08-29 15:47:46 +00001618/* Wimpy, slow approach to tp_new calls for subtypes of float:
1619 first create a regular float from whatever arguments we got,
1620 then allocate a subtype instance and initialize its ob_fval
1621 from the regular float. The regular float is then thrown away.
1622*/
1623static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001624float_subtype_new(PyTypeObject *type, PyObject *x)
Guido van Rossumbef14172001-08-29 15:47:46 +00001625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 assert(PyType_IsSubtype(type, &PyFloat_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001629 tmp = float_new_impl(&PyFloat_Type, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 if (tmp == NULL)
1631 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001632 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 newobj = type->tp_alloc(type, 0);
1634 if (newobj == NULL) {
1635 Py_DECREF(tmp);
1636 return NULL;
1637 }
1638 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1639 Py_DECREF(tmp);
1640 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001641}
1642
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001643/*[clinic input]
1644float.__getnewargs__
1645[clinic start generated code]*/
1646
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001647static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001648float___getnewargs___impl(PyObject *self)
1649/*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001650{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001651 return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001652}
1653
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001654/* this is for the benefit of the pack/unpack routines below */
1655
1656typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001658} float_format_type;
1659
1660static float_format_type double_format, float_format;
1661static float_format_type detected_double_format, detected_float_format;
1662
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001663/*[clinic input]
1664@classmethod
1665float.__getformat__
1666
1667 typestr: str
1668 Must be 'double' or 'float'.
1669 /
1670
1671You probably don't want to use this function.
1672
1673It exists mainly to be used in Python's test suite.
1674
1675This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
1676little-endian' best describes the format of floating point numbers used by the
1677C type named by typestr.
1678[clinic start generated code]*/
1679
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001680static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001681float___getformat___impl(PyTypeObject *type, const char *typestr)
1682/*[clinic end generated code: output=2bfb987228cc9628 input=d5a52600f835ad67]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001685
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001686 if (strcmp(typestr, "double") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 r = double_format;
1688 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001689 else if (strcmp(typestr, "float") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 r = float_format;
1691 }
1692 else {
1693 PyErr_SetString(PyExc_ValueError,
1694 "__getformat__() argument 1 must be "
1695 "'double' or 'float'");
1696 return NULL;
1697 }
1698
1699 switch (r) {
1700 case unknown_format:
1701 return PyUnicode_FromString("unknown");
1702 case ieee_little_endian_format:
1703 return PyUnicode_FromString("IEEE, little-endian");
1704 case ieee_big_endian_format:
1705 return PyUnicode_FromString("IEEE, big-endian");
1706 default:
Victor Stinner04394df2019-11-18 17:39:48 +01001707 PyErr_SetString(PyExc_RuntimeError,
1708 "insane float_format or double_format");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 return NULL;
1710 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001711}
1712
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001713/*[clinic input]
1714@classmethod
1715float.__set_format__
1716
1717 typestr: str
1718 Must be 'double' or 'float'.
1719 fmt: str
1720 Must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian',
1721 and in addition can only be one of the latter two if it appears to
1722 match the underlying C reality.
1723 /
1724
1725You probably don't want to use this function.
1726
1727It exists mainly to be used in Python's test suite.
1728
1729Override the automatic determination of C-level floating point type.
1730This affects how floats are converted to and from binary strings.
1731[clinic start generated code]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001732
1733static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001734float___set_format___impl(PyTypeObject *type, const char *typestr,
1735 const char *fmt)
1736/*[clinic end generated code: output=504460f5dc85acbd input=5306fa2b81a997e4]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 float_format_type f;
1739 float_format_type detected;
1740 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 if (strcmp(typestr, "double") == 0) {
1743 p = &double_format;
1744 detected = detected_double_format;
1745 }
1746 else if (strcmp(typestr, "float") == 0) {
1747 p = &float_format;
1748 detected = detected_float_format;
1749 }
1750 else {
1751 PyErr_SetString(PyExc_ValueError,
1752 "__setformat__() argument 1 must "
1753 "be 'double' or 'float'");
1754 return NULL;
1755 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001756
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001757 if (strcmp(fmt, "unknown") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 f = unknown_format;
1759 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001760 else if (strcmp(fmt, "IEEE, little-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 f = ieee_little_endian_format;
1762 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001763 else if (strcmp(fmt, "IEEE, big-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 f = ieee_big_endian_format;
1765 }
1766 else {
1767 PyErr_SetString(PyExc_ValueError,
1768 "__setformat__() argument 2 must be "
1769 "'unknown', 'IEEE, little-endian' or "
1770 "'IEEE, big-endian'");
1771 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 if (f != unknown_format && f != detected) {
1776 PyErr_Format(PyExc_ValueError,
1777 "can only set %s format to 'unknown' or the "
1778 "detected platform value", typestr);
1779 return NULL;
1780 }
1781
1782 *p = f;
1783 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001784}
1785
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001786static PyObject *
1787float_getreal(PyObject *v, void *closure)
1788{
1789 return float_float(v);
1790}
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001791
Guido van Rossumb43daf72007-08-01 18:08:08 +00001792static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001793float_getimag(PyObject *v, void *closure)
Guido van Rossumb43daf72007-08-01 18:08:08 +00001794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001796}
1797
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001798/*[clinic input]
1799float.__format__
1800
1801 format_spec: unicode
1802 /
1803
1804Formats the float according to format_spec.
1805[clinic start generated code]*/
1806
Eric Smith8c663262007-08-25 02:26:07 +00001807static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001808float___format___impl(PyObject *self, PyObject *format_spec)
1809/*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/
Eric Smith8c663262007-08-25 02:26:07 +00001810{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001811 _PyUnicodeWriter writer;
1812 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001813
Victor Stinner8f674cc2013-04-17 23:02:17 +02001814 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001815 ret = _PyFloat_FormatAdvancedWriter(
1816 &writer,
1817 self,
1818 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1819 if (ret == -1) {
1820 _PyUnicodeWriter_Dealloc(&writer);
1821 return NULL;
1822 }
1823 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001824}
1825
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001826static PyMethodDef float_methods[] = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001827 FLOAT_CONJUGATE_METHODDEF
1828 FLOAT___TRUNC___METHODDEF
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +03001829 FLOAT___FLOOR___METHODDEF
1830 FLOAT___CEIL___METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001831 FLOAT___ROUND___METHODDEF
1832 FLOAT_AS_INTEGER_RATIO_METHODDEF
1833 FLOAT_FROMHEX_METHODDEF
1834 FLOAT_HEX_METHODDEF
1835 FLOAT_IS_INTEGER_METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001836 FLOAT___GETNEWARGS___METHODDEF
1837 FLOAT___GETFORMAT___METHODDEF
1838 FLOAT___SET_FORMAT___METHODDEF
1839 FLOAT___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001841};
1842
Guido van Rossumb43daf72007-08-01 18:08:08 +00001843static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 {"real",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001845 float_getreal, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001846 "the real part of a complex number",
1847 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 {"imag",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001849 float_getimag, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001850 "the imaginary part of a complex number",
1851 NULL},
1852 {NULL} /* Sentinel */
1853};
1854
Tim Peters6d6c1a32001-08-02 04:15:00 +00001855
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001856static PyNumberMethods float_as_number = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001857 float_add, /* nb_add */
1858 float_sub, /* nb_subtract */
1859 float_mul, /* nb_multiply */
1860 float_rem, /* nb_remainder */
1861 float_divmod, /* nb_divmod */
1862 float_pow, /* nb_power */
1863 (unaryfunc)float_neg, /* nb_negative */
1864 float_float, /* nb_positive */
1865 (unaryfunc)float_abs, /* nb_absolute */
1866 (inquiry)float_bool, /* nb_bool */
1867 0, /* nb_invert */
1868 0, /* nb_lshift */
1869 0, /* nb_rshift */
1870 0, /* nb_and */
1871 0, /* nb_xor */
1872 0, /* nb_or */
1873 float___trunc___impl, /* nb_int */
1874 0, /* nb_reserved */
1875 float_float, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 0, /* nb_inplace_add */
1877 0, /* nb_inplace_subtract */
1878 0, /* nb_inplace_multiply */
1879 0, /* nb_inplace_remainder */
1880 0, /* nb_inplace_power */
1881 0, /* nb_inplace_lshift */
1882 0, /* nb_inplace_rshift */
1883 0, /* nb_inplace_and */
1884 0, /* nb_inplace_xor */
1885 0, /* nb_inplace_or */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001886 float_floor_div, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 float_div, /* nb_true_divide */
1888 0, /* nb_inplace_floor_divide */
1889 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001890};
1891
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001892PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1894 "float",
1895 sizeof(PyFloatObject),
1896 0,
1897 (destructor)float_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001898 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 0, /* tp_getattr */
1900 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001901 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 (reprfunc)float_repr, /* tp_repr */
1903 &float_as_number, /* tp_as_number */
1904 0, /* tp_as_sequence */
1905 0, /* tp_as_mapping */
1906 (hashfunc)float_hash, /* tp_hash */
1907 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001908 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 PyObject_GenericGetAttr, /* tp_getattro */
1910 0, /* tp_setattro */
1911 0, /* tp_as_buffer */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001912 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001913 float_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 0, /* tp_traverse */
1915 0, /* tp_clear */
1916 float_richcompare, /* tp_richcompare */
1917 0, /* tp_weaklistoffset */
1918 0, /* tp_iter */
1919 0, /* tp_iternext */
1920 float_methods, /* tp_methods */
1921 0, /* tp_members */
1922 float_getset, /* tp_getset */
1923 0, /* tp_base */
1924 0, /* tp_dict */
1925 0, /* tp_descr_get */
1926 0, /* tp_descr_set */
1927 0, /* tp_dictoffset */
1928 0, /* tp_init */
1929 0, /* tp_alloc */
1930 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001931};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001932
Victor Stinner1c8f0592013-07-22 22:24:54 +02001933int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001934_PyFloat_Init(void)
1935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 /* We attempt to determine if this machine is using IEEE
1937 floating point formats by peering at the bits of some
1938 carefully chosen values. If it looks like we are on an
1939 IEEE platform, the float packing/unpacking routines can
1940 just copy bits, if not they resort to arithmetic & shifts
1941 and masks. The shifts & masks approach works on all finite
1942 values, but what happens to infinities, NaNs and signed
1943 zeroes on packing is an accident, and attempting to unpack
1944 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 Note that if we're on some whacked-out platform which uses
1947 IEEE formats but isn't strictly little-endian or big-
1948 endian, we will fall back to the portable shifts & masks
1949 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001950
1951#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 {
1953 double x = 9006104071832581.0;
1954 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1955 detected_double_format = ieee_big_endian_format;
1956 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1957 detected_double_format = ieee_little_endian_format;
1958 else
1959 detected_double_format = unknown_format;
1960 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001961#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001963#endif
1964
1965#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 {
1967 float y = 16711938.0;
1968 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1969 detected_float_format = ieee_big_endian_format;
1970 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1971 detected_float_format = ieee_little_endian_format;
1972 else
1973 detected_float_format = unknown_format;
1974 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001975#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001977#endif
1978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 double_format = detected_double_format;
1980 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001983 if (FloatInfoType.tp_name == NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001984 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001985 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001986 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02001987 }
1988 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001989}
1990
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001991void
Victor Stinner2ba59372020-06-05 00:50:05 +02001992_PyFloat_ClearFreeList(PyThreadState *tstate)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001993{
Victor Stinner2ba59372020-06-05 00:50:05 +02001994 struct _Py_float_state *state = &tstate->interp->float_state;
Victor Stinnerbcb19832020-06-08 02:14:47 +02001995 PyFloatObject *f = state->free_list;
1996 while (f != NULL) {
1997 PyFloatObject *next = (PyFloatObject*) Py_TYPE(f);
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001998 PyObject_FREE(f);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001999 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 }
Victor Stinner2ba59372020-06-05 00:50:05 +02002001 state->free_list = NULL;
2002 state->numfree = 0;
Christian Heimes15ebc882008-02-04 18:48:49 +00002003}
2004
2005void
Victor Stinner2ba59372020-06-05 00:50:05 +02002006_PyFloat_Fini(PyThreadState *tstate)
Christian Heimes15ebc882008-02-04 18:48:49 +00002007{
Victor Stinner2ba59372020-06-05 00:50:05 +02002008 _PyFloat_ClearFreeList(tstate);
Victor Stinnerbcb19832020-06-08 02:14:47 +02002009#ifdef Py_DEBUG
2010 struct _Py_float_state *state = &tstate->interp->float_state;
2011 state->numfree = -1;
2012#endif
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002013}
Tim Peters9905b942003-03-20 20:53:32 +00002014
David Malcolm49526f42012-06-22 14:55:41 -04002015/* Print summary info about the state of the optimized allocator */
2016void
2017_PyFloat_DebugMallocStats(FILE *out)
2018{
Victor Stinner2ba59372020-06-05 00:50:05 +02002019 PyInterpreterState *interp = _PyInterpreterState_GET();
2020 struct _Py_float_state *state = &interp->float_state;
David Malcolm49526f42012-06-22 14:55:41 -04002021 _PyDebugAllocatorStats(out,
2022 "free PyFloatObject",
Victor Stinner2ba59372020-06-05 00:50:05 +02002023 state->numfree, sizeof(PyFloatObject));
David Malcolm49526f42012-06-22 14:55:41 -04002024}
2025
2026
Tim Peters9905b942003-03-20 20:53:32 +00002027/*----------------------------------------------------------------------------
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002028 * _PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h.
2029 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
2030 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
2031 * We use:
2032 * bits = (unsigned short)f; Note the truncation
2033 * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
2034 * bits++;
2035 * }
Tim Peters9905b942003-03-20 20:53:32 +00002036 */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002037
2038int
2039_PyFloat_Pack2(double x, unsigned char *p, int le)
2040{
2041 unsigned char sign;
2042 int e;
2043 double f;
2044 unsigned short bits;
2045 int incr = 1;
2046
2047 if (x == 0.0) {
2048 sign = (copysign(1.0, x) == -1.0);
2049 e = 0;
2050 bits = 0;
2051 }
2052 else if (Py_IS_INFINITY(x)) {
2053 sign = (x < 0.0);
2054 e = 0x1f;
2055 bits = 0;
2056 }
2057 else if (Py_IS_NAN(x)) {
2058 /* There are 2046 distinct half-precision NaNs (1022 signaling and
2059 1024 quiet), but there are only two quiet NaNs that don't arise by
2060 quieting a signaling NaN; we get those by setting the topmost bit
2061 of the fraction field and clearing all other fraction bits. We
2062 choose the one with the appropriate sign. */
2063 sign = (copysign(1.0, x) == -1.0);
2064 e = 0x1f;
2065 bits = 512;
2066 }
2067 else {
2068 sign = (x < 0.0);
2069 if (sign) {
2070 x = -x;
2071 }
2072
2073 f = frexp(x, &e);
2074 if (f < 0.5 || f >= 1.0) {
2075 PyErr_SetString(PyExc_SystemError,
2076 "frexp() result out of range");
2077 return -1;
2078 }
2079
2080 /* Normalize f to be in the range [1.0, 2.0) */
2081 f *= 2.0;
2082 e--;
2083
2084 if (e >= 16) {
2085 goto Overflow;
2086 }
2087 else if (e < -25) {
2088 /* |x| < 2**-25. Underflow to zero. */
2089 f = 0.0;
2090 e = 0;
2091 }
2092 else if (e < -14) {
2093 /* |x| < 2**-14. Gradual underflow */
2094 f = ldexp(f, 14 + e);
2095 e = 0;
2096 }
2097 else /* if (!(e == 0 && f == 0.0)) */ {
2098 e += 15;
2099 f -= 1.0; /* Get rid of leading 1 */
2100 }
2101
2102 f *= 1024.0; /* 2**10 */
2103 /* Round to even */
2104 bits = (unsigned short)f; /* Note the truncation */
2105 assert(bits < 1024);
2106 assert(e < 31);
2107 if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2108 ++bits;
2109 if (bits == 1024) {
2110 /* The carry propagated out of a string of 10 1 bits. */
2111 bits = 0;
2112 ++e;
2113 if (e == 31)
2114 goto Overflow;
2115 }
2116 }
2117 }
2118
2119 bits |= (e << 10) | (sign << 15);
2120
2121 /* Write out result. */
2122 if (le) {
2123 p += 1;
2124 incr = -1;
2125 }
2126
2127 /* First byte */
2128 *p = (unsigned char)((bits >> 8) & 0xFF);
2129 p += incr;
2130
2131 /* Second byte */
2132 *p = (unsigned char)(bits & 0xFF);
2133
2134 return 0;
2135
2136 Overflow:
2137 PyErr_SetString(PyExc_OverflowError,
2138 "float too large to pack with e format");
2139 return -1;
2140}
2141
Tim Peters9905b942003-03-20 20:53:32 +00002142int
2143_PyFloat_Pack4(double x, unsigned char *p, int le)
2144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (float_format == unknown_format) {
2146 unsigned char sign;
2147 int e;
2148 double f;
2149 unsigned int fbits;
2150 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 if (le) {
2153 p += 3;
2154 incr = -1;
2155 }
Tim Peters9905b942003-03-20 20:53:32 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 if (x < 0) {
2158 sign = 1;
2159 x = -x;
2160 }
2161 else
2162 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 /* Normalize f to be in the range [1.0, 2.0) */
2167 if (0.5 <= f && f < 1.0) {
2168 f *= 2.0;
2169 e--;
2170 }
2171 else if (f == 0.0)
2172 e = 0;
2173 else {
2174 PyErr_SetString(PyExc_SystemError,
2175 "frexp() result out of range");
2176 return -1;
2177 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 if (e >= 128)
2180 goto Overflow;
2181 else if (e < -126) {
2182 /* Gradual underflow */
2183 f = ldexp(f, 126 + e);
2184 e = 0;
2185 }
2186 else if (!(e == 0 && f == 0.0)) {
2187 e += 127;
2188 f -= 1.0; /* Get rid of leading 1 */
2189 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 f *= 8388608.0; /* 2**23 */
2192 fbits = (unsigned int)(f + 0.5); /* Round */
2193 assert(fbits <= 8388608);
2194 if (fbits >> 23) {
2195 /* The carry propagated out of a string of 23 1 bits. */
2196 fbits = 0;
2197 ++e;
2198 if (e >= 255)
2199 goto Overflow;
2200 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 /* First byte */
2203 *p = (sign << 7) | (e >> 1);
2204 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 /* Second byte */
2207 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2208 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 /* Third byte */
2211 *p = (fbits >> 8) & 0xFF;
2212 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 /* Fourth byte */
2215 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 /* Done */
2218 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 }
2221 else {
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002222 float y = (float)x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002224
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002225 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002227
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002228 unsigned char s[sizeof(float)];
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002229 memcpy(s, &y, sizeof(float));
2230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 if ((float_format == ieee_little_endian_format && !le)
2232 || (float_format == ieee_big_endian_format && le)) {
2233 p += 3;
2234 incr = -1;
2235 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 for (i = 0; i < 4; i++) {
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002238 *p = s[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 p += incr;
2240 }
2241 return 0;
2242 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002243 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 PyErr_SetString(PyExc_OverflowError,
2245 "float too large to pack with f format");
2246 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002247}
2248
2249int
2250_PyFloat_Pack8(double x, unsigned char *p, int le)
2251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 if (double_format == unknown_format) {
2253 unsigned char sign;
2254 int e;
2255 double f;
2256 unsigned int fhi, flo;
2257 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 if (le) {
2260 p += 7;
2261 incr = -1;
2262 }
Tim Peters9905b942003-03-20 20:53:32 +00002263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if (x < 0) {
2265 sign = 1;
2266 x = -x;
2267 }
2268 else
2269 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 /* Normalize f to be in the range [1.0, 2.0) */
2274 if (0.5 <= f && f < 1.0) {
2275 f *= 2.0;
2276 e--;
2277 }
2278 else if (f == 0.0)
2279 e = 0;
2280 else {
2281 PyErr_SetString(PyExc_SystemError,
2282 "frexp() result out of range");
2283 return -1;
2284 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 if (e >= 1024)
2287 goto Overflow;
2288 else if (e < -1022) {
2289 /* Gradual underflow */
2290 f = ldexp(f, 1022 + e);
2291 e = 0;
2292 }
2293 else if (!(e == 0 && f == 0.0)) {
2294 e += 1023;
2295 f -= 1.0; /* Get rid of leading 1 */
2296 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2299 f *= 268435456.0; /* 2**28 */
2300 fhi = (unsigned int)f; /* Truncate */
2301 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 f -= (double)fhi;
2304 f *= 16777216.0; /* 2**24 */
2305 flo = (unsigned int)(f + 0.5); /* Round */
2306 assert(flo <= 16777216);
2307 if (flo >> 24) {
2308 /* The carry propagated out of a string of 24 1 bits. */
2309 flo = 0;
2310 ++fhi;
2311 if (fhi >> 28) {
2312 /* And it also progagated out of the next 28 bits. */
2313 fhi = 0;
2314 ++e;
2315 if (e >= 2047)
2316 goto Overflow;
2317 }
2318 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 /* First byte */
2321 *p = (sign << 7) | (e >> 4);
2322 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* Second byte */
2325 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2326 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 /* Third byte */
2329 *p = (fhi >> 16) & 0xFF;
2330 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 /* Fourth byte */
2333 *p = (fhi >> 8) & 0xFF;
2334 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 /* Fifth byte */
2337 *p = fhi & 0xFF;
2338 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 /* Sixth byte */
2341 *p = (flo >> 16) & 0xFF;
2342 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 /* Seventh byte */
2345 *p = (flo >> 8) & 0xFF;
2346 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 /* Eighth byte */
2349 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002350 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 /* Done */
2353 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 Overflow:
2356 PyErr_SetString(PyExc_OverflowError,
2357 "float too large to pack with d format");
2358 return -1;
2359 }
2360 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002361 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 if ((double_format == ieee_little_endian_format && !le)
2365 || (double_format == ieee_big_endian_format && le)) {
2366 p += 7;
2367 incr = -1;
2368 }
2369
2370 for (i = 0; i < 8; i++) {
2371 *p = *s++;
2372 p += incr;
2373 }
2374 return 0;
2375 }
Tim Peters9905b942003-03-20 20:53:32 +00002376}
2377
2378double
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002379_PyFloat_Unpack2(const unsigned char *p, int le)
2380{
2381 unsigned char sign;
2382 int e;
2383 unsigned int f;
2384 double x;
2385 int incr = 1;
2386
2387 if (le) {
2388 p += 1;
2389 incr = -1;
2390 }
2391
2392 /* First byte */
2393 sign = (*p >> 7) & 1;
2394 e = (*p & 0x7C) >> 2;
2395 f = (*p & 0x03) << 8;
2396 p += incr;
2397
2398 /* Second byte */
2399 f |= *p;
2400
2401 if (e == 0x1f) {
2402#ifdef PY_NO_SHORT_FLOAT_REPR
2403 if (f == 0) {
2404 /* Infinity */
2405 return sign ? -Py_HUGE_VAL : Py_HUGE_VAL;
2406 }
2407 else {
2408 /* NaN */
2409#ifdef Py_NAN
2410 return sign ? -Py_NAN : Py_NAN;
2411#else
2412 PyErr_SetString(
2413 PyExc_ValueError,
2414 "can't unpack IEEE 754 NaN "
2415 "on platform that does not support NaNs");
2416 return -1;
2417#endif /* #ifdef Py_NAN */
2418 }
2419#else
2420 if (f == 0) {
2421 /* Infinity */
2422 return _Py_dg_infinity(sign);
2423 }
2424 else {
2425 /* NaN */
2426 return _Py_dg_stdnan(sign);
2427 }
2428#endif /* #ifdef PY_NO_SHORT_FLOAT_REPR */
2429 }
2430
2431 x = (double)f / 1024.0;
2432
2433 if (e == 0) {
2434 e = -14;
2435 }
2436 else {
2437 x += 1.0;
2438 e -= 15;
2439 }
2440 x = ldexp(x, e);
2441
2442 if (sign)
2443 x = -x;
2444
2445 return x;
2446}
2447
2448double
Tim Peters9905b942003-03-20 20:53:32 +00002449_PyFloat_Unpack4(const unsigned char *p, int le)
2450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 if (float_format == unknown_format) {
2452 unsigned char sign;
2453 int e;
2454 unsigned int f;
2455 double x;
2456 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 if (le) {
2459 p += 3;
2460 incr = -1;
2461 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 /* First byte */
2464 sign = (*p >> 7) & 1;
2465 e = (*p & 0x7F) << 1;
2466 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 /* Second byte */
2469 e |= (*p >> 7) & 1;
2470 f = (*p & 0x7F) << 16;
2471 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 if (e == 255) {
2474 PyErr_SetString(
2475 PyExc_ValueError,
2476 "can't unpack IEEE 754 special value "
2477 "on non-IEEE platform");
2478 return -1;
2479 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 /* Third byte */
2482 f |= *p << 8;
2483 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 /* Fourth byte */
2486 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 /* XXX This sadly ignores Inf/NaN issues */
2491 if (e == 0)
2492 e = -126;
2493 else {
2494 x += 1.0;
2495 e -= 127;
2496 }
2497 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 if (sign)
2500 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 return x;
2503 }
2504 else {
2505 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 if ((float_format == ieee_little_endian_format && !le)
2508 || (float_format == ieee_big_endian_format && le)) {
2509 char buf[4];
2510 char *d = &buf[3];
2511 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 for (i = 0; i < 4; i++) {
2514 *d-- = *p++;
2515 }
2516 memcpy(&x, buf, 4);
2517 }
2518 else {
2519 memcpy(&x, p, 4);
2520 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 return x;
2523 }
Tim Peters9905b942003-03-20 20:53:32 +00002524}
2525
2526double
2527_PyFloat_Unpack8(const unsigned char *p, int le)
2528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 if (double_format == unknown_format) {
2530 unsigned char sign;
2531 int e;
2532 unsigned int fhi, flo;
2533 double x;
2534 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 if (le) {
2537 p += 7;
2538 incr = -1;
2539 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 /* First byte */
2542 sign = (*p >> 7) & 1;
2543 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 /* Second byte */
2548 e |= (*p >> 4) & 0xF;
2549 fhi = (*p & 0xF) << 24;
2550 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 if (e == 2047) {
2553 PyErr_SetString(
2554 PyExc_ValueError,
2555 "can't unpack IEEE 754 special value "
2556 "on non-IEEE platform");
2557 return -1.0;
2558 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 /* Third byte */
2561 fhi |= *p << 16;
2562 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 /* Fourth byte */
2565 fhi |= *p << 8;
2566 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 /* Fifth byte */
2569 fhi |= *p;
2570 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 /* Sixth byte */
2573 flo = *p << 16;
2574 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 /* Seventh byte */
2577 flo |= *p << 8;
2578 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 /* Eighth byte */
2581 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2584 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 if (e == 0)
2587 e = -1022;
2588 else {
2589 x += 1.0;
2590 e -= 1023;
2591 }
2592 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 if (sign)
2595 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 return x;
2598 }
2599 else {
2600 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 if ((double_format == ieee_little_endian_format && !le)
2603 || (double_format == ieee_big_endian_format && le)) {
2604 char buf[8];
2605 char *d = &buf[7];
2606 int i;
2607
2608 for (i = 0; i < 8; i++) {
2609 *d-- = *p++;
2610 }
2611 memcpy(&x, buf, 8);
2612 }
2613 else {
2614 memcpy(&x, p, 8);
2615 }
2616
2617 return x;
2618 }
Tim Peters9905b942003-03-20 20:53:32 +00002619}