blob: 178f7b2f8d2fa8677d1be4407fe8eba4cda77023 [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 Stinnerc9bc2902020-10-27 02:24:34 +01009#include "pycore_long.h" // _PyLong_GetOne()
Victor Stinner04fc4f22020-06-16 01:28:07 +020010#include "pycore_object.h" // _PyObject_Init()
Victor Stinner2ba59372020-06-05 00:50:05 +020011#include "pycore_pystate.h" // _PyInterpreterState_GET()
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Guido van Rossum3f5da241990-12-20 15:06:42 +000013#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000014#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015
Serhiy Storchakab5c51d32017-03-11 09:21:05 +020016/*[clinic input]
17class float "PyObject *" "&PyFloat_Type"
18[clinic start generated code]*/
19/*[clinic end generated code: output=da39a3ee5e6b4b0d input=dd0003f68f144284]*/
20
21#include "clinic/floatobject.c.h"
Guido van Rossum6923e131990-11-02 17:50:43 +000022
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000023#ifndef PyFloat_MAXFREELIST
Victor Stinner2ba59372020-06-05 00:50:05 +020024# define PyFloat_MAXFREELIST 100
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000025#endif
Guido van Rossum3fce8831999-03-12 19:43:17 +000026
Victor Stinner522691c2020-06-23 16:40:40 +020027
28static struct _Py_float_state *
29get_float_state(void)
30{
31 PyInterpreterState *interp = _PyInterpreterState_GET();
32 return &interp->float_state;
33}
34
35
Christian Heimes93852662007-12-01 12:22:32 +000036double
37PyFloat_GetMax(void)
38{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000040}
41
42double
43PyFloat_GetMin(void)
44{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000046}
47
Christian Heimesd32ed6f2008-01-14 18:49:24 +000048static PyTypeObject FloatInfoType;
49
50PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000051"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000052\n\
Raymond Hettinger71170742019-09-11 07:17:32 -070053A named tuple holding information about the float type. It contains low level\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000054information about the precision and internal representation. Please study\n\
55your system's :file:`float.h` for more information.");
56
57static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 {"max", "DBL_MAX -- maximum representable finite float"},
59 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
60 "is representable"},
61 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
62 "is representable"},
Stefano Taschini0301c9b2018-03-26 11:41:30 +020063 {"min", "DBL_MIN -- Minimum positive normalized float"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
65 "is a normalized float"},
66 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
67 "a normalized"},
Zackery Spytzfdc5a942020-05-24 04:03:52 -060068 {"dig", "DBL_DIG -- maximum number of decimal digits that "
69 "can be faithfully represented in a float"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
71 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
72 "representable float"},
73 {"radix", "FLT_RADIX -- radix of exponent"},
Zackery Spytzfdc5a942020-05-24 04:03:52 -060074 {"rounds", "FLT_ROUNDS -- rounding mode used for arithmetic "
75 "operations"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +000077};
78
79static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 "sys.float_info", /* name */
81 floatinfo__doc__, /* doc */
82 floatinfo_fields, /* fields */
83 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +000084};
85
Christian Heimes93852662007-12-01 12:22:32 +000086PyObject *
87PyFloat_GetInfo(void)
88{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 PyObject* floatinfo;
90 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +000091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 floatinfo = PyStructSequence_New(&FloatInfoType);
93 if (floatinfo == NULL) {
94 return NULL;
95 }
Christian Heimes93852662007-12-01 12:22:32 +000096
Christian Heimesd32ed6f2008-01-14 18:49:24 +000097#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +000099#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 SetDblFlag(DBL_MAX);
103 SetIntFlag(DBL_MAX_EXP);
104 SetIntFlag(DBL_MAX_10_EXP);
105 SetDblFlag(DBL_MIN);
106 SetIntFlag(DBL_MIN_EXP);
107 SetIntFlag(DBL_MIN_10_EXP);
108 SetIntFlag(DBL_DIG);
109 SetIntFlag(DBL_MANT_DIG);
110 SetDblFlag(DBL_EPSILON);
111 SetIntFlag(FLT_RADIX);
112 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000113#undef SetIntFlag
114#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115
116 if (PyErr_Occurred()) {
117 Py_CLEAR(floatinfo);
118 return NULL;
119 }
120 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000121}
122
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000123PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000124PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125{
Victor Stinner522691c2020-06-23 16:40:40 +0200126 struct _Py_float_state *state = get_float_state();
Victor Stinner2ba59372020-06-05 00:50:05 +0200127 PyFloatObject *op = state->free_list;
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000128 if (op != NULL) {
Victor Stinnerbcb19832020-06-08 02:14:47 +0200129#ifdef Py_DEBUG
130 // PyFloat_FromDouble() must not be called after _PyFloat_Fini()
131 assert(state->numfree != -1);
132#endif
Victor Stinner2ba59372020-06-05 00:50:05 +0200133 state->free_list = (PyFloatObject *) Py_TYPE(op);
134 state->numfree--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 }
Victor Stinner2ba59372020-06-05 00:50:05 +0200136 else {
137 op = PyObject_Malloc(sizeof(PyFloatObject));
138 if (!op) {
139 return PyErr_NoMemory();
140 }
141 }
Victor Stinner04fc4f22020-06-16 01:28:07 +0200142 _PyObject_Init((PyObject*)op, &PyFloat_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 op->ob_fval = fval;
144 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145}
146
Brett Cannona721aba2016-09-09 14:57:09 -0700147static PyObject *
148float_from_string_inner(const char *s, Py_ssize_t len, void *obj)
149{
150 double x;
151 const char *end;
152 const char *last = s + len;
153 /* strip space */
154 while (s < last && Py_ISSPACE(*s)) {
155 s++;
156 }
157
158 while (s < last - 1 && Py_ISSPACE(last[-1])) {
159 last--;
160 }
161
162 /* We don't care about overflow or underflow. If the platform
163 * supports them, infinities and signed zeroes (on underflow) are
164 * fine. */
165 x = PyOS_string_to_double(s, (char **)&end, NULL);
166 if (end != last) {
167 PyErr_Format(PyExc_ValueError,
168 "could not convert string to float: "
169 "%R", obj);
170 return NULL;
171 }
172 else if (x == -1.0 && PyErr_Occurred()) {
173 return NULL;
174 }
175 else {
176 return PyFloat_FromDouble(x);
177 }
178}
179
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000180PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000181PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000182{
Brett Cannona721aba2016-09-09 14:57:09 -0700183 const char *s;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000184 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 Py_ssize_t len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200186 Py_buffer view = {NULL, NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200190 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000192 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200193 assert(PyUnicode_IS_ASCII(s_buffer));
194 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200195 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200196 assert(s != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000198 else if (PyBytes_Check(v)) {
199 s = PyBytes_AS_STRING(v);
200 len = PyBytes_GET_SIZE(v);
201 }
202 else if (PyByteArray_Check(v)) {
203 s = PyByteArray_AS_STRING(v);
204 len = PyByteArray_GET_SIZE(v);
205 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200206 else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
207 s = (const char *)view.buf;
208 len = view.len;
Martin Pantereeb896c2015-11-07 02:32:21 +0000209 /* Copy to NUL-terminated buffer. */
210 s_buffer = PyBytes_FromStringAndSize(s, len);
211 if (s_buffer == NULL) {
212 PyBuffer_Release(&view);
213 return NULL;
214 }
215 s = PyBytes_AS_STRING(s_buffer);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200216 }
217 else {
Ezio Melottia5b95992013-11-07 19:18:34 +0200218 PyErr_Format(PyExc_TypeError,
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +0300219 "float() argument must be a string or a real number, not '%.200s'",
Ezio Melottia5b95992013-11-07 19:18:34 +0200220 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 return NULL;
222 }
Brett Cannona721aba2016-09-09 14:57:09 -0700223 result = _Py_string_to_number_with_underscores(s, len, "float", v, v,
224 float_from_string_inner);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200225 PyBuffer_Release(&view);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000226 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000228}
229
Guido van Rossum234f9421993-06-17 12:35:49 +0000230static void
Fred Drakefd99de62000-07-09 05:02:18 +0000231float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 if (PyFloat_CheckExact(op)) {
Victor Stinner522691c2020-06-23 16:40:40 +0200234 struct _Py_float_state *state = get_float_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +0200235#ifdef Py_DEBUG
236 // float_dealloc() must not be called after _PyFloat_Fini()
237 assert(state->numfree != -1);
238#endif
Victor Stinner2ba59372020-06-05 00:50:05 +0200239 if (state->numfree >= PyFloat_MAXFREELIST) {
Victor Stinner32bd68c2020-12-01 10:37:39 +0100240 PyObject_Free(op);
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000241 return;
242 }
Victor Stinner2ba59372020-06-05 00:50:05 +0200243 state->numfree++;
244 Py_SET_TYPE(op, (PyTypeObject *)state->free_list);
245 state->free_list = op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 }
Victor Stinner522691c2020-06-23 16:40:40 +0200247 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 Py_TYPE(op)->tp_free((PyObject *)op);
Victor Stinner522691c2020-06-23 16:40:40 +0200249 }
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000250}
251
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000252double
Fred Drakefd99de62000-07-09 05:02:18 +0000253PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 PyNumberMethods *nb;
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300256 PyObject *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 if (op == NULL) {
260 PyErr_BadArgument();
261 return -1;
262 }
Tim Petersd2364e82001-11-01 20:09:42 +0000263
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300264 if (PyFloat_Check(op)) {
265 return PyFloat_AS_DOUBLE(op);
266 }
267
268 nb = Py_TYPE(op)->tp_as_number;
269 if (nb == NULL || nb->nb_float == NULL) {
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300270 if (nb && nb->nb_index) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300271 PyObject *res = _PyNumber_Index(op);
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300272 if (!res) {
273 return -1;
274 }
275 double val = PyLong_AsDouble(res);
276 Py_DECREF(res);
277 return val;
278 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300279 PyErr_Format(PyExc_TypeError, "must be real number, not %.50s",
Victor Stinner58ac7002020-02-07 03:04:21 +0100280 Py_TYPE(op)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 return -1;
282 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000283
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300284 res = (*nb->nb_float) (op);
285 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return -1;
287 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300288 if (!PyFloat_CheckExact(res)) {
289 if (!PyFloat_Check(res)) {
290 PyErr_Format(PyExc_TypeError,
291 "%.50s.__float__ returned non-float (type %.50s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100292 Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name);
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300293 Py_DECREF(res);
294 return -1;
295 }
296 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
297 "%.50s.__float__ returned non-float (type %.50s). "
298 "The ability to return an instance of a strict subclass of float "
299 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner58ac7002020-02-07 03:04:21 +0100300 Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name)) {
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300301 Py_DECREF(res);
302 return -1;
303 }
304 }
Tim Petersd2364e82001-11-01 20:09:42 +0000305
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300306 val = PyFloat_AS_DOUBLE(res);
307 Py_DECREF(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309}
310
Neil Schemenauer32117e52001-01-04 01:44:34 +0000311/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000312 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000313 set to NULL, and the function invoking this macro returns NULL. If
Serhiy Storchaka95949422013-08-27 19:40:23 +0300314 obj is not of float or int type, Py_NotImplemented is incref'ed,
Tim Peters77d8a4f2001-12-11 20:31:34 +0000315 stored in obj, and returned from the function invoking this macro.
316*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317#define CONVERT_TO_DOUBLE(obj, dbl) \
318 if (PyFloat_Check(obj)) \
319 dbl = PyFloat_AS_DOUBLE(obj); \
320 else if (convert_to_double(&(obj), &(dbl)) < 0) \
321 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000322
Eric Smith0923d1d2009-04-16 20:16:10 +0000323/* Methods */
324
Neil Schemenauer32117e52001-01-04 01:44:34 +0000325static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000326convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000327{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200328 PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 if (PyLong_Check(obj)) {
331 *dbl = PyLong_AsDouble(obj);
332 if (*dbl == -1.0 && PyErr_Occurred()) {
333 *v = NULL;
334 return -1;
335 }
336 }
337 else {
338 Py_INCREF(Py_NotImplemented);
339 *v = Py_NotImplemented;
340 return -1;
341 }
342 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000343}
344
Eric Smith0923d1d2009-04-16 20:16:10 +0000345static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000346float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000347{
348 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200349 char *buf;
350
351 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
352 'r', 0,
353 Py_DTSF_ADD_DOT_0,
354 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000355 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000356 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200357 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000358 PyMem_Free(buf);
359 return result;
360}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000361
Tim Peters307fa782004-09-23 08:06:40 +0000362/* Comparison is pretty much a nightmare. When comparing float to float,
363 * we do it as straightforwardly (and long-windedly) as conceivable, so
364 * that, e.g., Python x == y delivers the same result as the platform
365 * C x == y when x and/or y is a NaN.
366 * When mixing float with an integer type, there's no good *uniform* approach.
367 * Converting the double to an integer obviously doesn't work, since we
368 * may lose info from fractional bits. Converting the integer to a double
Serhiy Storchaka95949422013-08-27 19:40:23 +0300369 * also has two failure modes: (1) an int may trigger overflow (too
Tim Peters307fa782004-09-23 08:06:40 +0000370 * 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 +0200371 * 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 +0000372 * 63 bits of precision, but a C double probably has only 53), and then
373 * we can falsely claim equality when low-order integer bits are lost by
374 * coercion to double. So this part is painful too.
375 */
376
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000377static PyObject*
378float_richcompare(PyObject *v, PyObject *w, int op)
379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 double i, j;
381 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 assert(PyFloat_Check(v));
384 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 /* Switch on the type of w. Set i and j to doubles to be compared,
387 * and op to the richcomp to use.
388 */
389 if (PyFloat_Check(w))
390 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 else if (!Py_IS_FINITE(i)) {
393 if (PyLong_Check(w))
394 /* If i is an infinity, its magnitude exceeds any
395 * finite integer, so it doesn't matter which int we
396 * compare i with. If i is a NaN, similarly.
397 */
398 j = 0.0;
399 else
400 goto Unimplemented;
401 }
Tim Peters307fa782004-09-23 08:06:40 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 else if (PyLong_Check(w)) {
404 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
405 int wsign = _PyLong_Sign(w);
406 size_t nbits;
407 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 if (vsign != wsign) {
410 /* Magnitudes are irrelevant -- the signs alone
411 * determine the outcome.
412 */
413 i = (double)vsign;
414 j = (double)wsign;
415 goto Compare;
416 }
417 /* The signs are the same. */
418 /* Convert w to a double if it fits. In particular, 0 fits. */
419 nbits = _PyLong_NumBits(w);
420 if (nbits == (size_t)-1 && PyErr_Occurred()) {
421 /* This long is so large that size_t isn't big enough
422 * to hold the # of bits. Replace with little doubles
423 * that give the same outcome -- w is so large that
424 * its magnitude must exceed the magnitude of any
425 * finite float.
426 */
427 PyErr_Clear();
428 i = (double)vsign;
429 assert(wsign != 0);
430 j = wsign * 2.0;
431 goto Compare;
432 }
433 if (nbits <= 48) {
434 j = PyLong_AsDouble(w);
435 /* It's impossible that <= 48 bits overflowed. */
436 assert(j != -1.0 || ! PyErr_Occurred());
437 goto Compare;
438 }
439 assert(wsign != 0); /* else nbits was 0 */
440 assert(vsign != 0); /* if vsign were 0, then since wsign is
441 * not 0, we would have taken the
442 * vsign != wsign branch at the start */
443 /* We want to work with non-negative numbers. */
444 if (vsign < 0) {
445 /* "Multiply both sides" by -1; this also swaps the
446 * comparator.
447 */
448 i = -i;
449 op = _Py_SwappedOp[op];
450 }
451 assert(i > 0.0);
452 (void) frexp(i, &exponent);
453 /* exponent is the # of bits in v before the radix point;
454 * we know that nbits (the # of bits in w) > 48 at this point
455 */
456 if (exponent < 0 || (size_t)exponent < nbits) {
457 i = 1.0;
458 j = 2.0;
459 goto Compare;
460 }
461 if ((size_t)exponent > nbits) {
462 i = 2.0;
463 j = 1.0;
464 goto Compare;
465 }
466 /* v and w have the same number of bits before the radix
Serhiy Storchaka95949422013-08-27 19:40:23 +0300467 * point. Construct two ints that have the same comparison
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 * outcome.
469 */
470 {
471 double fracpart;
472 double intpart;
473 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 PyObject *vv = NULL;
475 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 if (wsign < 0) {
478 ww = PyNumber_Negative(w);
479 if (ww == NULL)
480 goto Error;
481 }
482 else
483 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 fracpart = modf(i, &intpart);
486 vv = PyLong_FromDouble(intpart);
487 if (vv == NULL)
488 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (fracpart != 0.0) {
491 /* Shift left, and or a 1 bit into vv
492 * to represent the lost fraction.
493 */
494 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000495
Serhiy Storchakaa5119e72019-05-19 14:14:38 +0300496 temp = _PyLong_Lshift(ww, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (temp == NULL)
498 goto Error;
499 Py_DECREF(ww);
500 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000501
Serhiy Storchakaa5119e72019-05-19 14:14:38 +0300502 temp = _PyLong_Lshift(vv, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 if (temp == NULL)
504 goto Error;
505 Py_DECREF(vv);
506 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000507
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100508 temp = PyNumber_Or(vv, _PyLong_GetOne());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 if (temp == NULL)
510 goto Error;
511 Py_DECREF(vv);
512 vv = temp;
513 }
Tim Peters307fa782004-09-23 08:06:40 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 r = PyObject_RichCompareBool(vv, ww, op);
516 if (r < 0)
517 goto Error;
518 result = PyBool_FromLong(r);
519 Error:
520 Py_XDECREF(vv);
521 Py_XDECREF(ww);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 return result;
523 }
524 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000525
Serhiy Storchaka95949422013-08-27 19:40:23 +0300526 else /* w isn't float or int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000528
529 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 switch (op) {
531 case Py_EQ:
532 r = i == j;
533 break;
534 case Py_NE:
535 r = i != j;
536 break;
537 case Py_LE:
538 r = i <= j;
539 break;
540 case Py_GE:
541 r = i >= j;
542 break;
543 case Py_LT:
544 r = i < j;
545 break;
546 case Py_GT:
547 r = i > j;
548 break;
549 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000551
552 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500553 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000554}
555
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000556static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000557float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000560}
561
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000562static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000563float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 double a,b;
566 CONVERT_TO_DOUBLE(v, a);
567 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 a = a + b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000570}
571
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000572static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000573float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 double a,b;
576 CONVERT_TO_DOUBLE(v, a);
577 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 a = a - b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000580}
581
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000582static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000583float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 double a,b;
586 CONVERT_TO_DOUBLE(v, a);
587 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 a = a * b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000590}
591
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000592static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000593float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 double a,b;
596 CONVERT_TO_DOUBLE(v, a);
597 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 if (b == 0.0) {
599 PyErr_SetString(PyExc_ZeroDivisionError,
600 "float division by zero");
601 return NULL;
602 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 a = a / b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000605}
606
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000607static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000608float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 double vx, wx;
611 double mod;
612 CONVERT_TO_DOUBLE(v, vx);
613 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (wx == 0.0) {
615 PyErr_SetString(PyExc_ZeroDivisionError,
616 "float modulo");
617 return NULL;
618 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000620 if (mod) {
621 /* ensure the remainder has the same sign as the denominator */
622 if ((wx < 0) != (mod < 0)) {
623 mod += wx;
624 }
625 }
626 else {
627 /* the remainder is zero, and in the presence of signed zeroes
628 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000629 it has the same sign as the denominator. */
630 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000633}
634
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900635static void
636_float_div_mod(double vx, double wx, double *floordiv, double *mod)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000637{
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900638 double div;
639 *mod = fmod(vx, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 /* fmod is typically exact, so vx-mod is *mathematically* an
641 exact multiple of wx. But this is fp arithmetic, and fp
642 vx - mod is an approximation; the result is that div may
643 not be an exact integral value after the division, although
644 it will always be very close to one.
645 */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900646 div = (vx - *mod) / wx;
647 if (*mod) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 /* ensure the remainder has the same sign as the denominator */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900649 if ((wx < 0) != (*mod < 0)) {
650 *mod += wx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 div -= 1.0;
652 }
653 }
654 else {
655 /* the remainder is zero, and in the presence of signed zeroes
656 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000657 it has the same sign as the denominator. */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900658 *mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 }
660 /* snap quotient to nearest integral value */
661 if (div) {
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900662 *floordiv = floor(div);
663 if (div - *floordiv > 0.5) {
664 *floordiv += 1.0;
Mark Dickinsonbe8147b2020-02-02 11:37:02 +0000665 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 }
667 else {
668 /* div is zero - get the same sign as the true quotient */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900669 *floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 }
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900671}
672
673static PyObject *
674float_divmod(PyObject *v, PyObject *w)
675{
Mark Dickinsonbe8147b2020-02-02 11:37:02 +0000676 double vx, wx;
677 double mod, floordiv;
678 CONVERT_TO_DOUBLE(v, vx);
679 CONVERT_TO_DOUBLE(w, wx);
680 if (wx == 0.0) {
681 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
682 return NULL;
683 }
684 _float_div_mod(vx, wx, &floordiv, &mod);
685 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000686}
687
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000688static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000689float_floor_div(PyObject *v, PyObject *w)
690{
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900691 double vx, wx;
692 double mod, floordiv;
693 CONVERT_TO_DOUBLE(v, vx);
694 CONVERT_TO_DOUBLE(w, wx);
695 if (wx == 0.0) {
696 PyErr_SetString(PyExc_ZeroDivisionError, "float floor division by zero");
697 return NULL;
698 }
699 _float_div_mod(vx, wx, &floordiv, &mod);
700 return PyFloat_FromDouble(floordiv);
Tim Peters63a35712001-12-11 19:57:24 +0000701}
702
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000703/* determine whether x is an odd integer or not; assumes that
704 x is not an infinity or nan. */
705#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
706
Tim Peters63a35712001-12-11 19:57:24 +0000707static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000708float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 double iv, iw, ix;
711 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 if ((PyObject *)z != Py_None) {
714 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
715 "allowed unless all arguments are integers");
716 return NULL;
717 }
Tim Peters32f453e2001-09-03 08:35:41 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 CONVERT_TO_DOUBLE(v, iv);
720 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 /* Sort out special cases here instead of relying on pow() */
723 if (iw == 0) { /* v**0 is 1, even 0**0 */
724 return PyFloat_FromDouble(1.0);
725 }
726 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
727 return PyFloat_FromDouble(iv);
728 }
729 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
730 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
731 }
732 if (Py_IS_INFINITY(iw)) {
733 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
734 * abs(v) > 1 (including case where v infinite)
735 *
736 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
737 * abs(v) > 1 (including case where v infinite)
738 */
739 iv = fabs(iv);
740 if (iv == 1.0)
741 return PyFloat_FromDouble(1.0);
742 else if ((iw > 0.0) == (iv > 1.0))
743 return PyFloat_FromDouble(fabs(iw)); /* return inf */
744 else
745 return PyFloat_FromDouble(0.0);
746 }
747 if (Py_IS_INFINITY(iv)) {
748 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
749 * both cases, we need to add the appropriate sign if w is
750 * an odd integer.
751 */
752 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
753 if (iw > 0.0)
754 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
755 else
756 return PyFloat_FromDouble(iw_is_odd ?
757 copysign(0.0, iv) : 0.0);
758 }
759 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
760 (already dealt with above), and an error
761 if w is negative. */
762 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
763 if (iw < 0.0) {
764 PyErr_SetString(PyExc_ZeroDivisionError,
765 "0.0 cannot be raised to a "
766 "negative power");
767 return NULL;
768 }
769 /* use correct sign if iw is odd */
770 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
771 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 if (iv < 0.0) {
774 /* Whether this is an error is a mess, and bumps into libm
775 * bugs so we have to figure it out ourselves.
776 */
777 if (iw != floor(iw)) {
778 /* Negative numbers raised to fractional powers
779 * become complex.
780 */
781 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
782 }
783 /* iw is an exact integer, albeit perhaps a very large
784 * one. Replace iv by its absolute value and remember
785 * to negate the pow result if iw is odd.
786 */
787 iv = -iv;
788 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
789 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
792 /* (-1) ** large_integer also ends up here. Here's an
793 * extract from the comments for the previous
794 * implementation explaining why this special case is
795 * necessary:
796 *
797 * -1 raised to an exact integer should never be exceptional.
798 * Alas, some libms (chiefly glibc as of early 2003) return
799 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
800 * happen to be representable in a *C* integer. That's a
801 * bug.
802 */
803 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
804 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 /* Now iv and iw are finite, iw is nonzero, and iv is
807 * positive and not equal to 1.0. We finally allow
808 * the platform pow to step in and do the rest.
809 */
810 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 ix = pow(iv, iw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 Py_ADJUST_ERANGE1(ix);
813 if (negate_result)
814 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (errno != 0) {
817 /* We don't expect any errno value other than ERANGE, but
818 * the range of libm bugs appears unbounded.
819 */
820 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
821 PyExc_ValueError);
822 return NULL;
823 }
824 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000825}
826
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000827#undef DOUBLE_IS_ODD_INTEGER
828
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000829static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000830float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000833}
834
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000835static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000836float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000839}
840
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000841static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000842float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000845}
846
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200847/*[clinic input]
848float.is_integer
849
850Return True if the float is an integer.
851[clinic start generated code]*/
852
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000853static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200854float_is_integer_impl(PyObject *self)
855/*[clinic end generated code: output=7112acf95a4d31ea input=311810d3f777e10d]*/
Christian Heimes53876d92008-04-19 00:31:39 +0000856{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200857 double x = PyFloat_AsDouble(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 PyObject *o;
859
860 if (x == -1.0 && PyErr_Occurred())
861 return NULL;
862 if (!Py_IS_FINITE(x))
863 Py_RETURN_FALSE;
864 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 o = (floor(x) == x) ? Py_True : Py_False;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (errno != 0) {
867 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
868 PyExc_ValueError);
869 return NULL;
870 }
871 Py_INCREF(o);
872 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000873}
874
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200875/*[clinic input]
876float.__trunc__
877
878Return the Integral closest to x between 0 and x.
879[clinic start generated code]*/
880
Christian Heimes53876d92008-04-19 00:31:39 +0000881static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200882float___trunc___impl(PyObject *self)
883/*[clinic end generated code: output=dd3e289dd4c6b538 input=591b9ba0d650fdff]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000884{
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500885 return PyLong_FromDouble(PyFloat_AS_DOUBLE(self));
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000886}
887
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +0300888/*[clinic input]
889float.__floor__
890
891Return the floor as an Integral.
892[clinic start generated code]*/
893
894static PyObject *
895float___floor___impl(PyObject *self)
896/*[clinic end generated code: output=e0551dbaea8c01d1 input=77bb13eb12e268df]*/
897{
898 double x = PyFloat_AS_DOUBLE(self);
899 return PyLong_FromDouble(floor(x));
900}
901
902/*[clinic input]
903float.__ceil__
904
905Return the ceiling as an Integral.
906[clinic start generated code]*/
907
908static PyObject *
909float___ceil___impl(PyObject *self)
910/*[clinic end generated code: output=a2fd8858f73736f9 input=79e41ae94aa0a516]*/
911{
912 double x = PyFloat_AS_DOUBLE(self);
913 return PyLong_FromDouble(ceil(x));
914}
915
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000916/* double_round: rounds a finite double to the closest multiple of
917 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
918 ndigits <= 323). Returns a Python float, or sets a Python error and
919 returns NULL on failure (OverflowError and memory errors are possible). */
920
921#ifndef PY_NO_SHORT_FLOAT_REPR
922/* version of double_round that uses the correctly-rounded string<->double
923 conversions from Python/dtoa.c */
924
925static PyObject *
926double_round(double x, int ndigits) {
927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 double rounded;
929 Py_ssize_t buflen, mybuflen=100;
930 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
931 int decpt, sign;
932 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000933 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000936 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000938 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 if (buf == NULL) {
940 PyErr_NoMemory();
941 return NULL;
942 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
945 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
946 buflen = buf_end - buf;
947 if (buflen + 8 > mybuflen) {
948 mybuflen = buflen+8;
949 mybuf = (char *)PyMem_Malloc(mybuflen);
950 if (mybuf == NULL) {
951 PyErr_NoMemory();
952 goto exit;
953 }
954 }
955 /* copy buf to mybuf, adding exponent, sign and leading 0 */
956 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
957 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 /* and convert the resulting string back to a double */
960 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000961 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000963 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 if (errno == ERANGE && fabs(rounded) >= 1.)
965 PyErr_SetString(PyExc_OverflowError,
966 "rounded value too large to represent");
967 else
968 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* done computing value; now clean up */
971 if (mybuf != shortbuf)
972 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000973 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 _Py_dg_freedtoa(buf);
975 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000976}
977
978#else /* PY_NO_SHORT_FLOAT_REPR */
979
980/* fallback version, to be used when correctly rounded binary<->decimal
981 conversions aren't available */
982
983static PyObject *
984double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 double pow1, pow2, y, z;
986 if (ndigits >= 0) {
987 if (ndigits > 22) {
988 /* pow1 and pow2 are each safe from overflow, but
989 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
990 pow1 = pow(10.0, (double)(ndigits-22));
991 pow2 = 1e22;
992 }
993 else {
994 pow1 = pow(10.0, (double)ndigits);
995 pow2 = 1.0;
996 }
997 y = (x*pow1)*pow2;
998 /* if y overflows, then rounded value is exactly x */
999 if (!Py_IS_FINITE(y))
1000 return PyFloat_FromDouble(x);
1001 }
1002 else {
1003 pow1 = pow(10.0, (double)-ndigits);
1004 pow2 = 1.0; /* unused; silences a gcc compiler warning */
1005 y = x / pow1;
1006 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 z = round(y);
1009 if (fabs(y-z) == 0.5)
1010 /* halfway between two integers; use round-half-even */
1011 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 if (ndigits >= 0)
1014 z = (z / pow2) / pow1;
1015 else
1016 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 /* if computation resulted in overflow, raise OverflowError */
1019 if (!Py_IS_FINITE(z)) {
1020 PyErr_SetString(PyExc_OverflowError,
1021 "overflow occurred during round");
1022 return NULL;
1023 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001026}
1027
1028#endif /* PY_NO_SHORT_FLOAT_REPR */
1029
1030/* round a Python float v to the closest multiple of 10**-ndigits */
1031
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001032/*[clinic input]
1033float.__round__
1034
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001035 ndigits as o_ndigits: object = None
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001036 /
1037
1038Return the Integral closest to x, rounding half toward even.
1039
1040When an argument is passed, work like built-in round(x, ndigits).
1041[clinic start generated code]*/
1042
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001043static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001044float___round___impl(PyObject *self, PyObject *o_ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001045/*[clinic end generated code: output=374c36aaa0f13980 input=fc0fe25924fbc9ed]*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 double x, rounded;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001049
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001050 x = PyFloat_AsDouble(self);
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001051 if (o_ndigits == Py_None) {
Steve Dowercb39d1f2015-04-15 16:10:59 -04001052 /* single-argument round or with None ndigits:
1053 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 rounded = round(x);
1055 if (fabs(x-rounded) == 0.5)
1056 /* halfway case: round to even */
1057 rounded = 2.0*round(x/2.0);
1058 return PyLong_FromDouble(rounded);
1059 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 /* interpret second argument as a Py_ssize_t; clips on overflow */
1062 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1063 if (ndigits == -1 && PyErr_Occurred())
1064 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 /* nans and infinities round to themselves */
1067 if (!Py_IS_FINITE(x))
1068 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1071 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1072 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001073#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1074#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 if (ndigits > NDIGITS_MAX)
1076 /* return x */
1077 return PyFloat_FromDouble(x);
1078 else if (ndigits < NDIGITS_MIN)
1079 /* return 0.0, but with sign of x */
1080 return PyFloat_FromDouble(0.0*x);
1081 else
1082 /* finite x, and ndigits is not unreasonably large */
1083 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001084#undef NDIGITS_MAX
1085#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001086}
1087
1088static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001089float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 if (PyFloat_CheckExact(v))
1092 Py_INCREF(v);
1093 else
1094 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1095 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001096}
1097
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001098/*[clinic input]
1099float.conjugate
1100
1101Return self, the complex conjugate of any float.
1102[clinic start generated code]*/
1103
1104static PyObject *
1105float_conjugate_impl(PyObject *self)
1106/*[clinic end generated code: output=8ca292c2479194af input=82ba6f37a9ff91dd]*/
1107{
1108 return float_float(self);
1109}
1110
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001111/* turn ASCII hex characters into integer values and vice versa */
1112
1113static char
1114char_from_hex(int x)
1115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001117 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001118}
1119
1120static int
1121hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 int x;
1123 switch(c) {
1124 case '0':
1125 x = 0;
1126 break;
1127 case '1':
1128 x = 1;
1129 break;
1130 case '2':
1131 x = 2;
1132 break;
1133 case '3':
1134 x = 3;
1135 break;
1136 case '4':
1137 x = 4;
1138 break;
1139 case '5':
1140 x = 5;
1141 break;
1142 case '6':
1143 x = 6;
1144 break;
1145 case '7':
1146 x = 7;
1147 break;
1148 case '8':
1149 x = 8;
1150 break;
1151 case '9':
1152 x = 9;
1153 break;
1154 case 'a':
1155 case 'A':
1156 x = 10;
1157 break;
1158 case 'b':
1159 case 'B':
1160 x = 11;
1161 break;
1162 case 'c':
1163 case 'C':
1164 x = 12;
1165 break;
1166 case 'd':
1167 case 'D':
1168 x = 13;
1169 break;
1170 case 'e':
1171 case 'E':
1172 x = 14;
1173 break;
1174 case 'f':
1175 case 'F':
1176 x = 15;
1177 break;
1178 default:
1179 x = -1;
1180 break;
1181 }
1182 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001183}
1184
1185/* convert a float to a hexadecimal string */
1186
1187/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1188 of the form 4k+1. */
1189#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1190
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001191/*[clinic input]
1192float.hex
1193
1194Return a hexadecimal representation of a floating-point number.
1195
1196>>> (-0.1).hex()
1197'-0x1.999999999999ap-4'
1198>>> 3.14159.hex()
1199'0x1.921f9f01b866ep+1'
1200[clinic start generated code]*/
1201
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001202static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001203float_hex_impl(PyObject *self)
1204/*[clinic end generated code: output=0ebc9836e4d302d4 input=bec1271a33d47e67]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 double x, m;
1207 int e, shift, i, si, esign;
1208 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1209 trailing NUL byte. */
1210 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001211
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001212 CONVERT_TO_DOUBLE(self, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001215 return float_repr((PyFloatObject *)self);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001218 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 return PyUnicode_FromString("-0x0.0p+0");
1220 else
1221 return PyUnicode_FromString("0x0.0p+0");
1222 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001225 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 m = ldexp(m, shift);
1227 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 si = 0;
1230 s[si] = char_from_hex((int)m);
1231 si++;
1232 m -= (int)m;
1233 s[si] = '.';
1234 si++;
1235 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1236 m *= 16.0;
1237 s[si] = char_from_hex((int)m);
1238 si++;
1239 m -= (int)m;
1240 }
1241 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (e < 0) {
1244 esign = (int)'-';
1245 e = -e;
1246 }
1247 else
1248 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 if (x < 0.0)
1251 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1252 else
1253 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001254}
1255
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001256/* Convert a hexadecimal string to a float. */
1257
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001258/*[clinic input]
1259@classmethod
1260float.fromhex
1261
1262 string: object
1263 /
1264
1265Create a floating-point number from a hexadecimal string.
1266
1267>>> float.fromhex('0x1.ffffp10')
12682047.984375
1269>>> float.fromhex('-0x1p-1074')
1270-5e-324
1271[clinic start generated code]*/
1272
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001273static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001274float_fromhex(PyTypeObject *type, PyObject *string)
1275/*[clinic end generated code: output=46c0274d22b78e82 input=0407bebd354bca89]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001276{
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001277 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 double x;
1279 long exp, top_exp, lsb, key_digit;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001280 const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 int half_eps, digit, round_up, negate=0;
1282 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 /*
1285 * For the sake of simplicity and correctness, we impose an artificial
1286 * limit on ndigits, the total number of hex digits in the coefficient
1287 * The limit is chosen to ensure that, writing exp for the exponent,
1288 *
1289 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1290 * guaranteed to overflow (provided it's nonzero)
1291 *
1292 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1293 * guaranteed to underflow to 0.
1294 *
1295 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1296 * overflow in the calculation of exp and top_exp below.
1297 *
1298 * More specifically, ndigits is assumed to satisfy the following
1299 * inequalities:
1300 *
1301 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1302 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1303 *
1304 * If either of these inequalities is not satisfied, a ValueError is
1305 * raised. Otherwise, write x for the value of the hex string, and
1306 * assume x is nonzero. Then
1307 *
1308 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1309 *
1310 * Now if exp > LONG_MAX/2 then:
1311 *
1312 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1313 * = DBL_MAX_EXP
1314 *
1315 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1316 * double, so overflows. If exp < LONG_MIN/2, then
1317 *
1318 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1319 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1320 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1321 *
1322 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1323 * when converted to a C double.
1324 *
1325 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1326 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1327 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001328
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001329 s = PyUnicode_AsUTF8AndSize(string, &length);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 if (s == NULL)
1331 return NULL;
1332 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 /********************
1335 * Parse the string *
1336 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 /* leading whitespace */
1339 while (Py_ISSPACE(*s))
1340 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 /* infinities and nans */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001343 x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 if (coeff_end != s) {
1345 s = coeff_end;
1346 goto finished;
1347 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 /* optional sign */
1350 if (*s == '-') {
1351 s++;
1352 negate = 1;
1353 }
1354 else if (*s == '+')
1355 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 /* [0x] */
1358 s_store = s;
1359 if (*s == '0') {
1360 s++;
1361 if (*s == 'x' || *s == 'X')
1362 s++;
1363 else
1364 s = s_store;
1365 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 /* coefficient: <integer> [. <fraction>] */
1368 coeff_start = s;
1369 while (hex_from_char(*s) >= 0)
1370 s++;
1371 s_store = s;
1372 if (*s == '.') {
1373 s++;
1374 while (hex_from_char(*s) >= 0)
1375 s++;
1376 coeff_end = s-1;
1377 }
1378 else
1379 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 /* ndigits = total # of hex digits; fdigits = # after point */
1382 ndigits = coeff_end - coeff_start;
1383 fdigits = coeff_end - s_store;
1384 if (ndigits == 0)
1385 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001386 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1387 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 /* [p <exponent>] */
1391 if (*s == 'p' || *s == 'P') {
1392 s++;
1393 exp_start = s;
1394 if (*s == '-' || *s == '+')
1395 s++;
1396 if (!('0' <= *s && *s <= '9'))
1397 goto parse_error;
1398 s++;
1399 while ('0' <= *s && *s <= '9')
1400 s++;
1401 exp = strtol(exp_start, NULL, 10);
1402 }
1403 else
1404 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001405
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001406/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1408 coeff_end-(j) : \
1409 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 /*******************************************
1412 * Compute rounded value of the hex string *
1413 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 /* Discard leading zeros, and catch extreme overflow and underflow */
1416 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1417 ndigits--;
1418 if (ndigits == 0 || exp < LONG_MIN/2) {
1419 x = 0.0;
1420 goto finished;
1421 }
1422 if (exp > LONG_MAX/2)
1423 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 /* Adjust exponent for fractional part. */
1426 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1429 top_exp = exp + 4*((long)ndigits - 1);
1430 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1431 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 /* catch almost all nonextreme cases of overflow and underflow here */
1434 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1435 x = 0.0;
1436 goto finished;
1437 }
1438 if (top_exp > DBL_MAX_EXP)
1439 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 /* lsb = exponent of least significant bit of the *rounded* value.
1442 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001443 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 x = 0.0;
1446 if (exp >= lsb) {
1447 /* no rounding required */
1448 for (i = ndigits-1; i >= 0; i--)
1449 x = 16.0*x + HEX_DIGIT(i);
1450 x = ldexp(x, (int)(exp));
1451 goto finished;
1452 }
1453 /* rounding required. key_digit is the index of the hex digit
1454 containing the first bit to be rounded away. */
1455 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1456 key_digit = (lsb - exp - 1) / 4;
1457 for (i = ndigits-1; i > key_digit; i--)
1458 x = 16.0*x + HEX_DIGIT(i);
1459 digit = HEX_DIGIT(key_digit);
1460 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1463 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1464 if ((digit & half_eps) != 0) {
1465 round_up = 0;
1466 if ((digit & (3*half_eps-1)) != 0 ||
1467 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1468 round_up = 1;
1469 else
1470 for (i = key_digit-1; i >= 0; i--)
1471 if (HEX_DIGIT(i) != 0) {
1472 round_up = 1;
1473 break;
1474 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001475 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 x += 2*half_eps;
1477 if (top_exp == DBL_MAX_EXP &&
1478 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1479 /* overflow corner case: pre-rounded value <
1480 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1481 goto overflow_error;
1482 }
1483 }
1484 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001485
1486 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 /* optional trailing whitespace leading to the end of the string */
1488 while (Py_ISSPACE(*s))
1489 s++;
1490 if (s != s_end)
1491 goto parse_error;
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001492 result = PyFloat_FromDouble(negate ? -x : x);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001493 if (type != &PyFloat_Type && result != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001494 Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001495 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001497
1498 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 PyErr_SetString(PyExc_OverflowError,
1500 "hexadecimal value too large to represent as a float");
1501 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001502
1503 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 PyErr_SetString(PyExc_ValueError,
1505 "invalid hexadecimal floating-point string");
1506 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001507
1508 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 PyErr_SetString(PyExc_ValueError,
1510 "hexadecimal string too long to convert");
1511 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001512}
1513
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001514/*[clinic input]
1515float.as_integer_ratio
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001516
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001517Return integer ratio.
1518
1519Return a pair of integers, whose ratio is exactly equal to the original float
1520and with a positive denominator.
1521
1522Raise OverflowError on infinities and a ValueError on NaNs.
1523
1524>>> (10.0).as_integer_ratio()
1525(10, 1)
1526>>> (0.0).as_integer_ratio()
1527(0, 1)
1528>>> (-.25).as_integer_ratio()
1529(-1, 4)
1530[clinic start generated code]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001531
Christian Heimes26855632008-01-27 23:50:43 +00001532static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001533float_as_integer_ratio_impl(PyObject *self)
1534/*[clinic end generated code: output=65f25f0d8d30a712 input=e21d08b4630c2e44]*/
Christian Heimes26855632008-01-27 23:50:43 +00001535{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001536 double self_double;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 double float_part;
1538 int exponent;
1539 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 PyObject *py_exponent = NULL;
1542 PyObject *numerator = NULL;
1543 PyObject *denominator = NULL;
1544 PyObject *result_pair = NULL;
1545 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001546
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001547 CONVERT_TO_DOUBLE(self, self_double);
Christian Heimes26855632008-01-27 23:50:43 +00001548
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001549 if (Py_IS_INFINITY(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001550 PyErr_SetString(PyExc_OverflowError,
1551 "cannot convert Infinity to integer ratio");
1552 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001554 if (Py_IS_NAN(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001555 PyErr_SetString(PyExc_ValueError,
1556 "cannot convert NaN to integer ratio");
1557 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 }
Christian Heimes26855632008-01-27 23:50:43 +00001559
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001560 float_part = frexp(self_double, &exponent); /* self_double == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1563 float_part *= 2.0;
1564 exponent--;
1565 }
1566 /* self == float_part * 2**exponent exactly and float_part is integral.
1567 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1568 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 numerator = PyLong_FromDouble(float_part);
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001571 if (numerator == NULL)
1572 goto error;
1573 denominator = PyLong_FromLong(1);
1574 if (denominator == NULL)
1575 goto error;
1576 py_exponent = PyLong_FromLong(Py_ABS(exponent));
1577 if (py_exponent == NULL)
1578 goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 /* fold in 2**exponent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 if (exponent > 0) {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001582 Py_SETREF(numerator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001583 long_methods->nb_lshift(numerator, py_exponent));
1584 if (numerator == NULL)
1585 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 }
1587 else {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001588 Py_SETREF(denominator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001589 long_methods->nb_lshift(denominator, py_exponent));
1590 if (denominator == NULL)
1591 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 }
1593
1594 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001595
Christian Heimes26855632008-01-27 23:50:43 +00001596error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 Py_XDECREF(py_exponent);
1598 Py_XDECREF(denominator);
1599 Py_XDECREF(numerator);
1600 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001601}
1602
Jeremy Hylton938ace62002-07-17 16:30:39 +00001603static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001604float_subtype_new(PyTypeObject *type, PyObject *x);
1605
1606/*[clinic input]
1607@classmethod
1608float.__new__ as float_new
Victor Stinnerc9bc2902020-10-27 02:24:34 +01001609 x: object(c_default="NULL") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001610 /
1611
1612Convert a string or number to a floating point number, if possible.
1613[clinic start generated code]*/
Guido van Rossumbef14172001-08-29 15:47:46 +00001614
Tim Peters6d6c1a32001-08-02 04:15:00 +00001615static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001616float_new_impl(PyTypeObject *type, PyObject *x)
Victor Stinnerc9bc2902020-10-27 02:24:34 +01001617/*[clinic end generated code: output=ccf1e8dc460ba6ba input=f43661b7de03e9d8]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00001618{
Victor Stinnerc9bc2902020-10-27 02:24:34 +01001619 if (type != &PyFloat_Type) {
1620 if (x == NULL) {
1621 x = _PyLong_GetZero();
1622 }
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001623 return float_subtype_new(type, x); /* Wimp out */
Victor Stinnerc9bc2902020-10-27 02:24:34 +01001624 }
1625
1626 if (x == NULL) {
1627 return PyFloat_FromDouble(0.0);
1628 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 /* If it's a string, but not a string subclass, use
1630 PyFloat_FromString. */
1631 if (PyUnicode_CheckExact(x))
1632 return PyFloat_FromString(x);
1633 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001634}
1635
Guido van Rossumbef14172001-08-29 15:47:46 +00001636/* Wimpy, slow approach to tp_new calls for subtypes of float:
1637 first create a regular float from whatever arguments we got,
1638 then allocate a subtype instance and initialize its ob_fval
1639 from the regular float. The regular float is then thrown away.
1640*/
1641static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001642float_subtype_new(PyTypeObject *type, PyObject *x)
Guido van Rossumbef14172001-08-29 15:47:46 +00001643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 assert(PyType_IsSubtype(type, &PyFloat_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001647 tmp = float_new_impl(&PyFloat_Type, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 if (tmp == NULL)
1649 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001650 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 newobj = type->tp_alloc(type, 0);
1652 if (newobj == NULL) {
1653 Py_DECREF(tmp);
1654 return NULL;
1655 }
1656 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1657 Py_DECREF(tmp);
1658 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001659}
1660
Dennis Sweeneye8acc352020-09-28 20:55:52 -04001661static PyObject *
1662float_vectorcall(PyObject *type, PyObject * const*args,
1663 size_t nargsf, PyObject *kwnames)
1664{
1665 if (!_PyArg_NoKwnames("float", kwnames)) {
1666 return NULL;
1667 }
1668
1669 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
1670 if (!_PyArg_CheckPositional("float", nargs, 0, 1)) {
1671 return NULL;
1672 }
1673
Victor Stinnerc9bc2902020-10-27 02:24:34 +01001674 PyObject *x = nargs >= 1 ? args[0] : NULL;
Dennis Sweeneye8acc352020-09-28 20:55:52 -04001675 return float_new_impl((PyTypeObject *)type, x);
1676}
1677
1678
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001679/*[clinic input]
1680float.__getnewargs__
1681[clinic start generated code]*/
1682
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001683static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001684float___getnewargs___impl(PyObject *self)
1685/*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001686{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001687 return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001688}
1689
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001690/* this is for the benefit of the pack/unpack routines below */
1691
1692typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001694} float_format_type;
1695
1696static float_format_type double_format, float_format;
1697static float_format_type detected_double_format, detected_float_format;
1698
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001699/*[clinic input]
1700@classmethod
1701float.__getformat__
1702
1703 typestr: str
1704 Must be 'double' or 'float'.
1705 /
1706
1707You probably don't want to use this function.
1708
1709It exists mainly to be used in Python's test suite.
1710
1711This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
1712little-endian' best describes the format of floating point numbers used by the
1713C type named by typestr.
1714[clinic start generated code]*/
1715
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001716static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001717float___getformat___impl(PyTypeObject *type, const char *typestr)
1718/*[clinic end generated code: output=2bfb987228cc9628 input=d5a52600f835ad67]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001721
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001722 if (strcmp(typestr, "double") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 r = double_format;
1724 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001725 else if (strcmp(typestr, "float") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 r = float_format;
1727 }
1728 else {
1729 PyErr_SetString(PyExc_ValueError,
1730 "__getformat__() argument 1 must be "
1731 "'double' or 'float'");
1732 return NULL;
1733 }
1734
1735 switch (r) {
1736 case unknown_format:
1737 return PyUnicode_FromString("unknown");
1738 case ieee_little_endian_format:
1739 return PyUnicode_FromString("IEEE, little-endian");
1740 case ieee_big_endian_format:
1741 return PyUnicode_FromString("IEEE, big-endian");
1742 default:
Victor Stinner04394df2019-11-18 17:39:48 +01001743 PyErr_SetString(PyExc_RuntimeError,
1744 "insane float_format or double_format");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 return NULL;
1746 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001747}
1748
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001749/*[clinic input]
1750@classmethod
1751float.__set_format__
1752
1753 typestr: str
1754 Must be 'double' or 'float'.
1755 fmt: str
1756 Must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian',
1757 and in addition can only be one of the latter two if it appears to
1758 match the underlying C reality.
1759 /
1760
1761You probably don't want to use this function.
1762
1763It exists mainly to be used in Python's test suite.
1764
1765Override the automatic determination of C-level floating point type.
1766This affects how floats are converted to and from binary strings.
1767[clinic start generated code]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001768
1769static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001770float___set_format___impl(PyTypeObject *type, const char *typestr,
1771 const char *fmt)
1772/*[clinic end generated code: output=504460f5dc85acbd input=5306fa2b81a997e4]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 float_format_type f;
1775 float_format_type detected;
1776 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 if (strcmp(typestr, "double") == 0) {
1779 p = &double_format;
1780 detected = detected_double_format;
1781 }
1782 else if (strcmp(typestr, "float") == 0) {
1783 p = &float_format;
1784 detected = detected_float_format;
1785 }
1786 else {
1787 PyErr_SetString(PyExc_ValueError,
1788 "__setformat__() argument 1 must "
1789 "be 'double' or 'float'");
1790 return NULL;
1791 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001792
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001793 if (strcmp(fmt, "unknown") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 f = unknown_format;
1795 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001796 else if (strcmp(fmt, "IEEE, little-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 f = ieee_little_endian_format;
1798 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001799 else if (strcmp(fmt, "IEEE, big-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 f = ieee_big_endian_format;
1801 }
1802 else {
1803 PyErr_SetString(PyExc_ValueError,
1804 "__setformat__() argument 2 must be "
1805 "'unknown', 'IEEE, little-endian' or "
1806 "'IEEE, big-endian'");
1807 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 if (f != unknown_format && f != detected) {
1812 PyErr_Format(PyExc_ValueError,
1813 "can only set %s format to 'unknown' or the "
1814 "detected platform value", typestr);
1815 return NULL;
1816 }
1817
1818 *p = f;
1819 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001820}
1821
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001822static PyObject *
1823float_getreal(PyObject *v, void *closure)
1824{
1825 return float_float(v);
1826}
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001827
Guido van Rossumb43daf72007-08-01 18:08:08 +00001828static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001829float_getimag(PyObject *v, void *closure)
Guido van Rossumb43daf72007-08-01 18:08:08 +00001830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001832}
1833
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001834/*[clinic input]
1835float.__format__
1836
1837 format_spec: unicode
1838 /
1839
1840Formats the float according to format_spec.
1841[clinic start generated code]*/
1842
Eric Smith8c663262007-08-25 02:26:07 +00001843static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001844float___format___impl(PyObject *self, PyObject *format_spec)
1845/*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/
Eric Smith8c663262007-08-25 02:26:07 +00001846{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001847 _PyUnicodeWriter writer;
1848 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001849
Victor Stinner8f674cc2013-04-17 23:02:17 +02001850 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001851 ret = _PyFloat_FormatAdvancedWriter(
1852 &writer,
1853 self,
1854 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1855 if (ret == -1) {
1856 _PyUnicodeWriter_Dealloc(&writer);
1857 return NULL;
1858 }
1859 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001860}
1861
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001862static PyMethodDef float_methods[] = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001863 FLOAT_CONJUGATE_METHODDEF
1864 FLOAT___TRUNC___METHODDEF
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +03001865 FLOAT___FLOOR___METHODDEF
1866 FLOAT___CEIL___METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001867 FLOAT___ROUND___METHODDEF
1868 FLOAT_AS_INTEGER_RATIO_METHODDEF
1869 FLOAT_FROMHEX_METHODDEF
1870 FLOAT_HEX_METHODDEF
1871 FLOAT_IS_INTEGER_METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001872 FLOAT___GETNEWARGS___METHODDEF
1873 FLOAT___GETFORMAT___METHODDEF
1874 FLOAT___SET_FORMAT___METHODDEF
1875 FLOAT___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001877};
1878
Guido van Rossumb43daf72007-08-01 18:08:08 +00001879static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 {"real",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001881 float_getreal, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001882 "the real part of a complex number",
1883 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 {"imag",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001885 float_getimag, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001886 "the imaginary part of a complex number",
1887 NULL},
1888 {NULL} /* Sentinel */
1889};
1890
Tim Peters6d6c1a32001-08-02 04:15:00 +00001891
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001892static PyNumberMethods float_as_number = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001893 float_add, /* nb_add */
1894 float_sub, /* nb_subtract */
1895 float_mul, /* nb_multiply */
1896 float_rem, /* nb_remainder */
1897 float_divmod, /* nb_divmod */
1898 float_pow, /* nb_power */
1899 (unaryfunc)float_neg, /* nb_negative */
1900 float_float, /* nb_positive */
1901 (unaryfunc)float_abs, /* nb_absolute */
1902 (inquiry)float_bool, /* nb_bool */
1903 0, /* nb_invert */
1904 0, /* nb_lshift */
1905 0, /* nb_rshift */
1906 0, /* nb_and */
1907 0, /* nb_xor */
1908 0, /* nb_or */
1909 float___trunc___impl, /* nb_int */
1910 0, /* nb_reserved */
1911 float_float, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 0, /* nb_inplace_add */
1913 0, /* nb_inplace_subtract */
1914 0, /* nb_inplace_multiply */
1915 0, /* nb_inplace_remainder */
1916 0, /* nb_inplace_power */
1917 0, /* nb_inplace_lshift */
1918 0, /* nb_inplace_rshift */
1919 0, /* nb_inplace_and */
1920 0, /* nb_inplace_xor */
1921 0, /* nb_inplace_or */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001922 float_floor_div, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 float_div, /* nb_true_divide */
1924 0, /* nb_inplace_floor_divide */
1925 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001926};
1927
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001928PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1930 "float",
1931 sizeof(PyFloatObject),
1932 0,
1933 (destructor)float_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001934 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 0, /* tp_getattr */
1936 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001937 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 (reprfunc)float_repr, /* tp_repr */
1939 &float_as_number, /* tp_as_number */
1940 0, /* tp_as_sequence */
1941 0, /* tp_as_mapping */
1942 (hashfunc)float_hash, /* tp_hash */
1943 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001944 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 PyObject_GenericGetAttr, /* tp_getattro */
1946 0, /* tp_setattro */
1947 0, /* tp_as_buffer */
Brandt Bucher145bf262021-02-26 14:51:55 -08001948 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
1949 _Py_TPFLAGS_MATCH_SELF, /* tp_flags */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001950 float_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 0, /* tp_traverse */
1952 0, /* tp_clear */
1953 float_richcompare, /* tp_richcompare */
1954 0, /* tp_weaklistoffset */
1955 0, /* tp_iter */
1956 0, /* tp_iternext */
1957 float_methods, /* tp_methods */
1958 0, /* tp_members */
1959 float_getset, /* tp_getset */
1960 0, /* tp_base */
1961 0, /* tp_dict */
1962 0, /* tp_descr_get */
1963 0, /* tp_descr_set */
1964 0, /* tp_dictoffset */
1965 0, /* tp_init */
1966 0, /* tp_alloc */
1967 float_new, /* tp_new */
Dennis Sweeneye8acc352020-09-28 20:55:52 -04001968 .tp_vectorcall = (vectorcallfunc)float_vectorcall,
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001969};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001970
Victor Stinner1c8f0592013-07-22 22:24:54 +02001971int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001972_PyFloat_Init(void)
1973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 /* We attempt to determine if this machine is using IEEE
1975 floating point formats by peering at the bits of some
1976 carefully chosen values. If it looks like we are on an
1977 IEEE platform, the float packing/unpacking routines can
1978 just copy bits, if not they resort to arithmetic & shifts
1979 and masks. The shifts & masks approach works on all finite
1980 values, but what happens to infinities, NaNs and signed
1981 zeroes on packing is an accident, and attempting to unpack
1982 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 Note that if we're on some whacked-out platform which uses
1985 IEEE formats but isn't strictly little-endian or big-
1986 endian, we will fall back to the portable shifts & masks
1987 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001988
1989#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 {
1991 double x = 9006104071832581.0;
1992 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1993 detected_double_format = ieee_big_endian_format;
1994 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1995 detected_double_format = ieee_little_endian_format;
1996 else
1997 detected_double_format = unknown_format;
1998 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001999#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002001#endif
2002
2003#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 {
2005 float y = 16711938.0;
2006 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
2007 detected_float_format = ieee_big_endian_format;
2008 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
2009 detected_float_format = ieee_little_endian_format;
2010 else
2011 detected_float_format = unknown_format;
2012 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002013#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002015#endif
2016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 double_format = detected_double_format;
2018 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002021 if (FloatInfoType.tp_name == NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01002022 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02002023 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01002024 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002025 }
2026 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002027}
2028
Victor Stinnerae00a5a2020-04-29 02:29:20 +02002029void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002030_PyFloat_ClearFreeList(PyInterpreterState *interp)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002031{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002032 struct _Py_float_state *state = &interp->float_state;
Victor Stinnerbcb19832020-06-08 02:14:47 +02002033 PyFloatObject *f = state->free_list;
2034 while (f != NULL) {
2035 PyFloatObject *next = (PyFloatObject*) Py_TYPE(f);
Victor Stinner32bd68c2020-12-01 10:37:39 +01002036 PyObject_Free(f);
Victor Stinnerbcb19832020-06-08 02:14:47 +02002037 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 }
Victor Stinner2ba59372020-06-05 00:50:05 +02002039 state->free_list = NULL;
2040 state->numfree = 0;
Christian Heimes15ebc882008-02-04 18:48:49 +00002041}
2042
2043void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002044_PyFloat_Fini(PyInterpreterState *interp)
Christian Heimes15ebc882008-02-04 18:48:49 +00002045{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002046 _PyFloat_ClearFreeList(interp);
Victor Stinnerbcb19832020-06-08 02:14:47 +02002047#ifdef Py_DEBUG
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002048 struct _Py_float_state *state = &interp->float_state;
Victor Stinnerbcb19832020-06-08 02:14:47 +02002049 state->numfree = -1;
2050#endif
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002051}
Tim Peters9905b942003-03-20 20:53:32 +00002052
David Malcolm49526f42012-06-22 14:55:41 -04002053/* Print summary info about the state of the optimized allocator */
2054void
2055_PyFloat_DebugMallocStats(FILE *out)
2056{
Victor Stinner522691c2020-06-23 16:40:40 +02002057 struct _Py_float_state *state = get_float_state();
David Malcolm49526f42012-06-22 14:55:41 -04002058 _PyDebugAllocatorStats(out,
2059 "free PyFloatObject",
Victor Stinner2ba59372020-06-05 00:50:05 +02002060 state->numfree, sizeof(PyFloatObject));
David Malcolm49526f42012-06-22 14:55:41 -04002061}
2062
2063
Tim Peters9905b942003-03-20 20:53:32 +00002064/*----------------------------------------------------------------------------
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002065 * _PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h.
2066 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
2067 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
2068 * We use:
2069 * bits = (unsigned short)f; Note the truncation
2070 * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
2071 * bits++;
2072 * }
Tim Peters9905b942003-03-20 20:53:32 +00002073 */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002074
2075int
2076_PyFloat_Pack2(double x, unsigned char *p, int le)
2077{
2078 unsigned char sign;
2079 int e;
2080 double f;
2081 unsigned short bits;
2082 int incr = 1;
2083
2084 if (x == 0.0) {
2085 sign = (copysign(1.0, x) == -1.0);
2086 e = 0;
2087 bits = 0;
2088 }
2089 else if (Py_IS_INFINITY(x)) {
2090 sign = (x < 0.0);
2091 e = 0x1f;
2092 bits = 0;
2093 }
2094 else if (Py_IS_NAN(x)) {
2095 /* There are 2046 distinct half-precision NaNs (1022 signaling and
2096 1024 quiet), but there are only two quiet NaNs that don't arise by
2097 quieting a signaling NaN; we get those by setting the topmost bit
2098 of the fraction field and clearing all other fraction bits. We
2099 choose the one with the appropriate sign. */
2100 sign = (copysign(1.0, x) == -1.0);
2101 e = 0x1f;
2102 bits = 512;
2103 }
2104 else {
2105 sign = (x < 0.0);
2106 if (sign) {
2107 x = -x;
2108 }
2109
2110 f = frexp(x, &e);
2111 if (f < 0.5 || f >= 1.0) {
2112 PyErr_SetString(PyExc_SystemError,
2113 "frexp() result out of range");
2114 return -1;
2115 }
2116
2117 /* Normalize f to be in the range [1.0, 2.0) */
2118 f *= 2.0;
2119 e--;
2120
2121 if (e >= 16) {
2122 goto Overflow;
2123 }
2124 else if (e < -25) {
2125 /* |x| < 2**-25. Underflow to zero. */
2126 f = 0.0;
2127 e = 0;
2128 }
2129 else if (e < -14) {
2130 /* |x| < 2**-14. Gradual underflow */
2131 f = ldexp(f, 14 + e);
2132 e = 0;
2133 }
2134 else /* if (!(e == 0 && f == 0.0)) */ {
2135 e += 15;
2136 f -= 1.0; /* Get rid of leading 1 */
2137 }
2138
2139 f *= 1024.0; /* 2**10 */
2140 /* Round to even */
2141 bits = (unsigned short)f; /* Note the truncation */
2142 assert(bits < 1024);
2143 assert(e < 31);
2144 if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2145 ++bits;
2146 if (bits == 1024) {
2147 /* The carry propagated out of a string of 10 1 bits. */
2148 bits = 0;
2149 ++e;
2150 if (e == 31)
2151 goto Overflow;
2152 }
2153 }
2154 }
2155
2156 bits |= (e << 10) | (sign << 15);
2157
2158 /* Write out result. */
2159 if (le) {
2160 p += 1;
2161 incr = -1;
2162 }
2163
2164 /* First byte */
2165 *p = (unsigned char)((bits >> 8) & 0xFF);
2166 p += incr;
2167
2168 /* Second byte */
2169 *p = (unsigned char)(bits & 0xFF);
2170
2171 return 0;
2172
2173 Overflow:
2174 PyErr_SetString(PyExc_OverflowError,
2175 "float too large to pack with e format");
2176 return -1;
2177}
2178
Tim Peters9905b942003-03-20 20:53:32 +00002179int
2180_PyFloat_Pack4(double x, unsigned char *p, int le)
2181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 if (float_format == unknown_format) {
2183 unsigned char sign;
2184 int e;
2185 double f;
2186 unsigned int fbits;
2187 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 if (le) {
2190 p += 3;
2191 incr = -1;
2192 }
Tim Peters9905b942003-03-20 20:53:32 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 if (x < 0) {
2195 sign = 1;
2196 x = -x;
2197 }
2198 else
2199 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 /* Normalize f to be in the range [1.0, 2.0) */
2204 if (0.5 <= f && f < 1.0) {
2205 f *= 2.0;
2206 e--;
2207 }
2208 else if (f == 0.0)
2209 e = 0;
2210 else {
2211 PyErr_SetString(PyExc_SystemError,
2212 "frexp() result out of range");
2213 return -1;
2214 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 if (e >= 128)
2217 goto Overflow;
2218 else if (e < -126) {
2219 /* Gradual underflow */
2220 f = ldexp(f, 126 + e);
2221 e = 0;
2222 }
2223 else if (!(e == 0 && f == 0.0)) {
2224 e += 127;
2225 f -= 1.0; /* Get rid of leading 1 */
2226 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 f *= 8388608.0; /* 2**23 */
2229 fbits = (unsigned int)(f + 0.5); /* Round */
2230 assert(fbits <= 8388608);
2231 if (fbits >> 23) {
2232 /* The carry propagated out of a string of 23 1 bits. */
2233 fbits = 0;
2234 ++e;
2235 if (e >= 255)
2236 goto Overflow;
2237 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 /* First byte */
2240 *p = (sign << 7) | (e >> 1);
2241 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 /* Second byte */
2244 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2245 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 /* Third byte */
2248 *p = (fbits >> 8) & 0xFF;
2249 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 /* Fourth byte */
2252 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 /* Done */
2255 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 }
2258 else {
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002259 float y = (float)x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002261
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002262 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002264
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002265 unsigned char s[sizeof(float)];
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002266 memcpy(s, &y, sizeof(float));
2267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 if ((float_format == ieee_little_endian_format && !le)
2269 || (float_format == ieee_big_endian_format && le)) {
2270 p += 3;
2271 incr = -1;
2272 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 for (i = 0; i < 4; i++) {
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002275 *p = s[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 p += incr;
2277 }
2278 return 0;
2279 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002280 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 PyErr_SetString(PyExc_OverflowError,
2282 "float too large to pack with f format");
2283 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002284}
2285
2286int
2287_PyFloat_Pack8(double x, unsigned char *p, int le)
2288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 if (double_format == unknown_format) {
2290 unsigned char sign;
2291 int e;
2292 double f;
2293 unsigned int fhi, flo;
2294 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 if (le) {
2297 p += 7;
2298 incr = -1;
2299 }
Tim Peters9905b942003-03-20 20:53:32 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 if (x < 0) {
2302 sign = 1;
2303 x = -x;
2304 }
2305 else
2306 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* Normalize f to be in the range [1.0, 2.0) */
2311 if (0.5 <= f && f < 1.0) {
2312 f *= 2.0;
2313 e--;
2314 }
2315 else if (f == 0.0)
2316 e = 0;
2317 else {
2318 PyErr_SetString(PyExc_SystemError,
2319 "frexp() result out of range");
2320 return -1;
2321 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 if (e >= 1024)
2324 goto Overflow;
2325 else if (e < -1022) {
2326 /* Gradual underflow */
2327 f = ldexp(f, 1022 + e);
2328 e = 0;
2329 }
2330 else if (!(e == 0 && f == 0.0)) {
2331 e += 1023;
2332 f -= 1.0; /* Get rid of leading 1 */
2333 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2336 f *= 268435456.0; /* 2**28 */
2337 fhi = (unsigned int)f; /* Truncate */
2338 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 f -= (double)fhi;
2341 f *= 16777216.0; /* 2**24 */
2342 flo = (unsigned int)(f + 0.5); /* Round */
2343 assert(flo <= 16777216);
2344 if (flo >> 24) {
2345 /* The carry propagated out of a string of 24 1 bits. */
2346 flo = 0;
2347 ++fhi;
2348 if (fhi >> 28) {
2349 /* And it also progagated out of the next 28 bits. */
2350 fhi = 0;
2351 ++e;
2352 if (e >= 2047)
2353 goto Overflow;
2354 }
2355 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 /* First byte */
2358 *p = (sign << 7) | (e >> 4);
2359 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 /* Second byte */
2362 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2363 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 /* Third byte */
2366 *p = (fhi >> 16) & 0xFF;
2367 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 /* Fourth byte */
2370 *p = (fhi >> 8) & 0xFF;
2371 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 /* Fifth byte */
2374 *p = fhi & 0xFF;
2375 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 /* Sixth byte */
2378 *p = (flo >> 16) & 0xFF;
2379 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 /* Seventh byte */
2382 *p = (flo >> 8) & 0xFF;
2383 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 /* Eighth byte */
2386 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002387 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 /* Done */
2390 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 Overflow:
2393 PyErr_SetString(PyExc_OverflowError,
2394 "float too large to pack with d format");
2395 return -1;
2396 }
2397 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002398 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 if ((double_format == ieee_little_endian_format && !le)
2402 || (double_format == ieee_big_endian_format && le)) {
2403 p += 7;
2404 incr = -1;
2405 }
2406
2407 for (i = 0; i < 8; i++) {
2408 *p = *s++;
2409 p += incr;
2410 }
2411 return 0;
2412 }
Tim Peters9905b942003-03-20 20:53:32 +00002413}
2414
2415double
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002416_PyFloat_Unpack2(const unsigned char *p, int le)
2417{
2418 unsigned char sign;
2419 int e;
2420 unsigned int f;
2421 double x;
2422 int incr = 1;
2423
2424 if (le) {
2425 p += 1;
2426 incr = -1;
2427 }
2428
2429 /* First byte */
2430 sign = (*p >> 7) & 1;
2431 e = (*p & 0x7C) >> 2;
2432 f = (*p & 0x03) << 8;
2433 p += incr;
2434
2435 /* Second byte */
2436 f |= *p;
2437
2438 if (e == 0x1f) {
2439#ifdef PY_NO_SHORT_FLOAT_REPR
2440 if (f == 0) {
2441 /* Infinity */
2442 return sign ? -Py_HUGE_VAL : Py_HUGE_VAL;
2443 }
2444 else {
2445 /* NaN */
2446#ifdef Py_NAN
2447 return sign ? -Py_NAN : Py_NAN;
2448#else
2449 PyErr_SetString(
2450 PyExc_ValueError,
2451 "can't unpack IEEE 754 NaN "
2452 "on platform that does not support NaNs");
2453 return -1;
2454#endif /* #ifdef Py_NAN */
2455 }
2456#else
2457 if (f == 0) {
2458 /* Infinity */
2459 return _Py_dg_infinity(sign);
2460 }
2461 else {
2462 /* NaN */
2463 return _Py_dg_stdnan(sign);
2464 }
2465#endif /* #ifdef PY_NO_SHORT_FLOAT_REPR */
2466 }
2467
2468 x = (double)f / 1024.0;
2469
2470 if (e == 0) {
2471 e = -14;
2472 }
2473 else {
2474 x += 1.0;
2475 e -= 15;
2476 }
2477 x = ldexp(x, e);
2478
2479 if (sign)
2480 x = -x;
2481
2482 return x;
2483}
2484
2485double
Tim Peters9905b942003-03-20 20:53:32 +00002486_PyFloat_Unpack4(const unsigned char *p, int le)
2487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 if (float_format == unknown_format) {
2489 unsigned char sign;
2490 int e;
2491 unsigned int f;
2492 double x;
2493 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 if (le) {
2496 p += 3;
2497 incr = -1;
2498 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 /* First byte */
2501 sign = (*p >> 7) & 1;
2502 e = (*p & 0x7F) << 1;
2503 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 /* Second byte */
2506 e |= (*p >> 7) & 1;
2507 f = (*p & 0x7F) << 16;
2508 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 if (e == 255) {
2511 PyErr_SetString(
2512 PyExc_ValueError,
2513 "can't unpack IEEE 754 special value "
2514 "on non-IEEE platform");
2515 return -1;
2516 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 /* Third byte */
2519 f |= *p << 8;
2520 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 /* Fourth byte */
2523 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 /* XXX This sadly ignores Inf/NaN issues */
2528 if (e == 0)
2529 e = -126;
2530 else {
2531 x += 1.0;
2532 e -= 127;
2533 }
2534 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 if (sign)
2537 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 return x;
2540 }
2541 else {
2542 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 if ((float_format == ieee_little_endian_format && !le)
2545 || (float_format == ieee_big_endian_format && le)) {
2546 char buf[4];
2547 char *d = &buf[3];
2548 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 for (i = 0; i < 4; i++) {
2551 *d-- = *p++;
2552 }
2553 memcpy(&x, buf, 4);
2554 }
2555 else {
2556 memcpy(&x, p, 4);
2557 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 return x;
2560 }
Tim Peters9905b942003-03-20 20:53:32 +00002561}
2562
2563double
2564_PyFloat_Unpack8(const unsigned char *p, int le)
2565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 if (double_format == unknown_format) {
2567 unsigned char sign;
2568 int e;
2569 unsigned int fhi, flo;
2570 double x;
2571 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 if (le) {
2574 p += 7;
2575 incr = -1;
2576 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 /* First byte */
2579 sign = (*p >> 7) & 1;
2580 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 /* Second byte */
2585 e |= (*p >> 4) & 0xF;
2586 fhi = (*p & 0xF) << 24;
2587 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 if (e == 2047) {
2590 PyErr_SetString(
2591 PyExc_ValueError,
2592 "can't unpack IEEE 754 special value "
2593 "on non-IEEE platform");
2594 return -1.0;
2595 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 /* Third byte */
2598 fhi |= *p << 16;
2599 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 /* Fourth byte */
2602 fhi |= *p << 8;
2603 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 /* Fifth byte */
2606 fhi |= *p;
2607 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 /* Sixth byte */
2610 flo = *p << 16;
2611 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 /* Seventh byte */
2614 flo |= *p << 8;
2615 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 /* Eighth byte */
2618 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2621 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 if (e == 0)
2624 e = -1022;
2625 else {
2626 x += 1.0;
2627 e -= 1023;
2628 }
2629 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 if (sign)
2632 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 return x;
2635 }
2636 else {
2637 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 if ((double_format == ieee_little_endian_format && !le)
2640 || (double_format == ieee_big_endian_format && le)) {
2641 char buf[8];
2642 char *d = &buf[7];
2643 int i;
2644
2645 for (i = 0; i < 8; i++) {
2646 *d-- = *p++;
2647 }
2648 memcpy(&x, buf, 8);
2649 }
2650 else {
2651 memcpy(&x, p, 8);
2652 }
2653
2654 return x;
2655 }
Tim Peters9905b942003-03-20 20:53:32 +00002656}