blob: 9f5014092cf20a6124572c006a8775b6fb137c96 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Float object implementation */
2
Guido van Rossum2a9096b1990-10-21 22:15:08 +00003/* XXX There should be overflow checks here, but it's hard to check
4 for any kind of float exception without losing portability. */
5
Guido van Rossumc0b618a1997-05-02 03:12:38 +00006#include "Python.h"
Victor Stinnere9e7d282020-02-12 22:54:42 +01007#include "pycore_dtoa.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Guido van Rossum3f5da241990-12-20 15:06:42 +00009#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000010#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Serhiy Storchakab5c51d32017-03-11 09:21:05 +020012/*[clinic input]
13class float "PyObject *" "&PyFloat_Type"
14[clinic start generated code]*/
15/*[clinic end generated code: output=da39a3ee5e6b4b0d input=dd0003f68f144284]*/
16
17#include "clinic/floatobject.c.h"
Guido van Rossum6923e131990-11-02 17:50:43 +000018
Mark Dickinsond19052c2010-06-27 18:19:09 +000019/* Special free list
Mark Dickinsond19052c2010-06-27 18:19:09 +000020 free_list is a singly-linked list of available PyFloatObjects, linked
21 via abuse of their ob_type members.
22*/
23
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000024#ifndef PyFloat_MAXFREELIST
25#define PyFloat_MAXFREELIST 100
26#endif
27static int numfree = 0;
Guido van Rossum3fce8831999-03-12 19:43:17 +000028static PyFloatObject *free_list = NULL;
29
Christian Heimes93852662007-12-01 12:22:32 +000030double
31PyFloat_GetMax(void)
32{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000034}
35
36double
37PyFloat_GetMin(void)
38{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000040}
41
Christian Heimesd32ed6f2008-01-14 18:49:24 +000042static PyTypeObject FloatInfoType;
43
44PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000045"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000046\n\
Raymond Hettinger71170742019-09-11 07:17:32 -070047A named tuple holding information about the float type. It contains low level\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000048information about the precision and internal representation. Please study\n\
49your system's :file:`float.h` for more information.");
50
51static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 {"max", "DBL_MAX -- maximum representable finite float"},
53 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
54 "is representable"},
55 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
56 "is representable"},
Stefano Taschini0301c9b2018-03-26 11:41:30 +020057 {"min", "DBL_MIN -- Minimum positive normalized float"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
59 "is a normalized float"},
60 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
61 "a normalized"},
62 {"dig", "DBL_DIG -- digits"},
63 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
64 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
65 "representable float"},
66 {"radix", "FLT_RADIX -- radix of exponent"},
Stefano Taschini0301c9b2018-03-26 11:41:30 +020067 {"rounds", "FLT_ROUNDS -- rounding mode"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +000069};
70
71static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 "sys.float_info", /* name */
73 floatinfo__doc__, /* doc */
74 floatinfo_fields, /* fields */
75 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +000076};
77
Christian Heimes93852662007-12-01 12:22:32 +000078PyObject *
79PyFloat_GetInfo(void)
80{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 PyObject* floatinfo;
82 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +000083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 floatinfo = PyStructSequence_New(&FloatInfoType);
85 if (floatinfo == NULL) {
86 return NULL;
87 }
Christian Heimes93852662007-12-01 12:22:32 +000088
Christian Heimesd32ed6f2008-01-14 18:49:24 +000089#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +000091#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +000093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 SetDblFlag(DBL_MAX);
95 SetIntFlag(DBL_MAX_EXP);
96 SetIntFlag(DBL_MAX_10_EXP);
97 SetDblFlag(DBL_MIN);
98 SetIntFlag(DBL_MIN_EXP);
99 SetIntFlag(DBL_MIN_10_EXP);
100 SetIntFlag(DBL_DIG);
101 SetIntFlag(DBL_MANT_DIG);
102 SetDblFlag(DBL_EPSILON);
103 SetIntFlag(FLT_RADIX);
104 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000105#undef SetIntFlag
106#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107
108 if (PyErr_Occurred()) {
109 Py_CLEAR(floatinfo);
110 return NULL;
111 }
112 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000113}
114
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000116PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000117{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200118 PyFloatObject *op = free_list;
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000119 if (op != NULL) {
120 free_list = (PyFloatObject *) Py_TYPE(op);
121 numfree--;
122 } else {
123 op = (PyFloatObject*) PyObject_MALLOC(sizeof(PyFloatObject));
124 if (!op)
125 return PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 }
127 /* Inline PyObject_New */
Victor Stinnerb509d522018-11-23 14:27:38 +0100128 (void)PyObject_INIT(op, &PyFloat_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 op->ob_fval = fval;
130 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131}
132
Brett Cannona721aba2016-09-09 14:57:09 -0700133static PyObject *
134float_from_string_inner(const char *s, Py_ssize_t len, void *obj)
135{
136 double x;
137 const char *end;
138 const char *last = s + len;
139 /* strip space */
140 while (s < last && Py_ISSPACE(*s)) {
141 s++;
142 }
143
144 while (s < last - 1 && Py_ISSPACE(last[-1])) {
145 last--;
146 }
147
148 /* We don't care about overflow or underflow. If the platform
149 * supports them, infinities and signed zeroes (on underflow) are
150 * fine. */
151 x = PyOS_string_to_double(s, (char **)&end, NULL);
152 if (end != last) {
153 PyErr_Format(PyExc_ValueError,
154 "could not convert string to float: "
155 "%R", obj);
156 return NULL;
157 }
158 else if (x == -1.0 && PyErr_Occurred()) {
159 return NULL;
160 }
161 else {
162 return PyFloat_FromDouble(x);
163 }
164}
165
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000166PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000167PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000168{
Brett Cannona721aba2016-09-09 14:57:09 -0700169 const char *s;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000170 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 Py_ssize_t len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200172 Py_buffer view = {NULL, NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200176 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000178 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200179 assert(PyUnicode_IS_ASCII(s_buffer));
180 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200181 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200182 assert(s != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000184 else if (PyBytes_Check(v)) {
185 s = PyBytes_AS_STRING(v);
186 len = PyBytes_GET_SIZE(v);
187 }
188 else if (PyByteArray_Check(v)) {
189 s = PyByteArray_AS_STRING(v);
190 len = PyByteArray_GET_SIZE(v);
191 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200192 else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
193 s = (const char *)view.buf;
194 len = view.len;
Martin Pantereeb896c2015-11-07 02:32:21 +0000195 /* Copy to NUL-terminated buffer. */
196 s_buffer = PyBytes_FromStringAndSize(s, len);
197 if (s_buffer == NULL) {
198 PyBuffer_Release(&view);
199 return NULL;
200 }
201 s = PyBytes_AS_STRING(s_buffer);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200202 }
203 else {
Ezio Melottia5b95992013-11-07 19:18:34 +0200204 PyErr_Format(PyExc_TypeError,
205 "float() argument must be a string or a number, not '%.200s'",
206 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 return NULL;
208 }
Brett Cannona721aba2016-09-09 14:57:09 -0700209 result = _Py_string_to_number_with_underscores(s, len, "float", v, v,
210 float_from_string_inner);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200211 PyBuffer_Release(&view);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000212 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000214}
215
Guido van Rossum234f9421993-06-17 12:35:49 +0000216static void
Fred Drakefd99de62000-07-09 05:02:18 +0000217float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 if (PyFloat_CheckExact(op)) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000220 if (numfree >= PyFloat_MAXFREELIST) {
221 PyObject_FREE(op);
222 return;
223 }
224 numfree++;
Victor Stinnerd2ec81a2020-02-07 09:17:07 +0100225 Py_SET_TYPE(op, (PyTypeObject *)free_list);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 free_list = op;
227 }
228 else
229 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000230}
231
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000232double
Fred Drakefd99de62000-07-09 05:02:18 +0000233PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 PyNumberMethods *nb;
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300236 PyObject *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 if (op == NULL) {
240 PyErr_BadArgument();
241 return -1;
242 }
Tim Petersd2364e82001-11-01 20:09:42 +0000243
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300244 if (PyFloat_Check(op)) {
245 return PyFloat_AS_DOUBLE(op);
246 }
247
248 nb = Py_TYPE(op)->tp_as_number;
249 if (nb == NULL || nb->nb_float == NULL) {
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300250 if (nb && nb->nb_index) {
251 PyObject *res = PyNumber_Index(op);
252 if (!res) {
253 return -1;
254 }
255 double val = PyLong_AsDouble(res);
256 Py_DECREF(res);
257 return val;
258 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300259 PyErr_Format(PyExc_TypeError, "must be real number, not %.50s",
Victor Stinner58ac7002020-02-07 03:04:21 +0100260 Py_TYPE(op)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 return -1;
262 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000263
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300264 res = (*nb->nb_float) (op);
265 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 return -1;
267 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300268 if (!PyFloat_CheckExact(res)) {
269 if (!PyFloat_Check(res)) {
270 PyErr_Format(PyExc_TypeError,
271 "%.50s.__float__ returned non-float (type %.50s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100272 Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name);
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300273 Py_DECREF(res);
274 return -1;
275 }
276 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
277 "%.50s.__float__ returned non-float (type %.50s). "
278 "The ability to return an instance of a strict subclass of float "
279 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner58ac7002020-02-07 03:04:21 +0100280 Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name)) {
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300281 Py_DECREF(res);
282 return -1;
283 }
284 }
Tim Petersd2364e82001-11-01 20:09:42 +0000285
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300286 val = PyFloat_AS_DOUBLE(res);
287 Py_DECREF(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000289}
290
Neil Schemenauer32117e52001-01-04 01:44:34 +0000291/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000292 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000293 set to NULL, and the function invoking this macro returns NULL. If
Serhiy Storchaka95949422013-08-27 19:40:23 +0300294 obj is not of float or int type, Py_NotImplemented is incref'ed,
Tim Peters77d8a4f2001-12-11 20:31:34 +0000295 stored in obj, and returned from the function invoking this macro.
296*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297#define CONVERT_TO_DOUBLE(obj, dbl) \
298 if (PyFloat_Check(obj)) \
299 dbl = PyFloat_AS_DOUBLE(obj); \
300 else if (convert_to_double(&(obj), &(dbl)) < 0) \
301 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000302
Eric Smith0923d1d2009-04-16 20:16:10 +0000303/* Methods */
304
Neil Schemenauer32117e52001-01-04 01:44:34 +0000305static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000306convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000307{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200308 PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (PyLong_Check(obj)) {
311 *dbl = PyLong_AsDouble(obj);
312 if (*dbl == -1.0 && PyErr_Occurred()) {
313 *v = NULL;
314 return -1;
315 }
316 }
317 else {
318 Py_INCREF(Py_NotImplemented);
319 *v = Py_NotImplemented;
320 return -1;
321 }
322 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000323}
324
Eric Smith0923d1d2009-04-16 20:16:10 +0000325static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000326float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000327{
328 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200329 char *buf;
330
331 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
332 'r', 0,
333 Py_DTSF_ADD_DOT_0,
334 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000335 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000336 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200337 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000338 PyMem_Free(buf);
339 return result;
340}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000341
Tim Peters307fa782004-09-23 08:06:40 +0000342/* Comparison is pretty much a nightmare. When comparing float to float,
343 * we do it as straightforwardly (and long-windedly) as conceivable, so
344 * that, e.g., Python x == y delivers the same result as the platform
345 * C x == y when x and/or y is a NaN.
346 * When mixing float with an integer type, there's no good *uniform* approach.
347 * Converting the double to an integer obviously doesn't work, since we
348 * may lose info from fractional bits. Converting the integer to a double
Serhiy Storchaka95949422013-08-27 19:40:23 +0300349 * also has two failure modes: (1) an int may trigger overflow (too
Tim Peters307fa782004-09-23 08:06:40 +0000350 * 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 +0200351 * 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 +0000352 * 63 bits of precision, but a C double probably has only 53), and then
353 * we can falsely claim equality when low-order integer bits are lost by
354 * coercion to double. So this part is painful too.
355 */
356
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000357static PyObject*
358float_richcompare(PyObject *v, PyObject *w, int op)
359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 double i, j;
361 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 assert(PyFloat_Check(v));
364 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 /* Switch on the type of w. Set i and j to doubles to be compared,
367 * and op to the richcomp to use.
368 */
369 if (PyFloat_Check(w))
370 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 else if (!Py_IS_FINITE(i)) {
373 if (PyLong_Check(w))
374 /* If i is an infinity, its magnitude exceeds any
375 * finite integer, so it doesn't matter which int we
376 * compare i with. If i is a NaN, similarly.
377 */
378 j = 0.0;
379 else
380 goto Unimplemented;
381 }
Tim Peters307fa782004-09-23 08:06:40 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 else if (PyLong_Check(w)) {
384 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
385 int wsign = _PyLong_Sign(w);
386 size_t nbits;
387 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 if (vsign != wsign) {
390 /* Magnitudes are irrelevant -- the signs alone
391 * determine the outcome.
392 */
393 i = (double)vsign;
394 j = (double)wsign;
395 goto Compare;
396 }
397 /* The signs are the same. */
398 /* Convert w to a double if it fits. In particular, 0 fits. */
399 nbits = _PyLong_NumBits(w);
400 if (nbits == (size_t)-1 && PyErr_Occurred()) {
401 /* This long is so large that size_t isn't big enough
402 * to hold the # of bits. Replace with little doubles
403 * that give the same outcome -- w is so large that
404 * its magnitude must exceed the magnitude of any
405 * finite float.
406 */
407 PyErr_Clear();
408 i = (double)vsign;
409 assert(wsign != 0);
410 j = wsign * 2.0;
411 goto Compare;
412 }
413 if (nbits <= 48) {
414 j = PyLong_AsDouble(w);
415 /* It's impossible that <= 48 bits overflowed. */
416 assert(j != -1.0 || ! PyErr_Occurred());
417 goto Compare;
418 }
419 assert(wsign != 0); /* else nbits was 0 */
420 assert(vsign != 0); /* if vsign were 0, then since wsign is
421 * not 0, we would have taken the
422 * vsign != wsign branch at the start */
423 /* We want to work with non-negative numbers. */
424 if (vsign < 0) {
425 /* "Multiply both sides" by -1; this also swaps the
426 * comparator.
427 */
428 i = -i;
429 op = _Py_SwappedOp[op];
430 }
431 assert(i > 0.0);
432 (void) frexp(i, &exponent);
433 /* exponent is the # of bits in v before the radix point;
434 * we know that nbits (the # of bits in w) > 48 at this point
435 */
436 if (exponent < 0 || (size_t)exponent < nbits) {
437 i = 1.0;
438 j = 2.0;
439 goto Compare;
440 }
441 if ((size_t)exponent > nbits) {
442 i = 2.0;
443 j = 1.0;
444 goto Compare;
445 }
446 /* v and w have the same number of bits before the radix
Serhiy Storchaka95949422013-08-27 19:40:23 +0300447 * point. Construct two ints that have the same comparison
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 * outcome.
449 */
450 {
451 double fracpart;
452 double intpart;
453 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 PyObject *vv = NULL;
455 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 if (wsign < 0) {
458 ww = PyNumber_Negative(w);
459 if (ww == NULL)
460 goto Error;
461 }
462 else
463 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 fracpart = modf(i, &intpart);
466 vv = PyLong_FromDouble(intpart);
467 if (vv == NULL)
468 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 if (fracpart != 0.0) {
471 /* Shift left, and or a 1 bit into vv
472 * to represent the lost fraction.
473 */
474 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000475
Serhiy Storchakaa5119e72019-05-19 14:14:38 +0300476 temp = _PyLong_Lshift(ww, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 if (temp == NULL)
478 goto Error;
479 Py_DECREF(ww);
480 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000481
Serhiy Storchakaa5119e72019-05-19 14:14:38 +0300482 temp = _PyLong_Lshift(vv, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 if (temp == NULL)
484 goto Error;
485 Py_DECREF(vv);
486 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000487
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300488 temp = PyNumber_Or(vv, _PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 if (temp == NULL)
490 goto Error;
491 Py_DECREF(vv);
492 vv = temp;
493 }
Tim Peters307fa782004-09-23 08:06:40 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 r = PyObject_RichCompareBool(vv, ww, op);
496 if (r < 0)
497 goto Error;
498 result = PyBool_FromLong(r);
499 Error:
500 Py_XDECREF(vv);
501 Py_XDECREF(ww);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 return result;
503 }
504 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000505
Serhiy Storchaka95949422013-08-27 19:40:23 +0300506 else /* w isn't float or int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000508
509 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 switch (op) {
511 case Py_EQ:
512 r = i == j;
513 break;
514 case Py_NE:
515 r = i != j;
516 break;
517 case Py_LE:
518 r = i <= j;
519 break;
520 case Py_GE:
521 r = i >= j;
522 break;
523 case Py_LT:
524 r = i < j;
525 break;
526 case Py_GT:
527 r = i > j;
528 break;
529 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000531
532 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500533 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000534}
535
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000536static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000537float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000540}
541
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000543float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 double a,b;
546 CONVERT_TO_DOUBLE(v, a);
547 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 a = a + b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000550}
551
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000552static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000553float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 double a,b;
556 CONVERT_TO_DOUBLE(v, a);
557 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 a = a - b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000560}
561
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000562static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000563float_mul(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_div(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 if (b == 0.0) {
579 PyErr_SetString(PyExc_ZeroDivisionError,
580 "float division by zero");
581 return NULL;
582 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 a = a / b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000585}
586
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000587static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000588float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 double vx, wx;
591 double mod;
592 CONVERT_TO_DOUBLE(v, vx);
593 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 if (wx == 0.0) {
595 PyErr_SetString(PyExc_ZeroDivisionError,
596 "float modulo");
597 return NULL;
598 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000600 if (mod) {
601 /* ensure the remainder has the same sign as the denominator */
602 if ((wx < 0) != (mod < 0)) {
603 mod += wx;
604 }
605 }
606 else {
607 /* the remainder is zero, and in the presence of signed zeroes
608 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000609 it has the same sign as the denominator. */
610 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000613}
614
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900615static void
616_float_div_mod(double vx, double wx, double *floordiv, double *mod)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000617{
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900618 double div;
619 *mod = fmod(vx, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 /* fmod is typically exact, so vx-mod is *mathematically* an
621 exact multiple of wx. But this is fp arithmetic, and fp
622 vx - mod is an approximation; the result is that div may
623 not be an exact integral value after the division, although
624 it will always be very close to one.
625 */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900626 div = (vx - *mod) / wx;
627 if (*mod) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 /* ensure the remainder has the same sign as the denominator */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900629 if ((wx < 0) != (*mod < 0)) {
630 *mod += wx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 div -= 1.0;
632 }
633 }
634 else {
635 /* the remainder is zero, and in the presence of signed zeroes
636 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000637 it has the same sign as the denominator. */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900638 *mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 }
640 /* snap quotient to nearest integral value */
641 if (div) {
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900642 *floordiv = floor(div);
643 if (div - *floordiv > 0.5) {
644 *floordiv += 1.0;
Mark Dickinsonbe8147b2020-02-02 11:37:02 +0000645 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 }
647 else {
648 /* div is zero - get the same sign as the true quotient */
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900649 *floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 }
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900651}
652
653static PyObject *
654float_divmod(PyObject *v, PyObject *w)
655{
Mark Dickinsonbe8147b2020-02-02 11:37:02 +0000656 double vx, wx;
657 double mod, floordiv;
658 CONVERT_TO_DOUBLE(v, vx);
659 CONVERT_TO_DOUBLE(w, wx);
660 if (wx == 0.0) {
661 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
662 return NULL;
663 }
664 _float_div_mod(vx, wx, &floordiv, &mod);
665 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000666}
667
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000668static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000669float_floor_div(PyObject *v, PyObject *w)
670{
Dong-hee Na8d49f7c2020-01-30 22:23:15 +0900671 double vx, wx;
672 double mod, floordiv;
673 CONVERT_TO_DOUBLE(v, vx);
674 CONVERT_TO_DOUBLE(w, wx);
675 if (wx == 0.0) {
676 PyErr_SetString(PyExc_ZeroDivisionError, "float floor division by zero");
677 return NULL;
678 }
679 _float_div_mod(vx, wx, &floordiv, &mod);
680 return PyFloat_FromDouble(floordiv);
Tim Peters63a35712001-12-11 19:57:24 +0000681}
682
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000683/* determine whether x is an odd integer or not; assumes that
684 x is not an infinity or nan. */
685#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
686
Tim Peters63a35712001-12-11 19:57:24 +0000687static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000688float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 double iv, iw, ix;
691 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 if ((PyObject *)z != Py_None) {
694 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
695 "allowed unless all arguments are integers");
696 return NULL;
697 }
Tim Peters32f453e2001-09-03 08:35:41 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 CONVERT_TO_DOUBLE(v, iv);
700 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 /* Sort out special cases here instead of relying on pow() */
703 if (iw == 0) { /* v**0 is 1, even 0**0 */
704 return PyFloat_FromDouble(1.0);
705 }
706 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
707 return PyFloat_FromDouble(iv);
708 }
709 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
710 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
711 }
712 if (Py_IS_INFINITY(iw)) {
713 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
714 * abs(v) > 1 (including case where v infinite)
715 *
716 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
717 * abs(v) > 1 (including case where v infinite)
718 */
719 iv = fabs(iv);
720 if (iv == 1.0)
721 return PyFloat_FromDouble(1.0);
722 else if ((iw > 0.0) == (iv > 1.0))
723 return PyFloat_FromDouble(fabs(iw)); /* return inf */
724 else
725 return PyFloat_FromDouble(0.0);
726 }
727 if (Py_IS_INFINITY(iv)) {
728 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
729 * both cases, we need to add the appropriate sign if w is
730 * an odd integer.
731 */
732 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
733 if (iw > 0.0)
734 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
735 else
736 return PyFloat_FromDouble(iw_is_odd ?
737 copysign(0.0, iv) : 0.0);
738 }
739 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
740 (already dealt with above), and an error
741 if w is negative. */
742 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
743 if (iw < 0.0) {
744 PyErr_SetString(PyExc_ZeroDivisionError,
745 "0.0 cannot be raised to a "
746 "negative power");
747 return NULL;
748 }
749 /* use correct sign if iw is odd */
750 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
751 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 if (iv < 0.0) {
754 /* Whether this is an error is a mess, and bumps into libm
755 * bugs so we have to figure it out ourselves.
756 */
757 if (iw != floor(iw)) {
758 /* Negative numbers raised to fractional powers
759 * become complex.
760 */
761 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
762 }
763 /* iw is an exact integer, albeit perhaps a very large
764 * one. Replace iv by its absolute value and remember
765 * to negate the pow result if iw is odd.
766 */
767 iv = -iv;
768 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
769 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
772 /* (-1) ** large_integer also ends up here. Here's an
773 * extract from the comments for the previous
774 * implementation explaining why this special case is
775 * necessary:
776 *
777 * -1 raised to an exact integer should never be exceptional.
778 * Alas, some libms (chiefly glibc as of early 2003) return
779 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
780 * happen to be representable in a *C* integer. That's a
781 * bug.
782 */
783 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
784 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 /* Now iv and iw are finite, iw is nonzero, and iv is
787 * positive and not equal to 1.0. We finally allow
788 * the platform pow to step in and do the rest.
789 */
790 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 ix = pow(iv, iw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 Py_ADJUST_ERANGE1(ix);
793 if (negate_result)
794 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 if (errno != 0) {
797 /* We don't expect any errno value other than ERANGE, but
798 * the range of libm bugs appears unbounded.
799 */
800 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
801 PyExc_ValueError);
802 return NULL;
803 }
804 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000805}
806
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000807#undef DOUBLE_IS_ODD_INTEGER
808
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000809static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000810float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813}
814
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000815static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000816float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000819}
820
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000821static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000822float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000825}
826
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200827/*[clinic input]
828float.is_integer
829
830Return True if the float is an integer.
831[clinic start generated code]*/
832
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000833static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200834float_is_integer_impl(PyObject *self)
835/*[clinic end generated code: output=7112acf95a4d31ea input=311810d3f777e10d]*/
Christian Heimes53876d92008-04-19 00:31:39 +0000836{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200837 double x = PyFloat_AsDouble(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 PyObject *o;
839
840 if (x == -1.0 && PyErr_Occurred())
841 return NULL;
842 if (!Py_IS_FINITE(x))
843 Py_RETURN_FALSE;
844 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 o = (floor(x) == x) ? Py_True : Py_False;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 if (errno != 0) {
847 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
848 PyExc_ValueError);
849 return NULL;
850 }
851 Py_INCREF(o);
852 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000853}
854
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200855/*[clinic input]
856float.__trunc__
857
858Return the Integral closest to x between 0 and x.
859[clinic start generated code]*/
860
Christian Heimes53876d92008-04-19 00:31:39 +0000861static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200862float___trunc___impl(PyObject *self)
863/*[clinic end generated code: output=dd3e289dd4c6b538 input=591b9ba0d650fdff]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000864{
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500865 return PyLong_FromDouble(PyFloat_AS_DOUBLE(self));
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000866}
867
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +0300868/*[clinic input]
869float.__floor__
870
871Return the floor as an Integral.
872[clinic start generated code]*/
873
874static PyObject *
875float___floor___impl(PyObject *self)
876/*[clinic end generated code: output=e0551dbaea8c01d1 input=77bb13eb12e268df]*/
877{
878 double x = PyFloat_AS_DOUBLE(self);
879 return PyLong_FromDouble(floor(x));
880}
881
882/*[clinic input]
883float.__ceil__
884
885Return the ceiling as an Integral.
886[clinic start generated code]*/
887
888static PyObject *
889float___ceil___impl(PyObject *self)
890/*[clinic end generated code: output=a2fd8858f73736f9 input=79e41ae94aa0a516]*/
891{
892 double x = PyFloat_AS_DOUBLE(self);
893 return PyLong_FromDouble(ceil(x));
894}
895
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000896/* double_round: rounds a finite double to the closest multiple of
897 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
898 ndigits <= 323). Returns a Python float, or sets a Python error and
899 returns NULL on failure (OverflowError and memory errors are possible). */
900
901#ifndef PY_NO_SHORT_FLOAT_REPR
902/* version of double_round that uses the correctly-rounded string<->double
903 conversions from Python/dtoa.c */
904
905static PyObject *
906double_round(double x, int ndigits) {
907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 double rounded;
909 Py_ssize_t buflen, mybuflen=100;
910 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
911 int decpt, sign;
912 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000913 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000916 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000918 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 if (buf == NULL) {
920 PyErr_NoMemory();
921 return NULL;
922 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
925 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
926 buflen = buf_end - buf;
927 if (buflen + 8 > mybuflen) {
928 mybuflen = buflen+8;
929 mybuf = (char *)PyMem_Malloc(mybuflen);
930 if (mybuf == NULL) {
931 PyErr_NoMemory();
932 goto exit;
933 }
934 }
935 /* copy buf to mybuf, adding exponent, sign and leading 0 */
936 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
937 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 /* and convert the resulting string back to a double */
940 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000941 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000943 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 if (errno == ERANGE && fabs(rounded) >= 1.)
945 PyErr_SetString(PyExc_OverflowError,
946 "rounded value too large to represent");
947 else
948 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 /* done computing value; now clean up */
951 if (mybuf != shortbuf)
952 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000953 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 _Py_dg_freedtoa(buf);
955 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000956}
957
958#else /* PY_NO_SHORT_FLOAT_REPR */
959
960/* fallback version, to be used when correctly rounded binary<->decimal
961 conversions aren't available */
962
963static PyObject *
964double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 double pow1, pow2, y, z;
966 if (ndigits >= 0) {
967 if (ndigits > 22) {
968 /* pow1 and pow2 are each safe from overflow, but
969 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
970 pow1 = pow(10.0, (double)(ndigits-22));
971 pow2 = 1e22;
972 }
973 else {
974 pow1 = pow(10.0, (double)ndigits);
975 pow2 = 1.0;
976 }
977 y = (x*pow1)*pow2;
978 /* if y overflows, then rounded value is exactly x */
979 if (!Py_IS_FINITE(y))
980 return PyFloat_FromDouble(x);
981 }
982 else {
983 pow1 = pow(10.0, (double)-ndigits);
984 pow2 = 1.0; /* unused; silences a gcc compiler warning */
985 y = x / pow1;
986 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 z = round(y);
989 if (fabs(y-z) == 0.5)
990 /* halfway between two integers; use round-half-even */
991 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 if (ndigits >= 0)
994 z = (z / pow2) / pow1;
995 else
996 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 /* if computation resulted in overflow, raise OverflowError */
999 if (!Py_IS_FINITE(z)) {
1000 PyErr_SetString(PyExc_OverflowError,
1001 "overflow occurred during round");
1002 return NULL;
1003 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001006}
1007
1008#endif /* PY_NO_SHORT_FLOAT_REPR */
1009
1010/* round a Python float v to the closest multiple of 10**-ndigits */
1011
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001012/*[clinic input]
1013float.__round__
1014
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001015 ndigits as o_ndigits: object = None
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001016 /
1017
1018Return the Integral closest to x, rounding half toward even.
1019
1020When an argument is passed, work like built-in round(x, ndigits).
1021[clinic start generated code]*/
1022
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001023static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001024float___round___impl(PyObject *self, PyObject *o_ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001025/*[clinic end generated code: output=374c36aaa0f13980 input=fc0fe25924fbc9ed]*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 double x, rounded;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001029
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001030 x = PyFloat_AsDouble(self);
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001031 if (o_ndigits == Py_None) {
Steve Dowercb39d1f2015-04-15 16:10:59 -04001032 /* single-argument round or with None ndigits:
1033 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 rounded = round(x);
1035 if (fabs(x-rounded) == 0.5)
1036 /* halfway case: round to even */
1037 rounded = 2.0*round(x/2.0);
1038 return PyLong_FromDouble(rounded);
1039 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 /* interpret second argument as a Py_ssize_t; clips on overflow */
1042 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1043 if (ndigits == -1 && PyErr_Occurred())
1044 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 /* nans and infinities round to themselves */
1047 if (!Py_IS_FINITE(x))
1048 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1051 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1052 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001053#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1054#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 if (ndigits > NDIGITS_MAX)
1056 /* return x */
1057 return PyFloat_FromDouble(x);
1058 else if (ndigits < NDIGITS_MIN)
1059 /* return 0.0, but with sign of x */
1060 return PyFloat_FromDouble(0.0*x);
1061 else
1062 /* finite x, and ndigits is not unreasonably large */
1063 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001064#undef NDIGITS_MAX
1065#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001066}
1067
1068static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001069float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 if (PyFloat_CheckExact(v))
1072 Py_INCREF(v);
1073 else
1074 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1075 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001076}
1077
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001078/*[clinic input]
1079float.conjugate
1080
1081Return self, the complex conjugate of any float.
1082[clinic start generated code]*/
1083
1084static PyObject *
1085float_conjugate_impl(PyObject *self)
1086/*[clinic end generated code: output=8ca292c2479194af input=82ba6f37a9ff91dd]*/
1087{
1088 return float_float(self);
1089}
1090
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001091/* turn ASCII hex characters into integer values and vice versa */
1092
1093static char
1094char_from_hex(int x)
1095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001097 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001098}
1099
1100static int
1101hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 int x;
1103 switch(c) {
1104 case '0':
1105 x = 0;
1106 break;
1107 case '1':
1108 x = 1;
1109 break;
1110 case '2':
1111 x = 2;
1112 break;
1113 case '3':
1114 x = 3;
1115 break;
1116 case '4':
1117 x = 4;
1118 break;
1119 case '5':
1120 x = 5;
1121 break;
1122 case '6':
1123 x = 6;
1124 break;
1125 case '7':
1126 x = 7;
1127 break;
1128 case '8':
1129 x = 8;
1130 break;
1131 case '9':
1132 x = 9;
1133 break;
1134 case 'a':
1135 case 'A':
1136 x = 10;
1137 break;
1138 case 'b':
1139 case 'B':
1140 x = 11;
1141 break;
1142 case 'c':
1143 case 'C':
1144 x = 12;
1145 break;
1146 case 'd':
1147 case 'D':
1148 x = 13;
1149 break;
1150 case 'e':
1151 case 'E':
1152 x = 14;
1153 break;
1154 case 'f':
1155 case 'F':
1156 x = 15;
1157 break;
1158 default:
1159 x = -1;
1160 break;
1161 }
1162 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001163}
1164
1165/* convert a float to a hexadecimal string */
1166
1167/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1168 of the form 4k+1. */
1169#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1170
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001171/*[clinic input]
1172float.hex
1173
1174Return a hexadecimal representation of a floating-point number.
1175
1176>>> (-0.1).hex()
1177'-0x1.999999999999ap-4'
1178>>> 3.14159.hex()
1179'0x1.921f9f01b866ep+1'
1180[clinic start generated code]*/
1181
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001182static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001183float_hex_impl(PyObject *self)
1184/*[clinic end generated code: output=0ebc9836e4d302d4 input=bec1271a33d47e67]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 double x, m;
1187 int e, shift, i, si, esign;
1188 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1189 trailing NUL byte. */
1190 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001191
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001192 CONVERT_TO_DOUBLE(self, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001195 return float_repr((PyFloatObject *)self);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001198 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 return PyUnicode_FromString("-0x0.0p+0");
1200 else
1201 return PyUnicode_FromString("0x0.0p+0");
1202 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001205 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 m = ldexp(m, shift);
1207 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 si = 0;
1210 s[si] = char_from_hex((int)m);
1211 si++;
1212 m -= (int)m;
1213 s[si] = '.';
1214 si++;
1215 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1216 m *= 16.0;
1217 s[si] = char_from_hex((int)m);
1218 si++;
1219 m -= (int)m;
1220 }
1221 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 if (e < 0) {
1224 esign = (int)'-';
1225 e = -e;
1226 }
1227 else
1228 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 if (x < 0.0)
1231 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1232 else
1233 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001234}
1235
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001236/* Convert a hexadecimal string to a float. */
1237
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001238/*[clinic input]
1239@classmethod
1240float.fromhex
1241
1242 string: object
1243 /
1244
1245Create a floating-point number from a hexadecimal string.
1246
1247>>> float.fromhex('0x1.ffffp10')
12482047.984375
1249>>> float.fromhex('-0x1p-1074')
1250-5e-324
1251[clinic start generated code]*/
1252
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001253static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001254float_fromhex(PyTypeObject *type, PyObject *string)
1255/*[clinic end generated code: output=46c0274d22b78e82 input=0407bebd354bca89]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001256{
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001257 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 double x;
1259 long exp, top_exp, lsb, key_digit;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001260 const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 int half_eps, digit, round_up, negate=0;
1262 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 /*
1265 * For the sake of simplicity and correctness, we impose an artificial
1266 * limit on ndigits, the total number of hex digits in the coefficient
1267 * The limit is chosen to ensure that, writing exp for the exponent,
1268 *
1269 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1270 * guaranteed to overflow (provided it's nonzero)
1271 *
1272 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1273 * guaranteed to underflow to 0.
1274 *
1275 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1276 * overflow in the calculation of exp and top_exp below.
1277 *
1278 * More specifically, ndigits is assumed to satisfy the following
1279 * inequalities:
1280 *
1281 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1282 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1283 *
1284 * If either of these inequalities is not satisfied, a ValueError is
1285 * raised. Otherwise, write x for the value of the hex string, and
1286 * assume x is nonzero. Then
1287 *
1288 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1289 *
1290 * Now if exp > LONG_MAX/2 then:
1291 *
1292 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1293 * = DBL_MAX_EXP
1294 *
1295 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1296 * double, so overflows. If exp < LONG_MIN/2, then
1297 *
1298 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1299 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1300 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1301 *
1302 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1303 * when converted to a C double.
1304 *
1305 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1306 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1307 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001308
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001309 s = PyUnicode_AsUTF8AndSize(string, &length);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (s == NULL)
1311 return NULL;
1312 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 /********************
1315 * Parse the string *
1316 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 /* leading whitespace */
1319 while (Py_ISSPACE(*s))
1320 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 /* infinities and nans */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001323 x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 if (coeff_end != s) {
1325 s = coeff_end;
1326 goto finished;
1327 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 /* optional sign */
1330 if (*s == '-') {
1331 s++;
1332 negate = 1;
1333 }
1334 else if (*s == '+')
1335 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 /* [0x] */
1338 s_store = s;
1339 if (*s == '0') {
1340 s++;
1341 if (*s == 'x' || *s == 'X')
1342 s++;
1343 else
1344 s = s_store;
1345 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 /* coefficient: <integer> [. <fraction>] */
1348 coeff_start = s;
1349 while (hex_from_char(*s) >= 0)
1350 s++;
1351 s_store = s;
1352 if (*s == '.') {
1353 s++;
1354 while (hex_from_char(*s) >= 0)
1355 s++;
1356 coeff_end = s-1;
1357 }
1358 else
1359 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 /* ndigits = total # of hex digits; fdigits = # after point */
1362 ndigits = coeff_end - coeff_start;
1363 fdigits = coeff_end - s_store;
1364 if (ndigits == 0)
1365 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001366 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1367 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 /* [p <exponent>] */
1371 if (*s == 'p' || *s == 'P') {
1372 s++;
1373 exp_start = s;
1374 if (*s == '-' || *s == '+')
1375 s++;
1376 if (!('0' <= *s && *s <= '9'))
1377 goto parse_error;
1378 s++;
1379 while ('0' <= *s && *s <= '9')
1380 s++;
1381 exp = strtol(exp_start, NULL, 10);
1382 }
1383 else
1384 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001385
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001386/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1388 coeff_end-(j) : \
1389 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 /*******************************************
1392 * Compute rounded value of the hex string *
1393 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 /* Discard leading zeros, and catch extreme overflow and underflow */
1396 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1397 ndigits--;
1398 if (ndigits == 0 || exp < LONG_MIN/2) {
1399 x = 0.0;
1400 goto finished;
1401 }
1402 if (exp > LONG_MAX/2)
1403 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 /* Adjust exponent for fractional part. */
1406 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1409 top_exp = exp + 4*((long)ndigits - 1);
1410 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1411 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 /* catch almost all nonextreme cases of overflow and underflow here */
1414 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1415 x = 0.0;
1416 goto finished;
1417 }
1418 if (top_exp > DBL_MAX_EXP)
1419 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 /* lsb = exponent of least significant bit of the *rounded* value.
1422 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001423 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 x = 0.0;
1426 if (exp >= lsb) {
1427 /* no rounding required */
1428 for (i = ndigits-1; i >= 0; i--)
1429 x = 16.0*x + HEX_DIGIT(i);
1430 x = ldexp(x, (int)(exp));
1431 goto finished;
1432 }
1433 /* rounding required. key_digit is the index of the hex digit
1434 containing the first bit to be rounded away. */
1435 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1436 key_digit = (lsb - exp - 1) / 4;
1437 for (i = ndigits-1; i > key_digit; i--)
1438 x = 16.0*x + HEX_DIGIT(i);
1439 digit = HEX_DIGIT(key_digit);
1440 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1443 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1444 if ((digit & half_eps) != 0) {
1445 round_up = 0;
1446 if ((digit & (3*half_eps-1)) != 0 ||
1447 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1448 round_up = 1;
1449 else
1450 for (i = key_digit-1; i >= 0; i--)
1451 if (HEX_DIGIT(i) != 0) {
1452 round_up = 1;
1453 break;
1454 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001455 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 x += 2*half_eps;
1457 if (top_exp == DBL_MAX_EXP &&
1458 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1459 /* overflow corner case: pre-rounded value <
1460 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1461 goto overflow_error;
1462 }
1463 }
1464 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001465
1466 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 /* optional trailing whitespace leading to the end of the string */
1468 while (Py_ISSPACE(*s))
1469 s++;
1470 if (s != s_end)
1471 goto parse_error;
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001472 result = PyFloat_FromDouble(negate ? -x : x);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001473 if (type != &PyFloat_Type && result != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001474 Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001475 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001477
1478 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 PyErr_SetString(PyExc_OverflowError,
1480 "hexadecimal value too large to represent as a float");
1481 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001482
1483 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 PyErr_SetString(PyExc_ValueError,
1485 "invalid hexadecimal floating-point string");
1486 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001487
1488 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 PyErr_SetString(PyExc_ValueError,
1490 "hexadecimal string too long to convert");
1491 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001492}
1493
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001494/*[clinic input]
1495float.as_integer_ratio
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001496
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001497Return integer ratio.
1498
1499Return a pair of integers, whose ratio is exactly equal to the original float
1500and with a positive denominator.
1501
1502Raise OverflowError on infinities and a ValueError on NaNs.
1503
1504>>> (10.0).as_integer_ratio()
1505(10, 1)
1506>>> (0.0).as_integer_ratio()
1507(0, 1)
1508>>> (-.25).as_integer_ratio()
1509(-1, 4)
1510[clinic start generated code]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001511
Christian Heimes26855632008-01-27 23:50:43 +00001512static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001513float_as_integer_ratio_impl(PyObject *self)
1514/*[clinic end generated code: output=65f25f0d8d30a712 input=e21d08b4630c2e44]*/
Christian Heimes26855632008-01-27 23:50:43 +00001515{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001516 double self_double;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 double float_part;
1518 int exponent;
1519 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 PyObject *py_exponent = NULL;
1522 PyObject *numerator = NULL;
1523 PyObject *denominator = NULL;
1524 PyObject *result_pair = NULL;
1525 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001526
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001527 CONVERT_TO_DOUBLE(self, self_double);
Christian Heimes26855632008-01-27 23:50:43 +00001528
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001529 if (Py_IS_INFINITY(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001530 PyErr_SetString(PyExc_OverflowError,
1531 "cannot convert Infinity to integer ratio");
1532 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001534 if (Py_IS_NAN(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001535 PyErr_SetString(PyExc_ValueError,
1536 "cannot convert NaN to integer ratio");
1537 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 }
Christian Heimes26855632008-01-27 23:50:43 +00001539
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001540 float_part = frexp(self_double, &exponent); /* self_double == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1543 float_part *= 2.0;
1544 exponent--;
1545 }
1546 /* self == float_part * 2**exponent exactly and float_part is integral.
1547 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1548 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 numerator = PyLong_FromDouble(float_part);
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001551 if (numerator == NULL)
1552 goto error;
1553 denominator = PyLong_FromLong(1);
1554 if (denominator == NULL)
1555 goto error;
1556 py_exponent = PyLong_FromLong(Py_ABS(exponent));
1557 if (py_exponent == NULL)
1558 goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 /* fold in 2**exponent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 if (exponent > 0) {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001562 Py_SETREF(numerator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001563 long_methods->nb_lshift(numerator, py_exponent));
1564 if (numerator == NULL)
1565 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 }
1567 else {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001568 Py_SETREF(denominator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001569 long_methods->nb_lshift(denominator, py_exponent));
1570 if (denominator == NULL)
1571 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 }
1573
1574 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001575
Christian Heimes26855632008-01-27 23:50:43 +00001576error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 Py_XDECREF(py_exponent);
1578 Py_XDECREF(denominator);
1579 Py_XDECREF(numerator);
1580 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001581}
1582
Jeremy Hylton938ace62002-07-17 16:30:39 +00001583static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001584float_subtype_new(PyTypeObject *type, PyObject *x);
1585
1586/*[clinic input]
1587@classmethod
1588float.__new__ as float_new
Serhiy Storchakaba85d692017-03-30 09:09:41 +03001589 x: object(c_default="_PyLong_Zero") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001590 /
1591
1592Convert a string or number to a floating point number, if possible.
1593[clinic start generated code]*/
Guido van Rossumbef14172001-08-29 15:47:46 +00001594
Tim Peters6d6c1a32001-08-02 04:15:00 +00001595static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001596float_new_impl(PyTypeObject *type, PyObject *x)
Serhiy Storchakabae68812017-04-05 12:00:42 +03001597/*[clinic end generated code: output=ccf1e8dc460ba6ba input=540ee77c204ff87a]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00001598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 if (type != &PyFloat_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001600 return float_subtype_new(type, x); /* Wimp out */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 /* If it's a string, but not a string subclass, use
1602 PyFloat_FromString. */
1603 if (PyUnicode_CheckExact(x))
1604 return PyFloat_FromString(x);
1605 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001606}
1607
Guido van Rossumbef14172001-08-29 15:47:46 +00001608/* Wimpy, slow approach to tp_new calls for subtypes of float:
1609 first create a regular float from whatever arguments we got,
1610 then allocate a subtype instance and initialize its ob_fval
1611 from the regular float. The regular float is then thrown away.
1612*/
1613static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001614float_subtype_new(PyTypeObject *type, PyObject *x)
Guido van Rossumbef14172001-08-29 15:47:46 +00001615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 assert(PyType_IsSubtype(type, &PyFloat_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001619 tmp = float_new_impl(&PyFloat_Type, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 if (tmp == NULL)
1621 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001622 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 newobj = type->tp_alloc(type, 0);
1624 if (newobj == NULL) {
1625 Py_DECREF(tmp);
1626 return NULL;
1627 }
1628 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1629 Py_DECREF(tmp);
1630 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001631}
1632
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001633/*[clinic input]
1634float.__getnewargs__
1635[clinic start generated code]*/
1636
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001637static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001638float___getnewargs___impl(PyObject *self)
1639/*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001640{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001641 return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001642}
1643
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001644/* this is for the benefit of the pack/unpack routines below */
1645
1646typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001648} float_format_type;
1649
1650static float_format_type double_format, float_format;
1651static float_format_type detected_double_format, detected_float_format;
1652
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001653/*[clinic input]
1654@classmethod
1655float.__getformat__
1656
1657 typestr: str
1658 Must be 'double' or 'float'.
1659 /
1660
1661You probably don't want to use this function.
1662
1663It exists mainly to be used in Python's test suite.
1664
1665This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
1666little-endian' best describes the format of floating point numbers used by the
1667C type named by typestr.
1668[clinic start generated code]*/
1669
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001670static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001671float___getformat___impl(PyTypeObject *type, const char *typestr)
1672/*[clinic end generated code: output=2bfb987228cc9628 input=d5a52600f835ad67]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001675
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001676 if (strcmp(typestr, "double") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 r = double_format;
1678 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001679 else if (strcmp(typestr, "float") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 r = float_format;
1681 }
1682 else {
1683 PyErr_SetString(PyExc_ValueError,
1684 "__getformat__() argument 1 must be "
1685 "'double' or 'float'");
1686 return NULL;
1687 }
1688
1689 switch (r) {
1690 case unknown_format:
1691 return PyUnicode_FromString("unknown");
1692 case ieee_little_endian_format:
1693 return PyUnicode_FromString("IEEE, little-endian");
1694 case ieee_big_endian_format:
1695 return PyUnicode_FromString("IEEE, big-endian");
1696 default:
Victor Stinner04394df2019-11-18 17:39:48 +01001697 PyErr_SetString(PyExc_RuntimeError,
1698 "insane float_format or double_format");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 return NULL;
1700 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001701}
1702
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001703/*[clinic input]
1704@classmethod
1705float.__set_format__
1706
1707 typestr: str
1708 Must be 'double' or 'float'.
1709 fmt: str
1710 Must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian',
1711 and in addition can only be one of the latter two if it appears to
1712 match the underlying C reality.
1713 /
1714
1715You probably don't want to use this function.
1716
1717It exists mainly to be used in Python's test suite.
1718
1719Override the automatic determination of C-level floating point type.
1720This affects how floats are converted to and from binary strings.
1721[clinic start generated code]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001722
1723static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001724float___set_format___impl(PyTypeObject *type, const char *typestr,
1725 const char *fmt)
1726/*[clinic end generated code: output=504460f5dc85acbd input=5306fa2b81a997e4]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 float_format_type f;
1729 float_format_type detected;
1730 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 if (strcmp(typestr, "double") == 0) {
1733 p = &double_format;
1734 detected = detected_double_format;
1735 }
1736 else if (strcmp(typestr, "float") == 0) {
1737 p = &float_format;
1738 detected = detected_float_format;
1739 }
1740 else {
1741 PyErr_SetString(PyExc_ValueError,
1742 "__setformat__() argument 1 must "
1743 "be 'double' or 'float'");
1744 return NULL;
1745 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001746
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001747 if (strcmp(fmt, "unknown") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 f = unknown_format;
1749 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001750 else if (strcmp(fmt, "IEEE, little-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 f = ieee_little_endian_format;
1752 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001753 else if (strcmp(fmt, "IEEE, big-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 f = ieee_big_endian_format;
1755 }
1756 else {
1757 PyErr_SetString(PyExc_ValueError,
1758 "__setformat__() argument 2 must be "
1759 "'unknown', 'IEEE, little-endian' or "
1760 "'IEEE, big-endian'");
1761 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 if (f != unknown_format && f != detected) {
1766 PyErr_Format(PyExc_ValueError,
1767 "can only set %s format to 'unknown' or the "
1768 "detected platform value", typestr);
1769 return NULL;
1770 }
1771
1772 *p = f;
1773 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001774}
1775
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001776static PyObject *
1777float_getreal(PyObject *v, void *closure)
1778{
1779 return float_float(v);
1780}
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001781
Guido van Rossumb43daf72007-08-01 18:08:08 +00001782static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001783float_getimag(PyObject *v, void *closure)
Guido van Rossumb43daf72007-08-01 18:08:08 +00001784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001786}
1787
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001788/*[clinic input]
1789float.__format__
1790
1791 format_spec: unicode
1792 /
1793
1794Formats the float according to format_spec.
1795[clinic start generated code]*/
1796
Eric Smith8c663262007-08-25 02:26:07 +00001797static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001798float___format___impl(PyObject *self, PyObject *format_spec)
1799/*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/
Eric Smith8c663262007-08-25 02:26:07 +00001800{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001801 _PyUnicodeWriter writer;
1802 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001803
Victor Stinner8f674cc2013-04-17 23:02:17 +02001804 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001805 ret = _PyFloat_FormatAdvancedWriter(
1806 &writer,
1807 self,
1808 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1809 if (ret == -1) {
1810 _PyUnicodeWriter_Dealloc(&writer);
1811 return NULL;
1812 }
1813 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001814}
1815
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001816static PyMethodDef float_methods[] = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001817 FLOAT_CONJUGATE_METHODDEF
1818 FLOAT___TRUNC___METHODDEF
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +03001819 FLOAT___FLOOR___METHODDEF
1820 FLOAT___CEIL___METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001821 FLOAT___ROUND___METHODDEF
1822 FLOAT_AS_INTEGER_RATIO_METHODDEF
1823 FLOAT_FROMHEX_METHODDEF
1824 FLOAT_HEX_METHODDEF
1825 FLOAT_IS_INTEGER_METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001826 FLOAT___GETNEWARGS___METHODDEF
1827 FLOAT___GETFORMAT___METHODDEF
1828 FLOAT___SET_FORMAT___METHODDEF
1829 FLOAT___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001831};
1832
Guido van Rossumb43daf72007-08-01 18:08:08 +00001833static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 {"real",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001835 float_getreal, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001836 "the real part of a complex number",
1837 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 {"imag",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001839 float_getimag, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001840 "the imaginary part of a complex number",
1841 NULL},
1842 {NULL} /* Sentinel */
1843};
1844
Tim Peters6d6c1a32001-08-02 04:15:00 +00001845
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001846static PyNumberMethods float_as_number = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001847 float_add, /* nb_add */
1848 float_sub, /* nb_subtract */
1849 float_mul, /* nb_multiply */
1850 float_rem, /* nb_remainder */
1851 float_divmod, /* nb_divmod */
1852 float_pow, /* nb_power */
1853 (unaryfunc)float_neg, /* nb_negative */
1854 float_float, /* nb_positive */
1855 (unaryfunc)float_abs, /* nb_absolute */
1856 (inquiry)float_bool, /* nb_bool */
1857 0, /* nb_invert */
1858 0, /* nb_lshift */
1859 0, /* nb_rshift */
1860 0, /* nb_and */
1861 0, /* nb_xor */
1862 0, /* nb_or */
1863 float___trunc___impl, /* nb_int */
1864 0, /* nb_reserved */
1865 float_float, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 0, /* nb_inplace_add */
1867 0, /* nb_inplace_subtract */
1868 0, /* nb_inplace_multiply */
1869 0, /* nb_inplace_remainder */
1870 0, /* nb_inplace_power */
1871 0, /* nb_inplace_lshift */
1872 0, /* nb_inplace_rshift */
1873 0, /* nb_inplace_and */
1874 0, /* nb_inplace_xor */
1875 0, /* nb_inplace_or */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001876 float_floor_div, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 float_div, /* nb_true_divide */
1878 0, /* nb_inplace_floor_divide */
1879 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001880};
1881
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001882PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1884 "float",
1885 sizeof(PyFloatObject),
1886 0,
1887 (destructor)float_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001888 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 0, /* tp_getattr */
1890 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001891 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 (reprfunc)float_repr, /* tp_repr */
1893 &float_as_number, /* tp_as_number */
1894 0, /* tp_as_sequence */
1895 0, /* tp_as_mapping */
1896 (hashfunc)float_hash, /* tp_hash */
1897 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001898 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 PyObject_GenericGetAttr, /* tp_getattro */
1900 0, /* tp_setattro */
1901 0, /* tp_as_buffer */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001902 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001903 float_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 0, /* tp_traverse */
1905 0, /* tp_clear */
1906 float_richcompare, /* tp_richcompare */
1907 0, /* tp_weaklistoffset */
1908 0, /* tp_iter */
1909 0, /* tp_iternext */
1910 float_methods, /* tp_methods */
1911 0, /* tp_members */
1912 float_getset, /* tp_getset */
1913 0, /* tp_base */
1914 0, /* tp_dict */
1915 0, /* tp_descr_get */
1916 0, /* tp_descr_set */
1917 0, /* tp_dictoffset */
1918 0, /* tp_init */
1919 0, /* tp_alloc */
1920 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001921};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001922
Victor Stinner1c8f0592013-07-22 22:24:54 +02001923int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001924_PyFloat_Init(void)
1925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 /* We attempt to determine if this machine is using IEEE
1927 floating point formats by peering at the bits of some
1928 carefully chosen values. If it looks like we are on an
1929 IEEE platform, the float packing/unpacking routines can
1930 just copy bits, if not they resort to arithmetic & shifts
1931 and masks. The shifts & masks approach works on all finite
1932 values, but what happens to infinities, NaNs and signed
1933 zeroes on packing is an accident, and attempting to unpack
1934 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 Note that if we're on some whacked-out platform which uses
1937 IEEE formats but isn't strictly little-endian or big-
1938 endian, we will fall back to the portable shifts & masks
1939 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001940
1941#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 {
1943 double x = 9006104071832581.0;
1944 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1945 detected_double_format = ieee_big_endian_format;
1946 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1947 detected_double_format = ieee_little_endian_format;
1948 else
1949 detected_double_format = unknown_format;
1950 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001951#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001953#endif
1954
1955#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 {
1957 float y = 16711938.0;
1958 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1959 detected_float_format = ieee_big_endian_format;
1960 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1961 detected_float_format = ieee_little_endian_format;
1962 else
1963 detected_float_format = unknown_format;
1964 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001965#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001967#endif
1968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 double_format = detected_double_format;
1970 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001973 if (FloatInfoType.tp_name == NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001974 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001975 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001976 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02001977 }
1978 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001979}
1980
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001981void
1982_PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001983{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001984 PyFloatObject *f = free_list, *next;
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001985 for (; f; f = next) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001986 next = (PyFloatObject*) Py_TYPE(f);
1987 PyObject_FREE(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001989 free_list = NULL;
1990 numfree = 0;
Christian Heimes15ebc882008-02-04 18:48:49 +00001991}
1992
1993void
Victor Stinnerbed48172019-08-27 00:12:32 +02001994_PyFloat_Fini(void)
Christian Heimes15ebc882008-02-04 18:48:49 +00001995{
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001996 _PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001997}
Tim Peters9905b942003-03-20 20:53:32 +00001998
David Malcolm49526f42012-06-22 14:55:41 -04001999/* Print summary info about the state of the optimized allocator */
2000void
2001_PyFloat_DebugMallocStats(FILE *out)
2002{
2003 _PyDebugAllocatorStats(out,
2004 "free PyFloatObject",
2005 numfree, sizeof(PyFloatObject));
2006}
2007
2008
Tim Peters9905b942003-03-20 20:53:32 +00002009/*----------------------------------------------------------------------------
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002010 * _PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h.
2011 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
2012 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
2013 * We use:
2014 * bits = (unsigned short)f; Note the truncation
2015 * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
2016 * bits++;
2017 * }
Tim Peters9905b942003-03-20 20:53:32 +00002018 */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002019
2020int
2021_PyFloat_Pack2(double x, unsigned char *p, int le)
2022{
2023 unsigned char sign;
2024 int e;
2025 double f;
2026 unsigned short bits;
2027 int incr = 1;
2028
2029 if (x == 0.0) {
2030 sign = (copysign(1.0, x) == -1.0);
2031 e = 0;
2032 bits = 0;
2033 }
2034 else if (Py_IS_INFINITY(x)) {
2035 sign = (x < 0.0);
2036 e = 0x1f;
2037 bits = 0;
2038 }
2039 else if (Py_IS_NAN(x)) {
2040 /* There are 2046 distinct half-precision NaNs (1022 signaling and
2041 1024 quiet), but there are only two quiet NaNs that don't arise by
2042 quieting a signaling NaN; we get those by setting the topmost bit
2043 of the fraction field and clearing all other fraction bits. We
2044 choose the one with the appropriate sign. */
2045 sign = (copysign(1.0, x) == -1.0);
2046 e = 0x1f;
2047 bits = 512;
2048 }
2049 else {
2050 sign = (x < 0.0);
2051 if (sign) {
2052 x = -x;
2053 }
2054
2055 f = frexp(x, &e);
2056 if (f < 0.5 || f >= 1.0) {
2057 PyErr_SetString(PyExc_SystemError,
2058 "frexp() result out of range");
2059 return -1;
2060 }
2061
2062 /* Normalize f to be in the range [1.0, 2.0) */
2063 f *= 2.0;
2064 e--;
2065
2066 if (e >= 16) {
2067 goto Overflow;
2068 }
2069 else if (e < -25) {
2070 /* |x| < 2**-25. Underflow to zero. */
2071 f = 0.0;
2072 e = 0;
2073 }
2074 else if (e < -14) {
2075 /* |x| < 2**-14. Gradual underflow */
2076 f = ldexp(f, 14 + e);
2077 e = 0;
2078 }
2079 else /* if (!(e == 0 && f == 0.0)) */ {
2080 e += 15;
2081 f -= 1.0; /* Get rid of leading 1 */
2082 }
2083
2084 f *= 1024.0; /* 2**10 */
2085 /* Round to even */
2086 bits = (unsigned short)f; /* Note the truncation */
2087 assert(bits < 1024);
2088 assert(e < 31);
2089 if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2090 ++bits;
2091 if (bits == 1024) {
2092 /* The carry propagated out of a string of 10 1 bits. */
2093 bits = 0;
2094 ++e;
2095 if (e == 31)
2096 goto Overflow;
2097 }
2098 }
2099 }
2100
2101 bits |= (e << 10) | (sign << 15);
2102
2103 /* Write out result. */
2104 if (le) {
2105 p += 1;
2106 incr = -1;
2107 }
2108
2109 /* First byte */
2110 *p = (unsigned char)((bits >> 8) & 0xFF);
2111 p += incr;
2112
2113 /* Second byte */
2114 *p = (unsigned char)(bits & 0xFF);
2115
2116 return 0;
2117
2118 Overflow:
2119 PyErr_SetString(PyExc_OverflowError,
2120 "float too large to pack with e format");
2121 return -1;
2122}
2123
Tim Peters9905b942003-03-20 20:53:32 +00002124int
2125_PyFloat_Pack4(double x, unsigned char *p, int le)
2126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 if (float_format == unknown_format) {
2128 unsigned char sign;
2129 int e;
2130 double f;
2131 unsigned int fbits;
2132 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 if (le) {
2135 p += 3;
2136 incr = -1;
2137 }
Tim Peters9905b942003-03-20 20:53:32 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 if (x < 0) {
2140 sign = 1;
2141 x = -x;
2142 }
2143 else
2144 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 /* Normalize f to be in the range [1.0, 2.0) */
2149 if (0.5 <= f && f < 1.0) {
2150 f *= 2.0;
2151 e--;
2152 }
2153 else if (f == 0.0)
2154 e = 0;
2155 else {
2156 PyErr_SetString(PyExc_SystemError,
2157 "frexp() result out of range");
2158 return -1;
2159 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (e >= 128)
2162 goto Overflow;
2163 else if (e < -126) {
2164 /* Gradual underflow */
2165 f = ldexp(f, 126 + e);
2166 e = 0;
2167 }
2168 else if (!(e == 0 && f == 0.0)) {
2169 e += 127;
2170 f -= 1.0; /* Get rid of leading 1 */
2171 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 f *= 8388608.0; /* 2**23 */
2174 fbits = (unsigned int)(f + 0.5); /* Round */
2175 assert(fbits <= 8388608);
2176 if (fbits >> 23) {
2177 /* The carry propagated out of a string of 23 1 bits. */
2178 fbits = 0;
2179 ++e;
2180 if (e >= 255)
2181 goto Overflow;
2182 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 /* First byte */
2185 *p = (sign << 7) | (e >> 1);
2186 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 /* Second byte */
2189 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2190 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 /* Third byte */
2193 *p = (fbits >> 8) & 0xFF;
2194 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 /* Fourth byte */
2197 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 /* Done */
2200 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 }
2203 else {
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002204 float y = (float)x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002206
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002207 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002209
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002210 unsigned char s[sizeof(float)];
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002211 memcpy(s, &y, sizeof(float));
2212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 if ((float_format == ieee_little_endian_format && !le)
2214 || (float_format == ieee_big_endian_format && le)) {
2215 p += 3;
2216 incr = -1;
2217 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 for (i = 0; i < 4; i++) {
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002220 *p = s[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 p += incr;
2222 }
2223 return 0;
2224 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002225 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 PyErr_SetString(PyExc_OverflowError,
2227 "float too large to pack with f format");
2228 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002229}
2230
2231int
2232_PyFloat_Pack8(double x, unsigned char *p, int le)
2233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 if (double_format == unknown_format) {
2235 unsigned char sign;
2236 int e;
2237 double f;
2238 unsigned int fhi, flo;
2239 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 if (le) {
2242 p += 7;
2243 incr = -1;
2244 }
Tim Peters9905b942003-03-20 20:53:32 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 if (x < 0) {
2247 sign = 1;
2248 x = -x;
2249 }
2250 else
2251 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 /* Normalize f to be in the range [1.0, 2.0) */
2256 if (0.5 <= f && f < 1.0) {
2257 f *= 2.0;
2258 e--;
2259 }
2260 else if (f == 0.0)
2261 e = 0;
2262 else {
2263 PyErr_SetString(PyExc_SystemError,
2264 "frexp() result out of range");
2265 return -1;
2266 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 if (e >= 1024)
2269 goto Overflow;
2270 else if (e < -1022) {
2271 /* Gradual underflow */
2272 f = ldexp(f, 1022 + e);
2273 e = 0;
2274 }
2275 else if (!(e == 0 && f == 0.0)) {
2276 e += 1023;
2277 f -= 1.0; /* Get rid of leading 1 */
2278 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2281 f *= 268435456.0; /* 2**28 */
2282 fhi = (unsigned int)f; /* Truncate */
2283 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 f -= (double)fhi;
2286 f *= 16777216.0; /* 2**24 */
2287 flo = (unsigned int)(f + 0.5); /* Round */
2288 assert(flo <= 16777216);
2289 if (flo >> 24) {
2290 /* The carry propagated out of a string of 24 1 bits. */
2291 flo = 0;
2292 ++fhi;
2293 if (fhi >> 28) {
2294 /* And it also progagated out of the next 28 bits. */
2295 fhi = 0;
2296 ++e;
2297 if (e >= 2047)
2298 goto Overflow;
2299 }
2300 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 /* First byte */
2303 *p = (sign << 7) | (e >> 4);
2304 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 /* Second byte */
2307 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2308 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* Third byte */
2311 *p = (fhi >> 16) & 0xFF;
2312 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 /* Fourth byte */
2315 *p = (fhi >> 8) & 0xFF;
2316 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 /* Fifth byte */
2319 *p = fhi & 0xFF;
2320 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 /* Sixth byte */
2323 *p = (flo >> 16) & 0xFF;
2324 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 /* Seventh byte */
2327 *p = (flo >> 8) & 0xFF;
2328 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 /* Eighth byte */
2331 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002332 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 /* Done */
2335 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 Overflow:
2338 PyErr_SetString(PyExc_OverflowError,
2339 "float too large to pack with d format");
2340 return -1;
2341 }
2342 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002343 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 if ((double_format == ieee_little_endian_format && !le)
2347 || (double_format == ieee_big_endian_format && le)) {
2348 p += 7;
2349 incr = -1;
2350 }
2351
2352 for (i = 0; i < 8; i++) {
2353 *p = *s++;
2354 p += incr;
2355 }
2356 return 0;
2357 }
Tim Peters9905b942003-03-20 20:53:32 +00002358}
2359
2360double
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002361_PyFloat_Unpack2(const unsigned char *p, int le)
2362{
2363 unsigned char sign;
2364 int e;
2365 unsigned int f;
2366 double x;
2367 int incr = 1;
2368
2369 if (le) {
2370 p += 1;
2371 incr = -1;
2372 }
2373
2374 /* First byte */
2375 sign = (*p >> 7) & 1;
2376 e = (*p & 0x7C) >> 2;
2377 f = (*p & 0x03) << 8;
2378 p += incr;
2379
2380 /* Second byte */
2381 f |= *p;
2382
2383 if (e == 0x1f) {
2384#ifdef PY_NO_SHORT_FLOAT_REPR
2385 if (f == 0) {
2386 /* Infinity */
2387 return sign ? -Py_HUGE_VAL : Py_HUGE_VAL;
2388 }
2389 else {
2390 /* NaN */
2391#ifdef Py_NAN
2392 return sign ? -Py_NAN : Py_NAN;
2393#else
2394 PyErr_SetString(
2395 PyExc_ValueError,
2396 "can't unpack IEEE 754 NaN "
2397 "on platform that does not support NaNs");
2398 return -1;
2399#endif /* #ifdef Py_NAN */
2400 }
2401#else
2402 if (f == 0) {
2403 /* Infinity */
2404 return _Py_dg_infinity(sign);
2405 }
2406 else {
2407 /* NaN */
2408 return _Py_dg_stdnan(sign);
2409 }
2410#endif /* #ifdef PY_NO_SHORT_FLOAT_REPR */
2411 }
2412
2413 x = (double)f / 1024.0;
2414
2415 if (e == 0) {
2416 e = -14;
2417 }
2418 else {
2419 x += 1.0;
2420 e -= 15;
2421 }
2422 x = ldexp(x, e);
2423
2424 if (sign)
2425 x = -x;
2426
2427 return x;
2428}
2429
2430double
Tim Peters9905b942003-03-20 20:53:32 +00002431_PyFloat_Unpack4(const unsigned char *p, int le)
2432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 if (float_format == unknown_format) {
2434 unsigned char sign;
2435 int e;
2436 unsigned int f;
2437 double x;
2438 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 if (le) {
2441 p += 3;
2442 incr = -1;
2443 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 /* First byte */
2446 sign = (*p >> 7) & 1;
2447 e = (*p & 0x7F) << 1;
2448 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 /* Second byte */
2451 e |= (*p >> 7) & 1;
2452 f = (*p & 0x7F) << 16;
2453 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 if (e == 255) {
2456 PyErr_SetString(
2457 PyExc_ValueError,
2458 "can't unpack IEEE 754 special value "
2459 "on non-IEEE platform");
2460 return -1;
2461 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 /* Third byte */
2464 f |= *p << 8;
2465 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 /* Fourth byte */
2468 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 /* XXX This sadly ignores Inf/NaN issues */
2473 if (e == 0)
2474 e = -126;
2475 else {
2476 x += 1.0;
2477 e -= 127;
2478 }
2479 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 if (sign)
2482 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 return x;
2485 }
2486 else {
2487 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 if ((float_format == ieee_little_endian_format && !le)
2490 || (float_format == ieee_big_endian_format && le)) {
2491 char buf[4];
2492 char *d = &buf[3];
2493 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 for (i = 0; i < 4; i++) {
2496 *d-- = *p++;
2497 }
2498 memcpy(&x, buf, 4);
2499 }
2500 else {
2501 memcpy(&x, p, 4);
2502 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 return x;
2505 }
Tim Peters9905b942003-03-20 20:53:32 +00002506}
2507
2508double
2509_PyFloat_Unpack8(const unsigned char *p, int le)
2510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 if (double_format == unknown_format) {
2512 unsigned char sign;
2513 int e;
2514 unsigned int fhi, flo;
2515 double x;
2516 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 if (le) {
2519 p += 7;
2520 incr = -1;
2521 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 /* First byte */
2524 sign = (*p >> 7) & 1;
2525 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 /* Second byte */
2530 e |= (*p >> 4) & 0xF;
2531 fhi = (*p & 0xF) << 24;
2532 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 if (e == 2047) {
2535 PyErr_SetString(
2536 PyExc_ValueError,
2537 "can't unpack IEEE 754 special value "
2538 "on non-IEEE platform");
2539 return -1.0;
2540 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 /* Third byte */
2543 fhi |= *p << 16;
2544 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 /* Fourth byte */
2547 fhi |= *p << 8;
2548 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 /* Fifth byte */
2551 fhi |= *p;
2552 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 /* Sixth byte */
2555 flo = *p << 16;
2556 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 /* Seventh byte */
2559 flo |= *p << 8;
2560 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 /* Eighth byte */
2563 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2566 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 if (e == 0)
2569 e = -1022;
2570 else {
2571 x += 1.0;
2572 e -= 1023;
2573 }
2574 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 if (sign)
2577 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 return x;
2580 }
2581 else {
2582 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 if ((double_format == ieee_little_endian_format && !le)
2585 || (double_format == ieee_big_endian_format && le)) {
2586 char buf[8];
2587 char *d = &buf[7];
2588 int i;
2589
2590 for (i = 0; i < 8; i++) {
2591 *d-- = *p++;
2592 }
2593 memcpy(&x, buf, 8);
2594 }
2595 else {
2596 memcpy(&x, p, 8);
2597 }
2598
2599 return x;
2600 }
Tim Peters9905b942003-03-20 20:53:32 +00002601}