blob: d0af0ea1a9825744fb902567b5e45822d907160d [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Float object implementation */
2
Guido van Rossum2a9096b1990-10-21 22:15:08 +00003/* XXX There should be overflow checks here, but it's hard to check
4 for any kind of float exception without losing portability. */
5
Guido van Rossumc0b618a1997-05-02 03:12:38 +00006#include "Python.h"
Victor Stinner04fc4f22020-06-16 01:28:07 +02007#include "pycore_dtoa.h" // _Py_dg_dtoa()
Victor Stinner2ba59372020-06-05 00:50:05 +02008#include "pycore_interp.h" // _PyInterpreterState.float_state
Victor Stinner04fc4f22020-06-16 01:28:07 +02009#include "pycore_object.h" // _PyObject_Init()
Victor Stinner2ba59372020-06-05 00:50:05 +020010#include "pycore_pystate.h" // _PyInterpreterState_GET()
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Guido van Rossum3f5da241990-12-20 15:06:42 +000012#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000013#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000014
Serhiy Storchakab5c51d32017-03-11 09:21:05 +020015/*[clinic input]
16class float "PyObject *" "&PyFloat_Type"
17[clinic start generated code]*/
18/*[clinic end generated code: output=da39a3ee5e6b4b0d input=dd0003f68f144284]*/
19
20#include "clinic/floatobject.c.h"
Guido van Rossum6923e131990-11-02 17:50:43 +000021
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000022#ifndef PyFloat_MAXFREELIST
Victor Stinner2ba59372020-06-05 00:50:05 +020023# define PyFloat_MAXFREELIST 100
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000024#endif
Guido van Rossum3fce8831999-03-12 19:43:17 +000025
Victor Stinner522691c2020-06-23 16:40:40 +020026
27static struct _Py_float_state *
28get_float_state(void)
29{
30 PyInterpreterState *interp = _PyInterpreterState_GET();
31 return &interp->float_state;
32}
33
34
Christian Heimes93852662007-12-01 12:22:32 +000035double
36PyFloat_GetMax(void)
37{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000038 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000039}
40
41double
42PyFloat_GetMin(void)
43{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000045}
46
Christian Heimesd32ed6f2008-01-14 18:49:24 +000047static PyTypeObject FloatInfoType;
48
49PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000050"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000051\n\
Raymond Hettinger71170742019-09-11 07:17:32 -070052A named tuple holding information about the float type. It contains low level\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000053information about the precision and internal representation. Please study\n\
54your system's :file:`float.h` for more information.");
55
56static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 {"max", "DBL_MAX -- maximum representable finite float"},
58 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
59 "is representable"},
60 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
61 "is representable"},
Stefano Taschini0301c9b2018-03-26 11:41:30 +020062 {"min", "DBL_MIN -- Minimum positive normalized float"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
64 "is a normalized float"},
65 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
66 "a normalized"},
Zackery Spytzfdc5a942020-05-24 04:03:52 -060067 {"dig", "DBL_DIG -- maximum number of decimal digits that "
68 "can be faithfully represented in a float"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
70 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
71 "representable float"},
72 {"radix", "FLT_RADIX -- radix of exponent"},
Zackery Spytzfdc5a942020-05-24 04:03:52 -060073 {"rounds", "FLT_ROUNDS -- rounding mode used for arithmetic "
74 "operations"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +000076};
77
78static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 "sys.float_info", /* name */
80 floatinfo__doc__, /* doc */
81 floatinfo_fields, /* fields */
82 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +000083};
84
Christian Heimes93852662007-12-01 12:22:32 +000085PyObject *
86PyFloat_GetInfo(void)
87{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 PyObject* floatinfo;
89 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +000090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 floatinfo = PyStructSequence_New(&FloatInfoType);
92 if (floatinfo == NULL) {
93 return NULL;
94 }
Christian Heimes93852662007-12-01 12:22:32 +000095
Christian Heimesd32ed6f2008-01-14 18:49:24 +000096#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +000098#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 SetDblFlag(DBL_MAX);
102 SetIntFlag(DBL_MAX_EXP);
103 SetIntFlag(DBL_MAX_10_EXP);
104 SetDblFlag(DBL_MIN);
105 SetIntFlag(DBL_MIN_EXP);
106 SetIntFlag(DBL_MIN_10_EXP);
107 SetIntFlag(DBL_DIG);
108 SetIntFlag(DBL_MANT_DIG);
109 SetDblFlag(DBL_EPSILON);
110 SetIntFlag(FLT_RADIX);
111 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000112#undef SetIntFlag
113#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114
115 if (PyErr_Occurred()) {
116 Py_CLEAR(floatinfo);
117 return NULL;
118 }
119 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000120}
121
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000122PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000123PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000124{
Victor Stinner522691c2020-06-23 16:40:40 +0200125 struct _Py_float_state *state = get_float_state();
Victor Stinner2ba59372020-06-05 00:50:05 +0200126 PyFloatObject *op = state->free_list;
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000127 if (op != NULL) {
Victor Stinnerbcb19832020-06-08 02:14:47 +0200128#ifdef Py_DEBUG
129 // PyFloat_FromDouble() must not be called after _PyFloat_Fini()
130 assert(state->numfree != -1);
131#endif
Victor Stinner2ba59372020-06-05 00:50:05 +0200132 state->free_list = (PyFloatObject *) Py_TYPE(op);
133 state->numfree--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 }
Victor Stinner2ba59372020-06-05 00:50:05 +0200135 else {
136 op = PyObject_Malloc(sizeof(PyFloatObject));
137 if (!op) {
138 return PyErr_NoMemory();
139 }
140 }
Victor Stinner04fc4f22020-06-16 01:28:07 +0200141 _PyObject_Init((PyObject*)op, &PyFloat_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 op->ob_fval = fval;
143 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144}
145
Brett Cannona721aba2016-09-09 14:57:09 -0700146static PyObject *
147float_from_string_inner(const char *s, Py_ssize_t len, void *obj)
148{
149 double x;
150 const char *end;
151 const char *last = s + len;
152 /* strip space */
153 while (s < last && Py_ISSPACE(*s)) {
154 s++;
155 }
156
157 while (s < last - 1 && Py_ISSPACE(last[-1])) {
158 last--;
159 }
160
161 /* We don't care about overflow or underflow. If the platform
162 * supports them, infinities and signed zeroes (on underflow) are
163 * fine. */
164 x = PyOS_string_to_double(s, (char **)&end, NULL);
165 if (end != last) {
166 PyErr_Format(PyExc_ValueError,
167 "could not convert string to float: "
168 "%R", obj);
169 return NULL;
170 }
171 else if (x == -1.0 && PyErr_Occurred()) {
172 return NULL;
173 }
174 else {
175 return PyFloat_FromDouble(x);
176 }
177}
178
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000179PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000180PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000181{
Brett Cannona721aba2016-09-09 14:57:09 -0700182 const char *s;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000183 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 Py_ssize_t len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200185 Py_buffer view = {NULL, NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200189 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000191 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200192 assert(PyUnicode_IS_ASCII(s_buffer));
193 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200194 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200195 assert(s != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000197 else if (PyBytes_Check(v)) {
198 s = PyBytes_AS_STRING(v);
199 len = PyBytes_GET_SIZE(v);
200 }
201 else if (PyByteArray_Check(v)) {
202 s = PyByteArray_AS_STRING(v);
203 len = PyByteArray_GET_SIZE(v);
204 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200205 else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
206 s = (const char *)view.buf;
207 len = view.len;
Martin Pantereeb896c2015-11-07 02:32:21 +0000208 /* Copy to NUL-terminated buffer. */
209 s_buffer = PyBytes_FromStringAndSize(s, len);
210 if (s_buffer == NULL) {
211 PyBuffer_Release(&view);
212 return NULL;
213 }
214 s = PyBytes_AS_STRING(s_buffer);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200215 }
216 else {
Ezio Melottia5b95992013-11-07 19:18:34 +0200217 PyErr_Format(PyExc_TypeError,
218 "float() argument must be a string or a number, not '%.200s'",
219 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 return NULL;
221 }
Brett Cannona721aba2016-09-09 14:57:09 -0700222 result = _Py_string_to_number_with_underscores(s, len, "float", v, v,
223 float_from_string_inner);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200224 PyBuffer_Release(&view);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000225 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000227}
228
Guido van Rossum234f9421993-06-17 12:35:49 +0000229static void
Fred Drakefd99de62000-07-09 05:02:18 +0000230float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 if (PyFloat_CheckExact(op)) {
Victor Stinner522691c2020-06-23 16:40:40 +0200233 struct _Py_float_state *state = get_float_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +0200234#ifdef Py_DEBUG
235 // float_dealloc() must not be called after _PyFloat_Fini()
236 assert(state->numfree != -1);
237#endif
Victor Stinner2ba59372020-06-05 00:50:05 +0200238 if (state->numfree >= PyFloat_MAXFREELIST) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000239 PyObject_FREE(op);
240 return;
241 }
Victor Stinner2ba59372020-06-05 00:50:05 +0200242 state->numfree++;
243 Py_SET_TYPE(op, (PyTypeObject *)state->free_list);
244 state->free_list = op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 }
Victor Stinner522691c2020-06-23 16:40:40 +0200246 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 Py_TYPE(op)->tp_free((PyObject *)op);
Victor Stinner522691c2020-06-23 16:40:40 +0200248 }
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000249}
250
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000251double
Fred Drakefd99de62000-07-09 05:02:18 +0000252PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 PyNumberMethods *nb;
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300255 PyObject *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 if (op == NULL) {
259 PyErr_BadArgument();
260 return -1;
261 }
Tim Petersd2364e82001-11-01 20:09:42 +0000262
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300263 if (PyFloat_Check(op)) {
264 return PyFloat_AS_DOUBLE(op);
265 }
266
267 nb = Py_TYPE(op)->tp_as_number;
268 if (nb == NULL || nb->nb_float == NULL) {
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300269 if (nb && nb->nb_index) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300270 PyObject *res = _PyNumber_Index(op);
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300271 if (!res) {
272 return -1;
273 }
274 double val = PyLong_AsDouble(res);
275 Py_DECREF(res);
276 return val;
277 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300278 PyErr_Format(PyExc_TypeError, "must be real number, not %.50s",
Victor Stinner58ac7002020-02-07 03:04:21 +0100279 Py_TYPE(op)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 return -1;
281 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000282
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300283 res = (*nb->nb_float) (op);
284 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 return -1;
286 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300287 if (!PyFloat_CheckExact(res)) {
288 if (!PyFloat_Check(res)) {
289 PyErr_Format(PyExc_TypeError,
290 "%.50s.__float__ returned non-float (type %.50s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100291 Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name);
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300292 Py_DECREF(res);
293 return -1;
294 }
295 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
296 "%.50s.__float__ returned non-float (type %.50s). "
297 "The ability to return an instance of a strict subclass of float "
298 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner58ac7002020-02-07 03:04:21 +0100299 Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name)) {
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300300 Py_DECREF(res);
301 return -1;
302 }
303 }
Tim Petersd2364e82001-11-01 20:09:42 +0000304
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300305 val = PyFloat_AS_DOUBLE(res);
306 Py_DECREF(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000308}
309
Neil Schemenauer32117e52001-01-04 01:44:34 +0000310/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000311 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000312 set to NULL, and the function invoking this macro returns NULL. If
Serhiy Storchaka95949422013-08-27 19:40:23 +0300313 obj is not of float or int type, Py_NotImplemented is incref'ed,
Tim Peters77d8a4f2001-12-11 20:31:34 +0000314 stored in obj, and returned from the function invoking this macro.
315*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316#define CONVERT_TO_DOUBLE(obj, dbl) \
317 if (PyFloat_Check(obj)) \
318 dbl = PyFloat_AS_DOUBLE(obj); \
319 else if (convert_to_double(&(obj), &(dbl)) < 0) \
320 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000321
Eric Smith0923d1d2009-04-16 20:16:10 +0000322/* Methods */
323
Neil Schemenauer32117e52001-01-04 01:44:34 +0000324static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000325convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000326{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200327 PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 if (PyLong_Check(obj)) {
330 *dbl = PyLong_AsDouble(obj);
331 if (*dbl == -1.0 && PyErr_Occurred()) {
332 *v = NULL;
333 return -1;
334 }
335 }
336 else {
337 Py_INCREF(Py_NotImplemented);
338 *v = Py_NotImplemented;
339 return -1;
340 }
341 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000342}
343
Eric Smith0923d1d2009-04-16 20:16:10 +0000344static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000345float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000346{
347 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200348 char *buf;
349
350 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
351 'r', 0,
352 Py_DTSF_ADD_DOT_0,
353 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000354 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000355 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200356 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000357 PyMem_Free(buf);
358 return result;
359}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000360
Tim Peters307fa782004-09-23 08:06:40 +0000361/* Comparison is pretty much a nightmare. When comparing float to float,
362 * we do it as straightforwardly (and long-windedly) as conceivable, so
363 * that, e.g., Python x == y delivers the same result as the platform
364 * C x == y when x and/or y is a NaN.
365 * When mixing float with an integer type, there's no good *uniform* approach.
366 * Converting the double to an integer obviously doesn't work, since we
367 * may lose info from fractional bits. Converting the integer to a double
Serhiy Storchaka95949422013-08-27 19:40:23 +0300368 * also has two failure modes: (1) an int may trigger overflow (too
Tim Peters307fa782004-09-23 08:06:40 +0000369 * 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 +0200370 * 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 +0000371 * 63 bits of precision, but a C double probably has only 53), and then
372 * we can falsely claim equality when low-order integer bits are lost by
373 * coercion to double. So this part is painful too.
374 */
375
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000376static PyObject*
377float_richcompare(PyObject *v, PyObject *w, int op)
378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 double i, j;
380 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 assert(PyFloat_Check(v));
383 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 /* Switch on the type of w. Set i and j to doubles to be compared,
386 * and op to the richcomp to use.
387 */
388 if (PyFloat_Check(w))
389 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 else if (!Py_IS_FINITE(i)) {
392 if (PyLong_Check(w))
393 /* If i is an infinity, its magnitude exceeds any
394 * finite integer, so it doesn't matter which int we
395 * compare i with. If i is a NaN, similarly.
396 */
397 j = 0.0;
398 else
399 goto Unimplemented;
400 }
Tim Peters307fa782004-09-23 08:06:40 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 else if (PyLong_Check(w)) {
403 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
404 int wsign = _PyLong_Sign(w);
405 size_t nbits;
406 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (vsign != wsign) {
409 /* Magnitudes are irrelevant -- the signs alone
410 * determine the outcome.
411 */
412 i = (double)vsign;
413 j = (double)wsign;
414 goto Compare;
415 }
416 /* The signs are the same. */
417 /* Convert w to a double if it fits. In particular, 0 fits. */
418 nbits = _PyLong_NumBits(w);
419 if (nbits == (size_t)-1 && PyErr_Occurred()) {
420 /* This long is so large that size_t isn't big enough
421 * to hold the # of bits. Replace with little doubles
422 * that give the same outcome -- w is so large that
423 * its magnitude must exceed the magnitude of any
424 * finite float.
425 */
426 PyErr_Clear();
427 i = (double)vsign;
428 assert(wsign != 0);
429 j = wsign * 2.0;
430 goto Compare;
431 }
432 if (nbits <= 48) {
433 j = PyLong_AsDouble(w);
434 /* It's impossible that <= 48 bits overflowed. */
435 assert(j != -1.0 || ! PyErr_Occurred());
436 goto Compare;
437 }
438 assert(wsign != 0); /* else nbits was 0 */
439 assert(vsign != 0); /* if vsign were 0, then since wsign is
440 * not 0, we would have taken the
441 * vsign != wsign branch at the start */
442 /* We want to work with non-negative numbers. */
443 if (vsign < 0) {
444 /* "Multiply both sides" by -1; this also swaps the
445 * comparator.
446 */
447 i = -i;
448 op = _Py_SwappedOp[op];
449 }
450 assert(i > 0.0);
451 (void) frexp(i, &exponent);
452 /* exponent is the # of bits in v before the radix point;
453 * we know that nbits (the # of bits in w) > 48 at this point
454 */
455 if (exponent < 0 || (size_t)exponent < nbits) {
456 i = 1.0;
457 j = 2.0;
458 goto Compare;
459 }
460 if ((size_t)exponent > nbits) {
461 i = 2.0;
462 j = 1.0;
463 goto Compare;
464 }
465 /* v and w have the same number of bits before the radix
Serhiy Storchaka95949422013-08-27 19:40:23 +0300466 * point. Construct two ints that have the same comparison
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 * outcome.
468 */
469 {
470 double fracpart;
471 double intpart;
472 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 PyObject *vv = NULL;
474 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 if (wsign < 0) {
477 ww = PyNumber_Negative(w);
478 if (ww == NULL)
479 goto Error;
480 }
481 else
482 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 fracpart = modf(i, &intpart);
485 vv = PyLong_FromDouble(intpart);
486 if (vv == NULL)
487 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 if (fracpart != 0.0) {
490 /* Shift left, and or a 1 bit into vv
491 * to represent the lost fraction.
492 */
493 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000494
Serhiy Storchakaa5119e72019-05-19 14:14:38 +0300495 temp = _PyLong_Lshift(ww, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 if (temp == NULL)
497 goto Error;
498 Py_DECREF(ww);
499 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000500
Serhiy Storchakaa5119e72019-05-19 14:14:38 +0300501 temp = _PyLong_Lshift(vv, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (temp == NULL)
503 goto Error;
504 Py_DECREF(vv);
505 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000506
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300507 temp = PyNumber_Or(vv, _PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 if (temp == NULL)
509 goto Error;
510 Py_DECREF(vv);
511 vv = temp;
512 }
Tim Peters307fa782004-09-23 08:06:40 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 r = PyObject_RichCompareBool(vv, ww, op);
515 if (r < 0)
516 goto Error;
517 result = PyBool_FromLong(r);
518 Error:
519 Py_XDECREF(vv);
520 Py_XDECREF(ww);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 return result;
522 }
523 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000524
Serhiy Storchaka95949422013-08-27 19:40:23 +0300525 else /* w isn't float or int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000527
528 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 switch (op) {
530 case Py_EQ:
531 r = i == j;
532 break;
533 case Py_NE:
534 r = i != j;
535 break;
536 case Py_LE:
537 r = i <= j;
538 break;
539 case Py_GE:
540 r = i >= j;
541 break;
542 case Py_LT:
543 r = i < j;
544 break;
545 case Py_GT:
546 r = i > j;
547 break;
548 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000550
551 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500552 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000553}
554
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000555static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000556float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000559}
560
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000561static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000562float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 double a,b;
565 CONVERT_TO_DOUBLE(v, a);
566 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 a = a + b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000569}
570
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000571static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000572float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 double a,b;
575 CONVERT_TO_DOUBLE(v, a);
576 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 a = a - b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000579}
580
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000581static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000582float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 double a,b;
585 CONVERT_TO_DOUBLE(v, a);
586 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 a = a * b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000589}
590
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000591static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000592float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 double a,b;
595 CONVERT_TO_DOUBLE(v, a);
596 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 if (b == 0.0) {
598 PyErr_SetString(PyExc_ZeroDivisionError,
599 "float division by zero");
600 return NULL;
601 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 a = a / b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000604}
605
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000606static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000607float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 double vx, wx;
610 double mod;
611 CONVERT_TO_DOUBLE(v, vx);
612 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (wx == 0.0) {
614 PyErr_SetString(PyExc_ZeroDivisionError,
615 "float modulo");
616 return NULL;
617 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000619 if (mod) {
620 /* ensure the remainder has the same sign as the denominator */
621 if ((wx < 0) != (mod < 0)) {
622 mod += wx;
623 }
624 }
625 else {
626 /* the remainder is zero, and in the presence of signed zeroes
627 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000628 it has the same sign as the denominator. */
629 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000632}
633
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900634static void
635_float_div_mod(double vx, double wx, double *floordiv, double *mod)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000636{
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900637 double div;
638 *mod = fmod(vx, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 /* fmod is typically exact, so vx-mod is *mathematically* an
640 exact multiple of wx. But this is fp arithmetic, and fp
641 vx - mod is an approximation; the result is that div may
642 not be an exact integral value after the division, although
643 it will always be very close to one.
644 */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900645 div = (vx - *mod) / wx;
646 if (*mod) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 /* ensure the remainder has the same sign as the denominator */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900648 if ((wx < 0) != (*mod < 0)) {
649 *mod += wx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 div -= 1.0;
651 }
652 }
653 else {
654 /* the remainder is zero, and in the presence of signed zeroes
655 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000656 it has the same sign as the denominator. */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900657 *mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 }
659 /* snap quotient to nearest integral value */
660 if (div) {
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900661 *floordiv = floor(div);
662 if (div - *floordiv > 0.5) {
663 *floordiv += 1.0;
Mark Dickinsonbe8147b2020-02-02 11:37:02 +0000664 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 }
666 else {
667 /* div is zero - get the same sign as the true quotient */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900668 *floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 }
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900670}
671
672static PyObject *
673float_divmod(PyObject *v, PyObject *w)
674{
Mark Dickinsonbe8147b2020-02-02 11:37:02 +0000675 double vx, wx;
676 double mod, floordiv;
677 CONVERT_TO_DOUBLE(v, vx);
678 CONVERT_TO_DOUBLE(w, wx);
679 if (wx == 0.0) {
680 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
681 return NULL;
682 }
683 _float_div_mod(vx, wx, &floordiv, &mod);
684 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000685}
686
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000687static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000688float_floor_div(PyObject *v, PyObject *w)
689{
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900690 double vx, wx;
691 double mod, floordiv;
692 CONVERT_TO_DOUBLE(v, vx);
693 CONVERT_TO_DOUBLE(w, wx);
694 if (wx == 0.0) {
695 PyErr_SetString(PyExc_ZeroDivisionError, "float floor division by zero");
696 return NULL;
697 }
698 _float_div_mod(vx, wx, &floordiv, &mod);
699 return PyFloat_FromDouble(floordiv);
Tim Peters63a35712001-12-11 19:57:24 +0000700}
701
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000702/* determine whether x is an odd integer or not; assumes that
703 x is not an infinity or nan. */
704#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
705
Tim Peters63a35712001-12-11 19:57:24 +0000706static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000707float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 double iv, iw, ix;
710 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 if ((PyObject *)z != Py_None) {
713 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
714 "allowed unless all arguments are integers");
715 return NULL;
716 }
Tim Peters32f453e2001-09-03 08:35:41 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 CONVERT_TO_DOUBLE(v, iv);
719 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 /* Sort out special cases here instead of relying on pow() */
722 if (iw == 0) { /* v**0 is 1, even 0**0 */
723 return PyFloat_FromDouble(1.0);
724 }
725 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
726 return PyFloat_FromDouble(iv);
727 }
728 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
729 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
730 }
731 if (Py_IS_INFINITY(iw)) {
732 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
733 * abs(v) > 1 (including case where v infinite)
734 *
735 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
736 * abs(v) > 1 (including case where v infinite)
737 */
738 iv = fabs(iv);
739 if (iv == 1.0)
740 return PyFloat_FromDouble(1.0);
741 else if ((iw > 0.0) == (iv > 1.0))
742 return PyFloat_FromDouble(fabs(iw)); /* return inf */
743 else
744 return PyFloat_FromDouble(0.0);
745 }
746 if (Py_IS_INFINITY(iv)) {
747 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
748 * both cases, we need to add the appropriate sign if w is
749 * an odd integer.
750 */
751 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
752 if (iw > 0.0)
753 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
754 else
755 return PyFloat_FromDouble(iw_is_odd ?
756 copysign(0.0, iv) : 0.0);
757 }
758 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
759 (already dealt with above), and an error
760 if w is negative. */
761 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
762 if (iw < 0.0) {
763 PyErr_SetString(PyExc_ZeroDivisionError,
764 "0.0 cannot be raised to a "
765 "negative power");
766 return NULL;
767 }
768 /* use correct sign if iw is odd */
769 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
770 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 if (iv < 0.0) {
773 /* Whether this is an error is a mess, and bumps into libm
774 * bugs so we have to figure it out ourselves.
775 */
776 if (iw != floor(iw)) {
777 /* Negative numbers raised to fractional powers
778 * become complex.
779 */
780 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
781 }
782 /* iw is an exact integer, albeit perhaps a very large
783 * one. Replace iv by its absolute value and remember
784 * to negate the pow result if iw is odd.
785 */
786 iv = -iv;
787 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
788 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
791 /* (-1) ** large_integer also ends up here. Here's an
792 * extract from the comments for the previous
793 * implementation explaining why this special case is
794 * necessary:
795 *
796 * -1 raised to an exact integer should never be exceptional.
797 * Alas, some libms (chiefly glibc as of early 2003) return
798 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
799 * happen to be representable in a *C* integer. That's a
800 * bug.
801 */
802 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
803 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 /* Now iv and iw are finite, iw is nonzero, and iv is
806 * positive and not equal to 1.0. We finally allow
807 * the platform pow to step in and do the rest.
808 */
809 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 ix = pow(iv, iw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 Py_ADJUST_ERANGE1(ix);
812 if (negate_result)
813 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 if (errno != 0) {
816 /* We don't expect any errno value other than ERANGE, but
817 * the range of libm bugs appears unbounded.
818 */
819 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
820 PyExc_ValueError);
821 return NULL;
822 }
823 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000824}
825
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000826#undef DOUBLE_IS_ODD_INTEGER
827
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000828static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000829float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000832}
833
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000834static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000835float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000838}
839
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000840static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000841float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000844}
845
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200846/*[clinic input]
847float.is_integer
848
849Return True if the float is an integer.
850[clinic start generated code]*/
851
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000852static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200853float_is_integer_impl(PyObject *self)
854/*[clinic end generated code: output=7112acf95a4d31ea input=311810d3f777e10d]*/
Christian Heimes53876d92008-04-19 00:31:39 +0000855{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200856 double x = PyFloat_AsDouble(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 PyObject *o;
858
859 if (x == -1.0 && PyErr_Occurred())
860 return NULL;
861 if (!Py_IS_FINITE(x))
862 Py_RETURN_FALSE;
863 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 o = (floor(x) == x) ? Py_True : Py_False;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 if (errno != 0) {
866 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
867 PyExc_ValueError);
868 return NULL;
869 }
870 Py_INCREF(o);
871 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000872}
873
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200874/*[clinic input]
875float.__trunc__
876
877Return the Integral closest to x between 0 and x.
878[clinic start generated code]*/
879
Christian Heimes53876d92008-04-19 00:31:39 +0000880static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200881float___trunc___impl(PyObject *self)
882/*[clinic end generated code: output=dd3e289dd4c6b538 input=591b9ba0d650fdff]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000883{
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500884 return PyLong_FromDouble(PyFloat_AS_DOUBLE(self));
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000885}
886
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +0300887/*[clinic input]
888float.__floor__
889
890Return the floor as an Integral.
891[clinic start generated code]*/
892
893static PyObject *
894float___floor___impl(PyObject *self)
895/*[clinic end generated code: output=e0551dbaea8c01d1 input=77bb13eb12e268df]*/
896{
897 double x = PyFloat_AS_DOUBLE(self);
898 return PyLong_FromDouble(floor(x));
899}
900
901/*[clinic input]
902float.__ceil__
903
904Return the ceiling as an Integral.
905[clinic start generated code]*/
906
907static PyObject *
908float___ceil___impl(PyObject *self)
909/*[clinic end generated code: output=a2fd8858f73736f9 input=79e41ae94aa0a516]*/
910{
911 double x = PyFloat_AS_DOUBLE(self);
912 return PyLong_FromDouble(ceil(x));
913}
914
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000915/* double_round: rounds a finite double to the closest multiple of
916 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
917 ndigits <= 323). Returns a Python float, or sets a Python error and
918 returns NULL on failure (OverflowError and memory errors are possible). */
919
920#ifndef PY_NO_SHORT_FLOAT_REPR
921/* version of double_round that uses the correctly-rounded string<->double
922 conversions from Python/dtoa.c */
923
924static PyObject *
925double_round(double x, int ndigits) {
926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 double rounded;
928 Py_ssize_t buflen, mybuflen=100;
929 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
930 int decpt, sign;
931 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000932 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000935 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000937 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 if (buf == NULL) {
939 PyErr_NoMemory();
940 return NULL;
941 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
944 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
945 buflen = buf_end - buf;
946 if (buflen + 8 > mybuflen) {
947 mybuflen = buflen+8;
948 mybuf = (char *)PyMem_Malloc(mybuflen);
949 if (mybuf == NULL) {
950 PyErr_NoMemory();
951 goto exit;
952 }
953 }
954 /* copy buf to mybuf, adding exponent, sign and leading 0 */
955 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
956 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 /* and convert the resulting string back to a double */
959 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000960 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000962 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 if (errno == ERANGE && fabs(rounded) >= 1.)
964 PyErr_SetString(PyExc_OverflowError,
965 "rounded value too large to represent");
966 else
967 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 /* done computing value; now clean up */
970 if (mybuf != shortbuf)
971 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000972 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 _Py_dg_freedtoa(buf);
974 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000975}
976
977#else /* PY_NO_SHORT_FLOAT_REPR */
978
979/* fallback version, to be used when correctly rounded binary<->decimal
980 conversions aren't available */
981
982static PyObject *
983double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 double pow1, pow2, y, z;
985 if (ndigits >= 0) {
986 if (ndigits > 22) {
987 /* pow1 and pow2 are each safe from overflow, but
988 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
989 pow1 = pow(10.0, (double)(ndigits-22));
990 pow2 = 1e22;
991 }
992 else {
993 pow1 = pow(10.0, (double)ndigits);
994 pow2 = 1.0;
995 }
996 y = (x*pow1)*pow2;
997 /* if y overflows, then rounded value is exactly x */
998 if (!Py_IS_FINITE(y))
999 return PyFloat_FromDouble(x);
1000 }
1001 else {
1002 pow1 = pow(10.0, (double)-ndigits);
1003 pow2 = 1.0; /* unused; silences a gcc compiler warning */
1004 y = x / pow1;
1005 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 z = round(y);
1008 if (fabs(y-z) == 0.5)
1009 /* halfway between two integers; use round-half-even */
1010 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 if (ndigits >= 0)
1013 z = (z / pow2) / pow1;
1014 else
1015 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 /* if computation resulted in overflow, raise OverflowError */
1018 if (!Py_IS_FINITE(z)) {
1019 PyErr_SetString(PyExc_OverflowError,
1020 "overflow occurred during round");
1021 return NULL;
1022 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001025}
1026
1027#endif /* PY_NO_SHORT_FLOAT_REPR */
1028
1029/* round a Python float v to the closest multiple of 10**-ndigits */
1030
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001031/*[clinic input]
1032float.__round__
1033
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001034 ndigits as o_ndigits: object = None
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001035 /
1036
1037Return the Integral closest to x, rounding half toward even.
1038
1039When an argument is passed, work like built-in round(x, ndigits).
1040[clinic start generated code]*/
1041
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001042static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001043float___round___impl(PyObject *self, PyObject *o_ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001044/*[clinic end generated code: output=374c36aaa0f13980 input=fc0fe25924fbc9ed]*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 double x, rounded;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001048
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001049 x = PyFloat_AsDouble(self);
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001050 if (o_ndigits == Py_None) {
Steve Dowercb39d1f2015-04-15 16:10:59 -04001051 /* single-argument round or with None ndigits:
1052 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 rounded = round(x);
1054 if (fabs(x-rounded) == 0.5)
1055 /* halfway case: round to even */
1056 rounded = 2.0*round(x/2.0);
1057 return PyLong_FromDouble(rounded);
1058 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 /* interpret second argument as a Py_ssize_t; clips on overflow */
1061 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1062 if (ndigits == -1 && PyErr_Occurred())
1063 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 /* nans and infinities round to themselves */
1066 if (!Py_IS_FINITE(x))
1067 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1070 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1071 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001072#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1073#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 if (ndigits > NDIGITS_MAX)
1075 /* return x */
1076 return PyFloat_FromDouble(x);
1077 else if (ndigits < NDIGITS_MIN)
1078 /* return 0.0, but with sign of x */
1079 return PyFloat_FromDouble(0.0*x);
1080 else
1081 /* finite x, and ndigits is not unreasonably large */
1082 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001083#undef NDIGITS_MAX
1084#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001085}
1086
1087static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001088float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 if (PyFloat_CheckExact(v))
1091 Py_INCREF(v);
1092 else
1093 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1094 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001095}
1096
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001097/*[clinic input]
1098float.conjugate
1099
1100Return self, the complex conjugate of any float.
1101[clinic start generated code]*/
1102
1103static PyObject *
1104float_conjugate_impl(PyObject *self)
1105/*[clinic end generated code: output=8ca292c2479194af input=82ba6f37a9ff91dd]*/
1106{
1107 return float_float(self);
1108}
1109
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001110/* turn ASCII hex characters into integer values and vice versa */
1111
1112static char
1113char_from_hex(int x)
1114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001116 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001117}
1118
1119static int
1120hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 int x;
1122 switch(c) {
1123 case '0':
1124 x = 0;
1125 break;
1126 case '1':
1127 x = 1;
1128 break;
1129 case '2':
1130 x = 2;
1131 break;
1132 case '3':
1133 x = 3;
1134 break;
1135 case '4':
1136 x = 4;
1137 break;
1138 case '5':
1139 x = 5;
1140 break;
1141 case '6':
1142 x = 6;
1143 break;
1144 case '7':
1145 x = 7;
1146 break;
1147 case '8':
1148 x = 8;
1149 break;
1150 case '9':
1151 x = 9;
1152 break;
1153 case 'a':
1154 case 'A':
1155 x = 10;
1156 break;
1157 case 'b':
1158 case 'B':
1159 x = 11;
1160 break;
1161 case 'c':
1162 case 'C':
1163 x = 12;
1164 break;
1165 case 'd':
1166 case 'D':
1167 x = 13;
1168 break;
1169 case 'e':
1170 case 'E':
1171 x = 14;
1172 break;
1173 case 'f':
1174 case 'F':
1175 x = 15;
1176 break;
1177 default:
1178 x = -1;
1179 break;
1180 }
1181 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001182}
1183
1184/* convert a float to a hexadecimal string */
1185
1186/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1187 of the form 4k+1. */
1188#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1189
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001190/*[clinic input]
1191float.hex
1192
1193Return a hexadecimal representation of a floating-point number.
1194
1195>>> (-0.1).hex()
1196'-0x1.999999999999ap-4'
1197>>> 3.14159.hex()
1198'0x1.921f9f01b866ep+1'
1199[clinic start generated code]*/
1200
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001201static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001202float_hex_impl(PyObject *self)
1203/*[clinic end generated code: output=0ebc9836e4d302d4 input=bec1271a33d47e67]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 double x, m;
1206 int e, shift, i, si, esign;
1207 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1208 trailing NUL byte. */
1209 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001210
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001211 CONVERT_TO_DOUBLE(self, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001214 return float_repr((PyFloatObject *)self);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001217 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 return PyUnicode_FromString("-0x0.0p+0");
1219 else
1220 return PyUnicode_FromString("0x0.0p+0");
1221 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001224 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 m = ldexp(m, shift);
1226 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 si = 0;
1229 s[si] = char_from_hex((int)m);
1230 si++;
1231 m -= (int)m;
1232 s[si] = '.';
1233 si++;
1234 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1235 m *= 16.0;
1236 s[si] = char_from_hex((int)m);
1237 si++;
1238 m -= (int)m;
1239 }
1240 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 if (e < 0) {
1243 esign = (int)'-';
1244 e = -e;
1245 }
1246 else
1247 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 if (x < 0.0)
1250 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1251 else
1252 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001253}
1254
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001255/* Convert a hexadecimal string to a float. */
1256
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001257/*[clinic input]
1258@classmethod
1259float.fromhex
1260
1261 string: object
1262 /
1263
1264Create a floating-point number from a hexadecimal string.
1265
1266>>> float.fromhex('0x1.ffffp10')
12672047.984375
1268>>> float.fromhex('-0x1p-1074')
1269-5e-324
1270[clinic start generated code]*/
1271
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001272static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001273float_fromhex(PyTypeObject *type, PyObject *string)
1274/*[clinic end generated code: output=46c0274d22b78e82 input=0407bebd354bca89]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001275{
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001276 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 double x;
1278 long exp, top_exp, lsb, key_digit;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001279 const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 int half_eps, digit, round_up, negate=0;
1281 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 /*
1284 * For the sake of simplicity and correctness, we impose an artificial
1285 * limit on ndigits, the total number of hex digits in the coefficient
1286 * The limit is chosen to ensure that, writing exp for the exponent,
1287 *
1288 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1289 * guaranteed to overflow (provided it's nonzero)
1290 *
1291 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1292 * guaranteed to underflow to 0.
1293 *
1294 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1295 * overflow in the calculation of exp and top_exp below.
1296 *
1297 * More specifically, ndigits is assumed to satisfy the following
1298 * inequalities:
1299 *
1300 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1301 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1302 *
1303 * If either of these inequalities is not satisfied, a ValueError is
1304 * raised. Otherwise, write x for the value of the hex string, and
1305 * assume x is nonzero. Then
1306 *
1307 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1308 *
1309 * Now if exp > LONG_MAX/2 then:
1310 *
1311 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1312 * = DBL_MAX_EXP
1313 *
1314 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1315 * double, so overflows. If exp < LONG_MIN/2, then
1316 *
1317 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1318 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1319 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1320 *
1321 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1322 * when converted to a C double.
1323 *
1324 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1325 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1326 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001327
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001328 s = PyUnicode_AsUTF8AndSize(string, &length);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 if (s == NULL)
1330 return NULL;
1331 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 /********************
1334 * Parse the string *
1335 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 /* leading whitespace */
1338 while (Py_ISSPACE(*s))
1339 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 /* infinities and nans */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001342 x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 if (coeff_end != s) {
1344 s = coeff_end;
1345 goto finished;
1346 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 /* optional sign */
1349 if (*s == '-') {
1350 s++;
1351 negate = 1;
1352 }
1353 else if (*s == '+')
1354 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 /* [0x] */
1357 s_store = s;
1358 if (*s == '0') {
1359 s++;
1360 if (*s == 'x' || *s == 'X')
1361 s++;
1362 else
1363 s = s_store;
1364 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 /* coefficient: <integer> [. <fraction>] */
1367 coeff_start = s;
1368 while (hex_from_char(*s) >= 0)
1369 s++;
1370 s_store = s;
1371 if (*s == '.') {
1372 s++;
1373 while (hex_from_char(*s) >= 0)
1374 s++;
1375 coeff_end = s-1;
1376 }
1377 else
1378 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 /* ndigits = total # of hex digits; fdigits = # after point */
1381 ndigits = coeff_end - coeff_start;
1382 fdigits = coeff_end - s_store;
1383 if (ndigits == 0)
1384 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001385 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1386 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 /* [p <exponent>] */
1390 if (*s == 'p' || *s == 'P') {
1391 s++;
1392 exp_start = s;
1393 if (*s == '-' || *s == '+')
1394 s++;
1395 if (!('0' <= *s && *s <= '9'))
1396 goto parse_error;
1397 s++;
1398 while ('0' <= *s && *s <= '9')
1399 s++;
1400 exp = strtol(exp_start, NULL, 10);
1401 }
1402 else
1403 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001404
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001405/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1407 coeff_end-(j) : \
1408 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 /*******************************************
1411 * Compute rounded value of the hex string *
1412 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 /* Discard leading zeros, and catch extreme overflow and underflow */
1415 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1416 ndigits--;
1417 if (ndigits == 0 || exp < LONG_MIN/2) {
1418 x = 0.0;
1419 goto finished;
1420 }
1421 if (exp > LONG_MAX/2)
1422 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 /* Adjust exponent for fractional part. */
1425 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1428 top_exp = exp + 4*((long)ndigits - 1);
1429 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1430 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 /* catch almost all nonextreme cases of overflow and underflow here */
1433 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1434 x = 0.0;
1435 goto finished;
1436 }
1437 if (top_exp > DBL_MAX_EXP)
1438 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 /* lsb = exponent of least significant bit of the *rounded* value.
1441 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001442 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 x = 0.0;
1445 if (exp >= lsb) {
1446 /* no rounding required */
1447 for (i = ndigits-1; i >= 0; i--)
1448 x = 16.0*x + HEX_DIGIT(i);
1449 x = ldexp(x, (int)(exp));
1450 goto finished;
1451 }
1452 /* rounding required. key_digit is the index of the hex digit
1453 containing the first bit to be rounded away. */
1454 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1455 key_digit = (lsb - exp - 1) / 4;
1456 for (i = ndigits-1; i > key_digit; i--)
1457 x = 16.0*x + HEX_DIGIT(i);
1458 digit = HEX_DIGIT(key_digit);
1459 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1462 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1463 if ((digit & half_eps) != 0) {
1464 round_up = 0;
1465 if ((digit & (3*half_eps-1)) != 0 ||
1466 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1467 round_up = 1;
1468 else
1469 for (i = key_digit-1; i >= 0; i--)
1470 if (HEX_DIGIT(i) != 0) {
1471 round_up = 1;
1472 break;
1473 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001474 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 x += 2*half_eps;
1476 if (top_exp == DBL_MAX_EXP &&
1477 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1478 /* overflow corner case: pre-rounded value <
1479 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1480 goto overflow_error;
1481 }
1482 }
1483 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001484
1485 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 /* optional trailing whitespace leading to the end of the string */
1487 while (Py_ISSPACE(*s))
1488 s++;
1489 if (s != s_end)
1490 goto parse_error;
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001491 result = PyFloat_FromDouble(negate ? -x : x);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001492 if (type != &PyFloat_Type && result != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001493 Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001494 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001496
1497 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 PyErr_SetString(PyExc_OverflowError,
1499 "hexadecimal value too large to represent as a float");
1500 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001501
1502 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 PyErr_SetString(PyExc_ValueError,
1504 "invalid hexadecimal floating-point string");
1505 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001506
1507 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 PyErr_SetString(PyExc_ValueError,
1509 "hexadecimal string too long to convert");
1510 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001511}
1512
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001513/*[clinic input]
1514float.as_integer_ratio
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001515
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001516Return integer ratio.
1517
1518Return a pair of integers, whose ratio is exactly equal to the original float
1519and with a positive denominator.
1520
1521Raise OverflowError on infinities and a ValueError on NaNs.
1522
1523>>> (10.0).as_integer_ratio()
1524(10, 1)
1525>>> (0.0).as_integer_ratio()
1526(0, 1)
1527>>> (-.25).as_integer_ratio()
1528(-1, 4)
1529[clinic start generated code]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001530
Christian Heimes26855632008-01-27 23:50:43 +00001531static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001532float_as_integer_ratio_impl(PyObject *self)
1533/*[clinic end generated code: output=65f25f0d8d30a712 input=e21d08b4630c2e44]*/
Christian Heimes26855632008-01-27 23:50:43 +00001534{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001535 double self_double;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 double float_part;
1537 int exponent;
1538 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 PyObject *py_exponent = NULL;
1541 PyObject *numerator = NULL;
1542 PyObject *denominator = NULL;
1543 PyObject *result_pair = NULL;
1544 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001545
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001546 CONVERT_TO_DOUBLE(self, self_double);
Christian Heimes26855632008-01-27 23:50:43 +00001547
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001548 if (Py_IS_INFINITY(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001549 PyErr_SetString(PyExc_OverflowError,
1550 "cannot convert Infinity to integer ratio");
1551 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001553 if (Py_IS_NAN(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001554 PyErr_SetString(PyExc_ValueError,
1555 "cannot convert NaN to integer ratio");
1556 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 }
Christian Heimes26855632008-01-27 23:50:43 +00001558
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001559 float_part = frexp(self_double, &exponent); /* self_double == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1562 float_part *= 2.0;
1563 exponent--;
1564 }
1565 /* self == float_part * 2**exponent exactly and float_part is integral.
1566 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1567 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 numerator = PyLong_FromDouble(float_part);
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001570 if (numerator == NULL)
1571 goto error;
1572 denominator = PyLong_FromLong(1);
1573 if (denominator == NULL)
1574 goto error;
1575 py_exponent = PyLong_FromLong(Py_ABS(exponent));
1576 if (py_exponent == NULL)
1577 goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 /* fold in 2**exponent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 if (exponent > 0) {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001581 Py_SETREF(numerator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001582 long_methods->nb_lshift(numerator, py_exponent));
1583 if (numerator == NULL)
1584 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 }
1586 else {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001587 Py_SETREF(denominator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001588 long_methods->nb_lshift(denominator, py_exponent));
1589 if (denominator == NULL)
1590 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 }
1592
1593 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001594
Christian Heimes26855632008-01-27 23:50:43 +00001595error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 Py_XDECREF(py_exponent);
1597 Py_XDECREF(denominator);
1598 Py_XDECREF(numerator);
1599 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001600}
1601
Jeremy Hylton938ace62002-07-17 16:30:39 +00001602static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001603float_subtype_new(PyTypeObject *type, PyObject *x);
1604
1605/*[clinic input]
1606@classmethod
1607float.__new__ as float_new
Serhiy Storchakaba85d692017-03-30 09:09:41 +03001608 x: object(c_default="_PyLong_Zero") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001609 /
1610
1611Convert a string or number to a floating point number, if possible.
1612[clinic start generated code]*/
Guido van Rossumbef14172001-08-29 15:47:46 +00001613
Tim Peters6d6c1a32001-08-02 04:15:00 +00001614static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001615float_new_impl(PyTypeObject *type, PyObject *x)
Serhiy Storchakabae68812017-04-05 12:00:42 +03001616/*[clinic end generated code: output=ccf1e8dc460ba6ba input=540ee77c204ff87a]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00001617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 if (type != &PyFloat_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001619 return float_subtype_new(type, x); /* Wimp out */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 /* If it's a string, but not a string subclass, use
1621 PyFloat_FromString. */
1622 if (PyUnicode_CheckExact(x))
1623 return PyFloat_FromString(x);
1624 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001625}
1626
Guido van Rossumbef14172001-08-29 15:47:46 +00001627/* Wimpy, slow approach to tp_new calls for subtypes of float:
1628 first create a regular float from whatever arguments we got,
1629 then allocate a subtype instance and initialize its ob_fval
1630 from the regular float. The regular float is then thrown away.
1631*/
1632static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001633float_subtype_new(PyTypeObject *type, PyObject *x)
Guido van Rossumbef14172001-08-29 15:47:46 +00001634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 assert(PyType_IsSubtype(type, &PyFloat_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001638 tmp = float_new_impl(&PyFloat_Type, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 if (tmp == NULL)
1640 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001641 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 newobj = type->tp_alloc(type, 0);
1643 if (newobj == NULL) {
1644 Py_DECREF(tmp);
1645 return NULL;
1646 }
1647 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1648 Py_DECREF(tmp);
1649 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001650}
1651
Dennis Sweeneye8acc352020-09-28 20:55:52 -04001652static PyObject *
1653float_vectorcall(PyObject *type, PyObject * const*args,
1654 size_t nargsf, PyObject *kwnames)
1655{
1656 if (!_PyArg_NoKwnames("float", kwnames)) {
1657 return NULL;
1658 }
1659
1660 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
1661 if (!_PyArg_CheckPositional("float", nargs, 0, 1)) {
1662 return NULL;
1663 }
1664
1665 PyObject *x = nargs >= 1 ? args[0] : _PyLong_Zero;
1666 return float_new_impl((PyTypeObject *)type, x);
1667}
1668
1669
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001670/*[clinic input]
1671float.__getnewargs__
1672[clinic start generated code]*/
1673
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001674static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001675float___getnewargs___impl(PyObject *self)
1676/*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001677{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001678 return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001679}
1680
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001681/* this is for the benefit of the pack/unpack routines below */
1682
1683typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001685} float_format_type;
1686
1687static float_format_type double_format, float_format;
1688static float_format_type detected_double_format, detected_float_format;
1689
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001690/*[clinic input]
1691@classmethod
1692float.__getformat__
1693
1694 typestr: str
1695 Must be 'double' or 'float'.
1696 /
1697
1698You probably don't want to use this function.
1699
1700It exists mainly to be used in Python's test suite.
1701
1702This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
1703little-endian' best describes the format of floating point numbers used by the
1704C type named by typestr.
1705[clinic start generated code]*/
1706
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001707static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001708float___getformat___impl(PyTypeObject *type, const char *typestr)
1709/*[clinic end generated code: output=2bfb987228cc9628 input=d5a52600f835ad67]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001712
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001713 if (strcmp(typestr, "double") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 r = double_format;
1715 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001716 else if (strcmp(typestr, "float") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 r = float_format;
1718 }
1719 else {
1720 PyErr_SetString(PyExc_ValueError,
1721 "__getformat__() argument 1 must be "
1722 "'double' or 'float'");
1723 return NULL;
1724 }
1725
1726 switch (r) {
1727 case unknown_format:
1728 return PyUnicode_FromString("unknown");
1729 case ieee_little_endian_format:
1730 return PyUnicode_FromString("IEEE, little-endian");
1731 case ieee_big_endian_format:
1732 return PyUnicode_FromString("IEEE, big-endian");
1733 default:
Victor Stinner04394df2019-11-18 17:39:48 +01001734 PyErr_SetString(PyExc_RuntimeError,
1735 "insane float_format or double_format");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 return NULL;
1737 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001738}
1739
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001740/*[clinic input]
1741@classmethod
1742float.__set_format__
1743
1744 typestr: str
1745 Must be 'double' or 'float'.
1746 fmt: str
1747 Must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian',
1748 and in addition can only be one of the latter two if it appears to
1749 match the underlying C reality.
1750 /
1751
1752You probably don't want to use this function.
1753
1754It exists mainly to be used in Python's test suite.
1755
1756Override the automatic determination of C-level floating point type.
1757This affects how floats are converted to and from binary strings.
1758[clinic start generated code]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001759
1760static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001761float___set_format___impl(PyTypeObject *type, const char *typestr,
1762 const char *fmt)
1763/*[clinic end generated code: output=504460f5dc85acbd input=5306fa2b81a997e4]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 float_format_type f;
1766 float_format_type detected;
1767 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 if (strcmp(typestr, "double") == 0) {
1770 p = &double_format;
1771 detected = detected_double_format;
1772 }
1773 else if (strcmp(typestr, "float") == 0) {
1774 p = &float_format;
1775 detected = detected_float_format;
1776 }
1777 else {
1778 PyErr_SetString(PyExc_ValueError,
1779 "__setformat__() argument 1 must "
1780 "be 'double' or 'float'");
1781 return NULL;
1782 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001783
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001784 if (strcmp(fmt, "unknown") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 f = unknown_format;
1786 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001787 else if (strcmp(fmt, "IEEE, little-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 f = ieee_little_endian_format;
1789 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001790 else if (strcmp(fmt, "IEEE, big-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 f = ieee_big_endian_format;
1792 }
1793 else {
1794 PyErr_SetString(PyExc_ValueError,
1795 "__setformat__() argument 2 must be "
1796 "'unknown', 'IEEE, little-endian' or "
1797 "'IEEE, big-endian'");
1798 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 if (f != unknown_format && f != detected) {
1803 PyErr_Format(PyExc_ValueError,
1804 "can only set %s format to 'unknown' or the "
1805 "detected platform value", typestr);
1806 return NULL;
1807 }
1808
1809 *p = f;
1810 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001811}
1812
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001813static PyObject *
1814float_getreal(PyObject *v, void *closure)
1815{
1816 return float_float(v);
1817}
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001818
Guido van Rossumb43daf72007-08-01 18:08:08 +00001819static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001820float_getimag(PyObject *v, void *closure)
Guido van Rossumb43daf72007-08-01 18:08:08 +00001821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001823}
1824
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001825/*[clinic input]
1826float.__format__
1827
1828 format_spec: unicode
1829 /
1830
1831Formats the float according to format_spec.
1832[clinic start generated code]*/
1833
Eric Smith8c663262007-08-25 02:26:07 +00001834static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001835float___format___impl(PyObject *self, PyObject *format_spec)
1836/*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/
Eric Smith8c663262007-08-25 02:26:07 +00001837{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001838 _PyUnicodeWriter writer;
1839 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001840
Victor Stinner8f674cc2013-04-17 23:02:17 +02001841 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001842 ret = _PyFloat_FormatAdvancedWriter(
1843 &writer,
1844 self,
1845 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1846 if (ret == -1) {
1847 _PyUnicodeWriter_Dealloc(&writer);
1848 return NULL;
1849 }
1850 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001851}
1852
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001853static PyMethodDef float_methods[] = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001854 FLOAT_CONJUGATE_METHODDEF
1855 FLOAT___TRUNC___METHODDEF
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +03001856 FLOAT___FLOOR___METHODDEF
1857 FLOAT___CEIL___METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001858 FLOAT___ROUND___METHODDEF
1859 FLOAT_AS_INTEGER_RATIO_METHODDEF
1860 FLOAT_FROMHEX_METHODDEF
1861 FLOAT_HEX_METHODDEF
1862 FLOAT_IS_INTEGER_METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001863 FLOAT___GETNEWARGS___METHODDEF
1864 FLOAT___GETFORMAT___METHODDEF
1865 FLOAT___SET_FORMAT___METHODDEF
1866 FLOAT___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001868};
1869
Guido van Rossumb43daf72007-08-01 18:08:08 +00001870static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 {"real",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001872 float_getreal, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001873 "the real part of a complex number",
1874 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 {"imag",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001876 float_getimag, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001877 "the imaginary part of a complex number",
1878 NULL},
1879 {NULL} /* Sentinel */
1880};
1881
Tim Peters6d6c1a32001-08-02 04:15:00 +00001882
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001883static PyNumberMethods float_as_number = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001884 float_add, /* nb_add */
1885 float_sub, /* nb_subtract */
1886 float_mul, /* nb_multiply */
1887 float_rem, /* nb_remainder */
1888 float_divmod, /* nb_divmod */
1889 float_pow, /* nb_power */
1890 (unaryfunc)float_neg, /* nb_negative */
1891 float_float, /* nb_positive */
1892 (unaryfunc)float_abs, /* nb_absolute */
1893 (inquiry)float_bool, /* nb_bool */
1894 0, /* nb_invert */
1895 0, /* nb_lshift */
1896 0, /* nb_rshift */
1897 0, /* nb_and */
1898 0, /* nb_xor */
1899 0, /* nb_or */
1900 float___trunc___impl, /* nb_int */
1901 0, /* nb_reserved */
1902 float_float, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 0, /* nb_inplace_add */
1904 0, /* nb_inplace_subtract */
1905 0, /* nb_inplace_multiply */
1906 0, /* nb_inplace_remainder */
1907 0, /* nb_inplace_power */
1908 0, /* nb_inplace_lshift */
1909 0, /* nb_inplace_rshift */
1910 0, /* nb_inplace_and */
1911 0, /* nb_inplace_xor */
1912 0, /* nb_inplace_or */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001913 float_floor_div, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 float_div, /* nb_true_divide */
1915 0, /* nb_inplace_floor_divide */
1916 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001917};
1918
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001919PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1921 "float",
1922 sizeof(PyFloatObject),
1923 0,
1924 (destructor)float_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001925 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 0, /* tp_getattr */
1927 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001928 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 (reprfunc)float_repr, /* tp_repr */
1930 &float_as_number, /* tp_as_number */
1931 0, /* tp_as_sequence */
1932 0, /* tp_as_mapping */
1933 (hashfunc)float_hash, /* tp_hash */
1934 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001935 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 PyObject_GenericGetAttr, /* tp_getattro */
1937 0, /* tp_setattro */
1938 0, /* tp_as_buffer */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001939 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001940 float_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 0, /* tp_traverse */
1942 0, /* tp_clear */
1943 float_richcompare, /* tp_richcompare */
1944 0, /* tp_weaklistoffset */
1945 0, /* tp_iter */
1946 0, /* tp_iternext */
1947 float_methods, /* tp_methods */
1948 0, /* tp_members */
1949 float_getset, /* tp_getset */
1950 0, /* tp_base */
1951 0, /* tp_dict */
1952 0, /* tp_descr_get */
1953 0, /* tp_descr_set */
1954 0, /* tp_dictoffset */
1955 0, /* tp_init */
1956 0, /* tp_alloc */
1957 float_new, /* tp_new */
Dennis Sweeneye8acc352020-09-28 20:55:52 -04001958 .tp_vectorcall = (vectorcallfunc)float_vectorcall,
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001959};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001960
Victor Stinner1c8f0592013-07-22 22:24:54 +02001961int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001962_PyFloat_Init(void)
1963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 /* We attempt to determine if this machine is using IEEE
1965 floating point formats by peering at the bits of some
1966 carefully chosen values. If it looks like we are on an
1967 IEEE platform, the float packing/unpacking routines can
1968 just copy bits, if not they resort to arithmetic & shifts
1969 and masks. The shifts & masks approach works on all finite
1970 values, but what happens to infinities, NaNs and signed
1971 zeroes on packing is an accident, and attempting to unpack
1972 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 Note that if we're on some whacked-out platform which uses
1975 IEEE formats but isn't strictly little-endian or big-
1976 endian, we will fall back to the portable shifts & masks
1977 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001978
1979#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 {
1981 double x = 9006104071832581.0;
1982 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1983 detected_double_format = ieee_big_endian_format;
1984 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1985 detected_double_format = ieee_little_endian_format;
1986 else
1987 detected_double_format = unknown_format;
1988 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001989#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001991#endif
1992
1993#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 {
1995 float y = 16711938.0;
1996 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1997 detected_float_format = ieee_big_endian_format;
1998 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1999 detected_float_format = ieee_little_endian_format;
2000 else
2001 detected_float_format = unknown_format;
2002 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002003#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002005#endif
2006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 double_format = detected_double_format;
2008 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002011 if (FloatInfoType.tp_name == NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01002012 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02002013 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01002014 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002015 }
2016 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002017}
2018
Victor Stinnerae00a5a2020-04-29 02:29:20 +02002019void
Victor Stinner2ba59372020-06-05 00:50:05 +02002020_PyFloat_ClearFreeList(PyThreadState *tstate)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002021{
Victor Stinner2ba59372020-06-05 00:50:05 +02002022 struct _Py_float_state *state = &tstate->interp->float_state;
Victor Stinnerbcb19832020-06-08 02:14:47 +02002023 PyFloatObject *f = state->free_list;
2024 while (f != NULL) {
2025 PyFloatObject *next = (PyFloatObject*) Py_TYPE(f);
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002026 PyObject_FREE(f);
Victor Stinnerbcb19832020-06-08 02:14:47 +02002027 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 }
Victor Stinner2ba59372020-06-05 00:50:05 +02002029 state->free_list = NULL;
2030 state->numfree = 0;
Christian Heimes15ebc882008-02-04 18:48:49 +00002031}
2032
2033void
Victor Stinner2ba59372020-06-05 00:50:05 +02002034_PyFloat_Fini(PyThreadState *tstate)
Christian Heimes15ebc882008-02-04 18:48:49 +00002035{
Victor Stinner2ba59372020-06-05 00:50:05 +02002036 _PyFloat_ClearFreeList(tstate);
Victor Stinnerbcb19832020-06-08 02:14:47 +02002037#ifdef Py_DEBUG
2038 struct _Py_float_state *state = &tstate->interp->float_state;
2039 state->numfree = -1;
2040#endif
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002041}
Tim Peters9905b942003-03-20 20:53:32 +00002042
David Malcolm49526f42012-06-22 14:55:41 -04002043/* Print summary info about the state of the optimized allocator */
2044void
2045_PyFloat_DebugMallocStats(FILE *out)
2046{
Victor Stinner522691c2020-06-23 16:40:40 +02002047 struct _Py_float_state *state = get_float_state();
David Malcolm49526f42012-06-22 14:55:41 -04002048 _PyDebugAllocatorStats(out,
2049 "free PyFloatObject",
Victor Stinner2ba59372020-06-05 00:50:05 +02002050 state->numfree, sizeof(PyFloatObject));
David Malcolm49526f42012-06-22 14:55:41 -04002051}
2052
2053
Tim Peters9905b942003-03-20 20:53:32 +00002054/*----------------------------------------------------------------------------
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002055 * _PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h.
2056 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
2057 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
2058 * We use:
2059 * bits = (unsigned short)f; Note the truncation
2060 * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
2061 * bits++;
2062 * }
Tim Peters9905b942003-03-20 20:53:32 +00002063 */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002064
2065int
2066_PyFloat_Pack2(double x, unsigned char *p, int le)
2067{
2068 unsigned char sign;
2069 int e;
2070 double f;
2071 unsigned short bits;
2072 int incr = 1;
2073
2074 if (x == 0.0) {
2075 sign = (copysign(1.0, x) == -1.0);
2076 e = 0;
2077 bits = 0;
2078 }
2079 else if (Py_IS_INFINITY(x)) {
2080 sign = (x < 0.0);
2081 e = 0x1f;
2082 bits = 0;
2083 }
2084 else if (Py_IS_NAN(x)) {
2085 /* There are 2046 distinct half-precision NaNs (1022 signaling and
2086 1024 quiet), but there are only two quiet NaNs that don't arise by
2087 quieting a signaling NaN; we get those by setting the topmost bit
2088 of the fraction field and clearing all other fraction bits. We
2089 choose the one with the appropriate sign. */
2090 sign = (copysign(1.0, x) == -1.0);
2091 e = 0x1f;
2092 bits = 512;
2093 }
2094 else {
2095 sign = (x < 0.0);
2096 if (sign) {
2097 x = -x;
2098 }
2099
2100 f = frexp(x, &e);
2101 if (f < 0.5 || f >= 1.0) {
2102 PyErr_SetString(PyExc_SystemError,
2103 "frexp() result out of range");
2104 return -1;
2105 }
2106
2107 /* Normalize f to be in the range [1.0, 2.0) */
2108 f *= 2.0;
2109 e--;
2110
2111 if (e >= 16) {
2112 goto Overflow;
2113 }
2114 else if (e < -25) {
2115 /* |x| < 2**-25. Underflow to zero. */
2116 f = 0.0;
2117 e = 0;
2118 }
2119 else if (e < -14) {
2120 /* |x| < 2**-14. Gradual underflow */
2121 f = ldexp(f, 14 + e);
2122 e = 0;
2123 }
2124 else /* if (!(e == 0 && f == 0.0)) */ {
2125 e += 15;
2126 f -= 1.0; /* Get rid of leading 1 */
2127 }
2128
2129 f *= 1024.0; /* 2**10 */
2130 /* Round to even */
2131 bits = (unsigned short)f; /* Note the truncation */
2132 assert(bits < 1024);
2133 assert(e < 31);
2134 if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2135 ++bits;
2136 if (bits == 1024) {
2137 /* The carry propagated out of a string of 10 1 bits. */
2138 bits = 0;
2139 ++e;
2140 if (e == 31)
2141 goto Overflow;
2142 }
2143 }
2144 }
2145
2146 bits |= (e << 10) | (sign << 15);
2147
2148 /* Write out result. */
2149 if (le) {
2150 p += 1;
2151 incr = -1;
2152 }
2153
2154 /* First byte */
2155 *p = (unsigned char)((bits >> 8) & 0xFF);
2156 p += incr;
2157
2158 /* Second byte */
2159 *p = (unsigned char)(bits & 0xFF);
2160
2161 return 0;
2162
2163 Overflow:
2164 PyErr_SetString(PyExc_OverflowError,
2165 "float too large to pack with e format");
2166 return -1;
2167}
2168
Tim Peters9905b942003-03-20 20:53:32 +00002169int
2170_PyFloat_Pack4(double x, unsigned char *p, int le)
2171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 if (float_format == unknown_format) {
2173 unsigned char sign;
2174 int e;
2175 double f;
2176 unsigned int fbits;
2177 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 if (le) {
2180 p += 3;
2181 incr = -1;
2182 }
Tim Peters9905b942003-03-20 20:53:32 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 if (x < 0) {
2185 sign = 1;
2186 x = -x;
2187 }
2188 else
2189 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 /* Normalize f to be in the range [1.0, 2.0) */
2194 if (0.5 <= f && f < 1.0) {
2195 f *= 2.0;
2196 e--;
2197 }
2198 else if (f == 0.0)
2199 e = 0;
2200 else {
2201 PyErr_SetString(PyExc_SystemError,
2202 "frexp() result out of range");
2203 return -1;
2204 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 if (e >= 128)
2207 goto Overflow;
2208 else if (e < -126) {
2209 /* Gradual underflow */
2210 f = ldexp(f, 126 + e);
2211 e = 0;
2212 }
2213 else if (!(e == 0 && f == 0.0)) {
2214 e += 127;
2215 f -= 1.0; /* Get rid of leading 1 */
2216 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 f *= 8388608.0; /* 2**23 */
2219 fbits = (unsigned int)(f + 0.5); /* Round */
2220 assert(fbits <= 8388608);
2221 if (fbits >> 23) {
2222 /* The carry propagated out of a string of 23 1 bits. */
2223 fbits = 0;
2224 ++e;
2225 if (e >= 255)
2226 goto Overflow;
2227 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 /* First byte */
2230 *p = (sign << 7) | (e >> 1);
2231 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 /* Second byte */
2234 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2235 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 /* Third byte */
2238 *p = (fbits >> 8) & 0xFF;
2239 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 /* Fourth byte */
2242 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 /* Done */
2245 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 }
2248 else {
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002249 float y = (float)x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002251
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002252 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002254
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002255 unsigned char s[sizeof(float)];
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002256 memcpy(s, &y, sizeof(float));
2257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 if ((float_format == ieee_little_endian_format && !le)
2259 || (float_format == ieee_big_endian_format && le)) {
2260 p += 3;
2261 incr = -1;
2262 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 for (i = 0; i < 4; i++) {
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002265 *p = s[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 p += incr;
2267 }
2268 return 0;
2269 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002270 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 PyErr_SetString(PyExc_OverflowError,
2272 "float too large to pack with f format");
2273 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002274}
2275
2276int
2277_PyFloat_Pack8(double x, unsigned char *p, int le)
2278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 if (double_format == unknown_format) {
2280 unsigned char sign;
2281 int e;
2282 double f;
2283 unsigned int fhi, flo;
2284 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 if (le) {
2287 p += 7;
2288 incr = -1;
2289 }
Tim Peters9905b942003-03-20 20:53:32 +00002290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 if (x < 0) {
2292 sign = 1;
2293 x = -x;
2294 }
2295 else
2296 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 /* Normalize f to be in the range [1.0, 2.0) */
2301 if (0.5 <= f && f < 1.0) {
2302 f *= 2.0;
2303 e--;
2304 }
2305 else if (f == 0.0)
2306 e = 0;
2307 else {
2308 PyErr_SetString(PyExc_SystemError,
2309 "frexp() result out of range");
2310 return -1;
2311 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 if (e >= 1024)
2314 goto Overflow;
2315 else if (e < -1022) {
2316 /* Gradual underflow */
2317 f = ldexp(f, 1022 + e);
2318 e = 0;
2319 }
2320 else if (!(e == 0 && f == 0.0)) {
2321 e += 1023;
2322 f -= 1.0; /* Get rid of leading 1 */
2323 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2326 f *= 268435456.0; /* 2**28 */
2327 fhi = (unsigned int)f; /* Truncate */
2328 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 f -= (double)fhi;
2331 f *= 16777216.0; /* 2**24 */
2332 flo = (unsigned int)(f + 0.5); /* Round */
2333 assert(flo <= 16777216);
2334 if (flo >> 24) {
2335 /* The carry propagated out of a string of 24 1 bits. */
2336 flo = 0;
2337 ++fhi;
2338 if (fhi >> 28) {
2339 /* And it also progagated out of the next 28 bits. */
2340 fhi = 0;
2341 ++e;
2342 if (e >= 2047)
2343 goto Overflow;
2344 }
2345 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 /* First byte */
2348 *p = (sign << 7) | (e >> 4);
2349 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 /* Second byte */
2352 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2353 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 /* Third byte */
2356 *p = (fhi >> 16) & 0xFF;
2357 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 /* Fourth byte */
2360 *p = (fhi >> 8) & 0xFF;
2361 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 /* Fifth byte */
2364 *p = fhi & 0xFF;
2365 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 /* Sixth byte */
2368 *p = (flo >> 16) & 0xFF;
2369 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 /* Seventh byte */
2372 *p = (flo >> 8) & 0xFF;
2373 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 /* Eighth byte */
2376 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002377 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 /* Done */
2380 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 Overflow:
2383 PyErr_SetString(PyExc_OverflowError,
2384 "float too large to pack with d format");
2385 return -1;
2386 }
2387 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002388 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 if ((double_format == ieee_little_endian_format && !le)
2392 || (double_format == ieee_big_endian_format && le)) {
2393 p += 7;
2394 incr = -1;
2395 }
2396
2397 for (i = 0; i < 8; i++) {
2398 *p = *s++;
2399 p += incr;
2400 }
2401 return 0;
2402 }
Tim Peters9905b942003-03-20 20:53:32 +00002403}
2404
2405double
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002406_PyFloat_Unpack2(const unsigned char *p, int le)
2407{
2408 unsigned char sign;
2409 int e;
2410 unsigned int f;
2411 double x;
2412 int incr = 1;
2413
2414 if (le) {
2415 p += 1;
2416 incr = -1;
2417 }
2418
2419 /* First byte */
2420 sign = (*p >> 7) & 1;
2421 e = (*p & 0x7C) >> 2;
2422 f = (*p & 0x03) << 8;
2423 p += incr;
2424
2425 /* Second byte */
2426 f |= *p;
2427
2428 if (e == 0x1f) {
2429#ifdef PY_NO_SHORT_FLOAT_REPR
2430 if (f == 0) {
2431 /* Infinity */
2432 return sign ? -Py_HUGE_VAL : Py_HUGE_VAL;
2433 }
2434 else {
2435 /* NaN */
2436#ifdef Py_NAN
2437 return sign ? -Py_NAN : Py_NAN;
2438#else
2439 PyErr_SetString(
2440 PyExc_ValueError,
2441 "can't unpack IEEE 754 NaN "
2442 "on platform that does not support NaNs");
2443 return -1;
2444#endif /* #ifdef Py_NAN */
2445 }
2446#else
2447 if (f == 0) {
2448 /* Infinity */
2449 return _Py_dg_infinity(sign);
2450 }
2451 else {
2452 /* NaN */
2453 return _Py_dg_stdnan(sign);
2454 }
2455#endif /* #ifdef PY_NO_SHORT_FLOAT_REPR */
2456 }
2457
2458 x = (double)f / 1024.0;
2459
2460 if (e == 0) {
2461 e = -14;
2462 }
2463 else {
2464 x += 1.0;
2465 e -= 15;
2466 }
2467 x = ldexp(x, e);
2468
2469 if (sign)
2470 x = -x;
2471
2472 return x;
2473}
2474
2475double
Tim Peters9905b942003-03-20 20:53:32 +00002476_PyFloat_Unpack4(const unsigned char *p, int le)
2477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 if (float_format == unknown_format) {
2479 unsigned char sign;
2480 int e;
2481 unsigned int f;
2482 double x;
2483 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 if (le) {
2486 p += 3;
2487 incr = -1;
2488 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 /* First byte */
2491 sign = (*p >> 7) & 1;
2492 e = (*p & 0x7F) << 1;
2493 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 /* Second byte */
2496 e |= (*p >> 7) & 1;
2497 f = (*p & 0x7F) << 16;
2498 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 if (e == 255) {
2501 PyErr_SetString(
2502 PyExc_ValueError,
2503 "can't unpack IEEE 754 special value "
2504 "on non-IEEE platform");
2505 return -1;
2506 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 /* Third byte */
2509 f |= *p << 8;
2510 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 /* Fourth byte */
2513 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 /* XXX This sadly ignores Inf/NaN issues */
2518 if (e == 0)
2519 e = -126;
2520 else {
2521 x += 1.0;
2522 e -= 127;
2523 }
2524 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 if (sign)
2527 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 return x;
2530 }
2531 else {
2532 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 if ((float_format == ieee_little_endian_format && !le)
2535 || (float_format == ieee_big_endian_format && le)) {
2536 char buf[4];
2537 char *d = &buf[3];
2538 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 for (i = 0; i < 4; i++) {
2541 *d-- = *p++;
2542 }
2543 memcpy(&x, buf, 4);
2544 }
2545 else {
2546 memcpy(&x, p, 4);
2547 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 return x;
2550 }
Tim Peters9905b942003-03-20 20:53:32 +00002551}
2552
2553double
2554_PyFloat_Unpack8(const unsigned char *p, int le)
2555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 if (double_format == unknown_format) {
2557 unsigned char sign;
2558 int e;
2559 unsigned int fhi, flo;
2560 double x;
2561 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 if (le) {
2564 p += 7;
2565 incr = -1;
2566 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 /* First byte */
2569 sign = (*p >> 7) & 1;
2570 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 /* Second byte */
2575 e |= (*p >> 4) & 0xF;
2576 fhi = (*p & 0xF) << 24;
2577 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 if (e == 2047) {
2580 PyErr_SetString(
2581 PyExc_ValueError,
2582 "can't unpack IEEE 754 special value "
2583 "on non-IEEE platform");
2584 return -1.0;
2585 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 /* Third byte */
2588 fhi |= *p << 16;
2589 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 /* Fourth byte */
2592 fhi |= *p << 8;
2593 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 /* Fifth byte */
2596 fhi |= *p;
2597 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 /* Sixth byte */
2600 flo = *p << 16;
2601 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 /* Seventh byte */
2604 flo |= *p << 8;
2605 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 /* Eighth byte */
2608 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2611 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 if (e == 0)
2614 e = -1022;
2615 else {
2616 x += 1.0;
2617 e -= 1023;
2618 }
2619 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 if (sign)
2622 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 return x;
2625 }
2626 else {
2627 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 if ((double_format == ieee_little_endian_format && !le)
2630 || (double_format == ieee_big_endian_format && le)) {
2631 char buf[8];
2632 char *d = &buf[7];
2633 int i;
2634
2635 for (i = 0; i < 8; i++) {
2636 *d-- = *p++;
2637 }
2638 memcpy(&x, buf, 8);
2639 }
2640 else {
2641 memcpy(&x, p, 8);
2642 }
2643
2644 return x;
2645 }
Tim Peters9905b942003-03-20 20:53:32 +00002646}