blob: 04f968e56b142761cd02f6ddfc72f791576b8b41 [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{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200865 double x = PyFloat_AsDouble(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 (void)modf(x, &wholepart);
869 /* Try to get out cheap if this fits in a Python int. The attempt
870 * to cast to long must be protected, as C doesn't define what
871 * happens if the double is too big to fit in a long. Some rare
872 * systems raise an exception then (RISCOS was mentioned as one,
873 * and someone using a non-default option on Sun also bumped into
874 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
875 * still be vulnerable: if a long has more bits of precision than
876 * a double, casting MIN/MAX to double may yield an approximation,
877 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
878 * yield true from the C expression wholepart<=LONG_MAX, despite
879 * that wholepart is actually greater than LONG_MAX.
880 */
881 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
882 const long aslong = (long)wholepart;
883 return PyLong_FromLong(aslong);
884 }
885 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000886}
887
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +0300888/*[clinic input]
889float.__floor__
890
891Return the floor as an Integral.
892[clinic start generated code]*/
893
894static PyObject *
895float___floor___impl(PyObject *self)
896/*[clinic end generated code: output=e0551dbaea8c01d1 input=77bb13eb12e268df]*/
897{
898 double x = PyFloat_AS_DOUBLE(self);
899 return PyLong_FromDouble(floor(x));
900}
901
902/*[clinic input]
903float.__ceil__
904
905Return the ceiling as an Integral.
906[clinic start generated code]*/
907
908static PyObject *
909float___ceil___impl(PyObject *self)
910/*[clinic end generated code: output=a2fd8858f73736f9 input=79e41ae94aa0a516]*/
911{
912 double x = PyFloat_AS_DOUBLE(self);
913 return PyLong_FromDouble(ceil(x));
914}
915
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000916/* double_round: rounds a finite double to the closest multiple of
917 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
918 ndigits <= 323). Returns a Python float, or sets a Python error and
919 returns NULL on failure (OverflowError and memory errors are possible). */
920
921#ifndef PY_NO_SHORT_FLOAT_REPR
922/* version of double_round that uses the correctly-rounded string<->double
923 conversions from Python/dtoa.c */
924
925static PyObject *
926double_round(double x, int ndigits) {
927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 double rounded;
929 Py_ssize_t buflen, mybuflen=100;
930 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
931 int decpt, sign;
932 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000933 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000936 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000938 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 if (buf == NULL) {
940 PyErr_NoMemory();
941 return NULL;
942 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
945 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
946 buflen = buf_end - buf;
947 if (buflen + 8 > mybuflen) {
948 mybuflen = buflen+8;
949 mybuf = (char *)PyMem_Malloc(mybuflen);
950 if (mybuf == NULL) {
951 PyErr_NoMemory();
952 goto exit;
953 }
954 }
955 /* copy buf to mybuf, adding exponent, sign and leading 0 */
956 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
957 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 /* and convert the resulting string back to a double */
960 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000961 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000963 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 if (errno == ERANGE && fabs(rounded) >= 1.)
965 PyErr_SetString(PyExc_OverflowError,
966 "rounded value too large to represent");
967 else
968 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* done computing value; now clean up */
971 if (mybuf != shortbuf)
972 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000973 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 _Py_dg_freedtoa(buf);
975 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000976}
977
978#else /* PY_NO_SHORT_FLOAT_REPR */
979
980/* fallback version, to be used when correctly rounded binary<->decimal
981 conversions aren't available */
982
983static PyObject *
984double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 double pow1, pow2, y, z;
986 if (ndigits >= 0) {
987 if (ndigits > 22) {
988 /* pow1 and pow2 are each safe from overflow, but
989 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
990 pow1 = pow(10.0, (double)(ndigits-22));
991 pow2 = 1e22;
992 }
993 else {
994 pow1 = pow(10.0, (double)ndigits);
995 pow2 = 1.0;
996 }
997 y = (x*pow1)*pow2;
998 /* if y overflows, then rounded value is exactly x */
999 if (!Py_IS_FINITE(y))
1000 return PyFloat_FromDouble(x);
1001 }
1002 else {
1003 pow1 = pow(10.0, (double)-ndigits);
1004 pow2 = 1.0; /* unused; silences a gcc compiler warning */
1005 y = x / pow1;
1006 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 z = round(y);
1009 if (fabs(y-z) == 0.5)
1010 /* halfway between two integers; use round-half-even */
1011 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 if (ndigits >= 0)
1014 z = (z / pow2) / pow1;
1015 else
1016 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 /* if computation resulted in overflow, raise OverflowError */
1019 if (!Py_IS_FINITE(z)) {
1020 PyErr_SetString(PyExc_OverflowError,
1021 "overflow occurred during round");
1022 return NULL;
1023 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001026}
1027
1028#endif /* PY_NO_SHORT_FLOAT_REPR */
1029
1030/* round a Python float v to the closest multiple of 10**-ndigits */
1031
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001032/*[clinic input]
1033float.__round__
1034
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001035 ndigits as o_ndigits: object = None
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001036 /
1037
1038Return the Integral closest to x, rounding half toward even.
1039
1040When an argument is passed, work like built-in round(x, ndigits).
1041[clinic start generated code]*/
1042
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001043static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001044float___round___impl(PyObject *self, PyObject *o_ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001045/*[clinic end generated code: output=374c36aaa0f13980 input=fc0fe25924fbc9ed]*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 double x, rounded;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001049
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001050 x = PyFloat_AsDouble(self);
Serhiy Storchaka279f4462019-09-14 12:24:05 +03001051 if (o_ndigits == Py_None) {
Steve Dowercb39d1f2015-04-15 16:10:59 -04001052 /* single-argument round or with None ndigits:
1053 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 rounded = round(x);
1055 if (fabs(x-rounded) == 0.5)
1056 /* halfway case: round to even */
1057 rounded = 2.0*round(x/2.0);
1058 return PyLong_FromDouble(rounded);
1059 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 /* interpret second argument as a Py_ssize_t; clips on overflow */
1062 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1063 if (ndigits == -1 && PyErr_Occurred())
1064 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 /* nans and infinities round to themselves */
1067 if (!Py_IS_FINITE(x))
1068 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1071 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1072 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001073#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1074#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 if (ndigits > NDIGITS_MAX)
1076 /* return x */
1077 return PyFloat_FromDouble(x);
1078 else if (ndigits < NDIGITS_MIN)
1079 /* return 0.0, but with sign of x */
1080 return PyFloat_FromDouble(0.0*x);
1081 else
1082 /* finite x, and ndigits is not unreasonably large */
1083 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001084#undef NDIGITS_MAX
1085#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001086}
1087
1088static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001089float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 if (PyFloat_CheckExact(v))
1092 Py_INCREF(v);
1093 else
1094 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1095 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001096}
1097
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001098/*[clinic input]
1099float.conjugate
1100
1101Return self, the complex conjugate of any float.
1102[clinic start generated code]*/
1103
1104static PyObject *
1105float_conjugate_impl(PyObject *self)
1106/*[clinic end generated code: output=8ca292c2479194af input=82ba6f37a9ff91dd]*/
1107{
1108 return float_float(self);
1109}
1110
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001111/* turn ASCII hex characters into integer values and vice versa */
1112
1113static char
1114char_from_hex(int x)
1115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001117 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001118}
1119
1120static int
1121hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 int x;
1123 switch(c) {
1124 case '0':
1125 x = 0;
1126 break;
1127 case '1':
1128 x = 1;
1129 break;
1130 case '2':
1131 x = 2;
1132 break;
1133 case '3':
1134 x = 3;
1135 break;
1136 case '4':
1137 x = 4;
1138 break;
1139 case '5':
1140 x = 5;
1141 break;
1142 case '6':
1143 x = 6;
1144 break;
1145 case '7':
1146 x = 7;
1147 break;
1148 case '8':
1149 x = 8;
1150 break;
1151 case '9':
1152 x = 9;
1153 break;
1154 case 'a':
1155 case 'A':
1156 x = 10;
1157 break;
1158 case 'b':
1159 case 'B':
1160 x = 11;
1161 break;
1162 case 'c':
1163 case 'C':
1164 x = 12;
1165 break;
1166 case 'd':
1167 case 'D':
1168 x = 13;
1169 break;
1170 case 'e':
1171 case 'E':
1172 x = 14;
1173 break;
1174 case 'f':
1175 case 'F':
1176 x = 15;
1177 break;
1178 default:
1179 x = -1;
1180 break;
1181 }
1182 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001183}
1184
1185/* convert a float to a hexadecimal string */
1186
1187/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1188 of the form 4k+1. */
1189#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1190
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001191/*[clinic input]
1192float.hex
1193
1194Return a hexadecimal representation of a floating-point number.
1195
1196>>> (-0.1).hex()
1197'-0x1.999999999999ap-4'
1198>>> 3.14159.hex()
1199'0x1.921f9f01b866ep+1'
1200[clinic start generated code]*/
1201
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001202static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001203float_hex_impl(PyObject *self)
1204/*[clinic end generated code: output=0ebc9836e4d302d4 input=bec1271a33d47e67]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 double x, m;
1207 int e, shift, i, si, esign;
1208 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1209 trailing NUL byte. */
1210 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001211
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001212 CONVERT_TO_DOUBLE(self, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001215 return float_repr((PyFloatObject *)self);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001218 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 return PyUnicode_FromString("-0x0.0p+0");
1220 else
1221 return PyUnicode_FromString("0x0.0p+0");
1222 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001225 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 m = ldexp(m, shift);
1227 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 si = 0;
1230 s[si] = char_from_hex((int)m);
1231 si++;
1232 m -= (int)m;
1233 s[si] = '.';
1234 si++;
1235 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1236 m *= 16.0;
1237 s[si] = char_from_hex((int)m);
1238 si++;
1239 m -= (int)m;
1240 }
1241 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (e < 0) {
1244 esign = (int)'-';
1245 e = -e;
1246 }
1247 else
1248 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 if (x < 0.0)
1251 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1252 else
1253 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001254}
1255
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001256/* Convert a hexadecimal string to a float. */
1257
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001258/*[clinic input]
1259@classmethod
1260float.fromhex
1261
1262 string: object
1263 /
1264
1265Create a floating-point number from a hexadecimal string.
1266
1267>>> float.fromhex('0x1.ffffp10')
12682047.984375
1269>>> float.fromhex('-0x1p-1074')
1270-5e-324
1271[clinic start generated code]*/
1272
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001273static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001274float_fromhex(PyTypeObject *type, PyObject *string)
1275/*[clinic end generated code: output=46c0274d22b78e82 input=0407bebd354bca89]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001276{
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001277 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 double x;
1279 long exp, top_exp, lsb, key_digit;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001280 const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 int half_eps, digit, round_up, negate=0;
1282 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 /*
1285 * For the sake of simplicity and correctness, we impose an artificial
1286 * limit on ndigits, the total number of hex digits in the coefficient
1287 * The limit is chosen to ensure that, writing exp for the exponent,
1288 *
1289 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1290 * guaranteed to overflow (provided it's nonzero)
1291 *
1292 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1293 * guaranteed to underflow to 0.
1294 *
1295 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1296 * overflow in the calculation of exp and top_exp below.
1297 *
1298 * More specifically, ndigits is assumed to satisfy the following
1299 * inequalities:
1300 *
1301 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1302 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1303 *
1304 * If either of these inequalities is not satisfied, a ValueError is
1305 * raised. Otherwise, write x for the value of the hex string, and
1306 * assume x is nonzero. Then
1307 *
1308 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1309 *
1310 * Now if exp > LONG_MAX/2 then:
1311 *
1312 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1313 * = DBL_MAX_EXP
1314 *
1315 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1316 * double, so overflows. If exp < LONG_MIN/2, then
1317 *
1318 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1319 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1320 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1321 *
1322 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1323 * when converted to a C double.
1324 *
1325 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1326 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1327 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001328
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001329 s = PyUnicode_AsUTF8AndSize(string, &length);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 if (s == NULL)
1331 return NULL;
1332 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 /********************
1335 * Parse the string *
1336 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 /* leading whitespace */
1339 while (Py_ISSPACE(*s))
1340 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 /* infinities and nans */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001343 x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 if (coeff_end != s) {
1345 s = coeff_end;
1346 goto finished;
1347 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 /* optional sign */
1350 if (*s == '-') {
1351 s++;
1352 negate = 1;
1353 }
1354 else if (*s == '+')
1355 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 /* [0x] */
1358 s_store = s;
1359 if (*s == '0') {
1360 s++;
1361 if (*s == 'x' || *s == 'X')
1362 s++;
1363 else
1364 s = s_store;
1365 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 /* coefficient: <integer> [. <fraction>] */
1368 coeff_start = s;
1369 while (hex_from_char(*s) >= 0)
1370 s++;
1371 s_store = s;
1372 if (*s == '.') {
1373 s++;
1374 while (hex_from_char(*s) >= 0)
1375 s++;
1376 coeff_end = s-1;
1377 }
1378 else
1379 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 /* ndigits = total # of hex digits; fdigits = # after point */
1382 ndigits = coeff_end - coeff_start;
1383 fdigits = coeff_end - s_store;
1384 if (ndigits == 0)
1385 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001386 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1387 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 /* [p <exponent>] */
1391 if (*s == 'p' || *s == 'P') {
1392 s++;
1393 exp_start = s;
1394 if (*s == '-' || *s == '+')
1395 s++;
1396 if (!('0' <= *s && *s <= '9'))
1397 goto parse_error;
1398 s++;
1399 while ('0' <= *s && *s <= '9')
1400 s++;
1401 exp = strtol(exp_start, NULL, 10);
1402 }
1403 else
1404 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001405
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001406/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1408 coeff_end-(j) : \
1409 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 /*******************************************
1412 * Compute rounded value of the hex string *
1413 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 /* Discard leading zeros, and catch extreme overflow and underflow */
1416 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1417 ndigits--;
1418 if (ndigits == 0 || exp < LONG_MIN/2) {
1419 x = 0.0;
1420 goto finished;
1421 }
1422 if (exp > LONG_MAX/2)
1423 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 /* Adjust exponent for fractional part. */
1426 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1429 top_exp = exp + 4*((long)ndigits - 1);
1430 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1431 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 /* catch almost all nonextreme cases of overflow and underflow here */
1434 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1435 x = 0.0;
1436 goto finished;
1437 }
1438 if (top_exp > DBL_MAX_EXP)
1439 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 /* lsb = exponent of least significant bit of the *rounded* value.
1442 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001443 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 x = 0.0;
1446 if (exp >= lsb) {
1447 /* no rounding required */
1448 for (i = ndigits-1; i >= 0; i--)
1449 x = 16.0*x + HEX_DIGIT(i);
1450 x = ldexp(x, (int)(exp));
1451 goto finished;
1452 }
1453 /* rounding required. key_digit is the index of the hex digit
1454 containing the first bit to be rounded away. */
1455 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1456 key_digit = (lsb - exp - 1) / 4;
1457 for (i = ndigits-1; i > key_digit; i--)
1458 x = 16.0*x + HEX_DIGIT(i);
1459 digit = HEX_DIGIT(key_digit);
1460 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1463 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1464 if ((digit & half_eps) != 0) {
1465 round_up = 0;
1466 if ((digit & (3*half_eps-1)) != 0 ||
1467 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1468 round_up = 1;
1469 else
1470 for (i = key_digit-1; i >= 0; i--)
1471 if (HEX_DIGIT(i) != 0) {
1472 round_up = 1;
1473 break;
1474 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001475 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 x += 2*half_eps;
1477 if (top_exp == DBL_MAX_EXP &&
1478 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1479 /* overflow corner case: pre-rounded value <
1480 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1481 goto overflow_error;
1482 }
1483 }
1484 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001485
1486 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 /* optional trailing whitespace leading to the end of the string */
1488 while (Py_ISSPACE(*s))
1489 s++;
1490 if (s != s_end)
1491 goto parse_error;
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001492 result = PyFloat_FromDouble(negate ? -x : x);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001493 if (type != &PyFloat_Type && result != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001494 Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001495 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001497
1498 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 PyErr_SetString(PyExc_OverflowError,
1500 "hexadecimal value too large to represent as a float");
1501 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001502
1503 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 PyErr_SetString(PyExc_ValueError,
1505 "invalid hexadecimal floating-point string");
1506 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001507
1508 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 PyErr_SetString(PyExc_ValueError,
1510 "hexadecimal string too long to convert");
1511 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001512}
1513
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001514/*[clinic input]
1515float.as_integer_ratio
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001516
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001517Return integer ratio.
1518
1519Return a pair of integers, whose ratio is exactly equal to the original float
1520and with a positive denominator.
1521
1522Raise OverflowError on infinities and a ValueError on NaNs.
1523
1524>>> (10.0).as_integer_ratio()
1525(10, 1)
1526>>> (0.0).as_integer_ratio()
1527(0, 1)
1528>>> (-.25).as_integer_ratio()
1529(-1, 4)
1530[clinic start generated code]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001531
Christian Heimes26855632008-01-27 23:50:43 +00001532static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001533float_as_integer_ratio_impl(PyObject *self)
1534/*[clinic end generated code: output=65f25f0d8d30a712 input=e21d08b4630c2e44]*/
Christian Heimes26855632008-01-27 23:50:43 +00001535{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001536 double self_double;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 double float_part;
1538 int exponent;
1539 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 PyObject *py_exponent = NULL;
1542 PyObject *numerator = NULL;
1543 PyObject *denominator = NULL;
1544 PyObject *result_pair = NULL;
1545 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001546
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001547 CONVERT_TO_DOUBLE(self, self_double);
Christian Heimes26855632008-01-27 23:50:43 +00001548
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001549 if (Py_IS_INFINITY(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001550 PyErr_SetString(PyExc_OverflowError,
1551 "cannot convert Infinity to integer ratio");
1552 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001554 if (Py_IS_NAN(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001555 PyErr_SetString(PyExc_ValueError,
1556 "cannot convert NaN to integer ratio");
1557 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 }
Christian Heimes26855632008-01-27 23:50:43 +00001559
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001560 float_part = frexp(self_double, &exponent); /* self_double == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1563 float_part *= 2.0;
1564 exponent--;
1565 }
1566 /* self == float_part * 2**exponent exactly and float_part is integral.
1567 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1568 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 numerator = PyLong_FromDouble(float_part);
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001571 if (numerator == NULL)
1572 goto error;
1573 denominator = PyLong_FromLong(1);
1574 if (denominator == NULL)
1575 goto error;
1576 py_exponent = PyLong_FromLong(Py_ABS(exponent));
1577 if (py_exponent == NULL)
1578 goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 /* fold in 2**exponent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 if (exponent > 0) {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001582 Py_SETREF(numerator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001583 long_methods->nb_lshift(numerator, py_exponent));
1584 if (numerator == NULL)
1585 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 }
1587 else {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001588 Py_SETREF(denominator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001589 long_methods->nb_lshift(denominator, py_exponent));
1590 if (denominator == NULL)
1591 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 }
1593
1594 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001595
Christian Heimes26855632008-01-27 23:50:43 +00001596error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 Py_XDECREF(py_exponent);
1598 Py_XDECREF(denominator);
1599 Py_XDECREF(numerator);
1600 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001601}
1602
Jeremy Hylton938ace62002-07-17 16:30:39 +00001603static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001604float_subtype_new(PyTypeObject *type, PyObject *x);
1605
1606/*[clinic input]
1607@classmethod
1608float.__new__ as float_new
Serhiy Storchakaba85d692017-03-30 09:09:41 +03001609 x: object(c_default="_PyLong_Zero") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001610 /
1611
1612Convert a string or number to a floating point number, if possible.
1613[clinic start generated code]*/
Guido van Rossumbef14172001-08-29 15:47:46 +00001614
Tim Peters6d6c1a32001-08-02 04:15:00 +00001615static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001616float_new_impl(PyTypeObject *type, PyObject *x)
Serhiy Storchakabae68812017-04-05 12:00:42 +03001617/*[clinic end generated code: output=ccf1e8dc460ba6ba input=540ee77c204ff87a]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00001618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 if (type != &PyFloat_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001620 return float_subtype_new(type, x); /* Wimp out */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 /* If it's a string, but not a string subclass, use
1622 PyFloat_FromString. */
1623 if (PyUnicode_CheckExact(x))
1624 return PyFloat_FromString(x);
1625 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001626}
1627
Guido van Rossumbef14172001-08-29 15:47:46 +00001628/* Wimpy, slow approach to tp_new calls for subtypes of float:
1629 first create a regular float from whatever arguments we got,
1630 then allocate a subtype instance and initialize its ob_fval
1631 from the regular float. The regular float is then thrown away.
1632*/
1633static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001634float_subtype_new(PyTypeObject *type, PyObject *x)
Guido van Rossumbef14172001-08-29 15:47:46 +00001635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 assert(PyType_IsSubtype(type, &PyFloat_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001639 tmp = float_new_impl(&PyFloat_Type, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 if (tmp == NULL)
1641 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001642 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 newobj = type->tp_alloc(type, 0);
1644 if (newobj == NULL) {
1645 Py_DECREF(tmp);
1646 return NULL;
1647 }
1648 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1649 Py_DECREF(tmp);
1650 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001651}
1652
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001653/*[clinic input]
1654float.__getnewargs__
1655[clinic start generated code]*/
1656
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001657static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001658float___getnewargs___impl(PyObject *self)
1659/*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001660{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001661 return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001662}
1663
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001664/* this is for the benefit of the pack/unpack routines below */
1665
1666typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001668} float_format_type;
1669
1670static float_format_type double_format, float_format;
1671static float_format_type detected_double_format, detected_float_format;
1672
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001673/*[clinic input]
1674@classmethod
1675float.__getformat__
1676
1677 typestr: str
1678 Must be 'double' or 'float'.
1679 /
1680
1681You probably don't want to use this function.
1682
1683It exists mainly to be used in Python's test suite.
1684
1685This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
1686little-endian' best describes the format of floating point numbers used by the
1687C type named by typestr.
1688[clinic start generated code]*/
1689
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001690static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001691float___getformat___impl(PyTypeObject *type, const char *typestr)
1692/*[clinic end generated code: output=2bfb987228cc9628 input=d5a52600f835ad67]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001695
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001696 if (strcmp(typestr, "double") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 r = double_format;
1698 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001699 else if (strcmp(typestr, "float") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 r = float_format;
1701 }
1702 else {
1703 PyErr_SetString(PyExc_ValueError,
1704 "__getformat__() argument 1 must be "
1705 "'double' or 'float'");
1706 return NULL;
1707 }
1708
1709 switch (r) {
1710 case unknown_format:
1711 return PyUnicode_FromString("unknown");
1712 case ieee_little_endian_format:
1713 return PyUnicode_FromString("IEEE, little-endian");
1714 case ieee_big_endian_format:
1715 return PyUnicode_FromString("IEEE, big-endian");
1716 default:
Victor Stinner04394df2019-11-18 17:39:48 +01001717 PyErr_SetString(PyExc_RuntimeError,
1718 "insane float_format or double_format");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 return NULL;
1720 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001721}
1722
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001723/*[clinic input]
1724@classmethod
1725float.__set_format__
1726
1727 typestr: str
1728 Must be 'double' or 'float'.
1729 fmt: str
1730 Must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian',
1731 and in addition can only be one of the latter two if it appears to
1732 match the underlying C reality.
1733 /
1734
1735You probably don't want to use this function.
1736
1737It exists mainly to be used in Python's test suite.
1738
1739Override the automatic determination of C-level floating point type.
1740This affects how floats are converted to and from binary strings.
1741[clinic start generated code]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001742
1743static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001744float___set_format___impl(PyTypeObject *type, const char *typestr,
1745 const char *fmt)
1746/*[clinic end generated code: output=504460f5dc85acbd input=5306fa2b81a997e4]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 float_format_type f;
1749 float_format_type detected;
1750 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 if (strcmp(typestr, "double") == 0) {
1753 p = &double_format;
1754 detected = detected_double_format;
1755 }
1756 else if (strcmp(typestr, "float") == 0) {
1757 p = &float_format;
1758 detected = detected_float_format;
1759 }
1760 else {
1761 PyErr_SetString(PyExc_ValueError,
1762 "__setformat__() argument 1 must "
1763 "be 'double' or 'float'");
1764 return NULL;
1765 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001766
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001767 if (strcmp(fmt, "unknown") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 f = unknown_format;
1769 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001770 else if (strcmp(fmt, "IEEE, little-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 f = ieee_little_endian_format;
1772 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001773 else if (strcmp(fmt, "IEEE, big-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 f = ieee_big_endian_format;
1775 }
1776 else {
1777 PyErr_SetString(PyExc_ValueError,
1778 "__setformat__() argument 2 must be "
1779 "'unknown', 'IEEE, little-endian' or "
1780 "'IEEE, big-endian'");
1781 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 if (f != unknown_format && f != detected) {
1786 PyErr_Format(PyExc_ValueError,
1787 "can only set %s format to 'unknown' or the "
1788 "detected platform value", typestr);
1789 return NULL;
1790 }
1791
1792 *p = f;
1793 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001794}
1795
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001796static PyObject *
1797float_getreal(PyObject *v, void *closure)
1798{
1799 return float_float(v);
1800}
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001801
Guido van Rossumb43daf72007-08-01 18:08:08 +00001802static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001803float_getimag(PyObject *v, void *closure)
Guido van Rossumb43daf72007-08-01 18:08:08 +00001804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001806}
1807
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001808/*[clinic input]
1809float.__format__
1810
1811 format_spec: unicode
1812 /
1813
1814Formats the float according to format_spec.
1815[clinic start generated code]*/
1816
Eric Smith8c663262007-08-25 02:26:07 +00001817static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001818float___format___impl(PyObject *self, PyObject *format_spec)
1819/*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/
Eric Smith8c663262007-08-25 02:26:07 +00001820{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001821 _PyUnicodeWriter writer;
1822 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001823
Victor Stinner8f674cc2013-04-17 23:02:17 +02001824 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001825 ret = _PyFloat_FormatAdvancedWriter(
1826 &writer,
1827 self,
1828 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1829 if (ret == -1) {
1830 _PyUnicodeWriter_Dealloc(&writer);
1831 return NULL;
1832 }
1833 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001834}
1835
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001836static PyMethodDef float_methods[] = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001837 FLOAT_CONJUGATE_METHODDEF
1838 FLOAT___TRUNC___METHODDEF
Batuhan Taşkayacb8b9462019-12-16 01:00:28 +03001839 FLOAT___FLOOR___METHODDEF
1840 FLOAT___CEIL___METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001841 FLOAT___ROUND___METHODDEF
1842 FLOAT_AS_INTEGER_RATIO_METHODDEF
1843 FLOAT_FROMHEX_METHODDEF
1844 FLOAT_HEX_METHODDEF
1845 FLOAT_IS_INTEGER_METHODDEF
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001846 FLOAT___GETNEWARGS___METHODDEF
1847 FLOAT___GETFORMAT___METHODDEF
1848 FLOAT___SET_FORMAT___METHODDEF
1849 FLOAT___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001851};
1852
Guido van Rossumb43daf72007-08-01 18:08:08 +00001853static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 {"real",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001855 float_getreal, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001856 "the real part of a complex number",
1857 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 {"imag",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001859 float_getimag, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001860 "the imaginary part of a complex number",
1861 NULL},
1862 {NULL} /* Sentinel */
1863};
1864
Tim Peters6d6c1a32001-08-02 04:15:00 +00001865
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001866static PyNumberMethods float_as_number = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001867 float_add, /* nb_add */
1868 float_sub, /* nb_subtract */
1869 float_mul, /* nb_multiply */
1870 float_rem, /* nb_remainder */
1871 float_divmod, /* nb_divmod */
1872 float_pow, /* nb_power */
1873 (unaryfunc)float_neg, /* nb_negative */
1874 float_float, /* nb_positive */
1875 (unaryfunc)float_abs, /* nb_absolute */
1876 (inquiry)float_bool, /* nb_bool */
1877 0, /* nb_invert */
1878 0, /* nb_lshift */
1879 0, /* nb_rshift */
1880 0, /* nb_and */
1881 0, /* nb_xor */
1882 0, /* nb_or */
1883 float___trunc___impl, /* nb_int */
1884 0, /* nb_reserved */
1885 float_float, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 0, /* nb_inplace_add */
1887 0, /* nb_inplace_subtract */
1888 0, /* nb_inplace_multiply */
1889 0, /* nb_inplace_remainder */
1890 0, /* nb_inplace_power */
1891 0, /* nb_inplace_lshift */
1892 0, /* nb_inplace_rshift */
1893 0, /* nb_inplace_and */
1894 0, /* nb_inplace_xor */
1895 0, /* nb_inplace_or */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001896 float_floor_div, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 float_div, /* nb_true_divide */
1898 0, /* nb_inplace_floor_divide */
1899 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001900};
1901
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001902PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1904 "float",
1905 sizeof(PyFloatObject),
1906 0,
1907 (destructor)float_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001908 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 0, /* tp_getattr */
1910 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001911 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 (reprfunc)float_repr, /* tp_repr */
1913 &float_as_number, /* tp_as_number */
1914 0, /* tp_as_sequence */
1915 0, /* tp_as_mapping */
1916 (hashfunc)float_hash, /* tp_hash */
1917 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001918 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 PyObject_GenericGetAttr, /* tp_getattro */
1920 0, /* tp_setattro */
1921 0, /* tp_as_buffer */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001922 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001923 float_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 0, /* tp_traverse */
1925 0, /* tp_clear */
1926 float_richcompare, /* tp_richcompare */
1927 0, /* tp_weaklistoffset */
1928 0, /* tp_iter */
1929 0, /* tp_iternext */
1930 float_methods, /* tp_methods */
1931 0, /* tp_members */
1932 float_getset, /* tp_getset */
1933 0, /* tp_base */
1934 0, /* tp_dict */
1935 0, /* tp_descr_get */
1936 0, /* tp_descr_set */
1937 0, /* tp_dictoffset */
1938 0, /* tp_init */
1939 0, /* tp_alloc */
1940 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001941};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001942
Victor Stinner1c8f0592013-07-22 22:24:54 +02001943int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001944_PyFloat_Init(void)
1945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 /* We attempt to determine if this machine is using IEEE
1947 floating point formats by peering at the bits of some
1948 carefully chosen values. If it looks like we are on an
1949 IEEE platform, the float packing/unpacking routines can
1950 just copy bits, if not they resort to arithmetic & shifts
1951 and masks. The shifts & masks approach works on all finite
1952 values, but what happens to infinities, NaNs and signed
1953 zeroes on packing is an accident, and attempting to unpack
1954 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 Note that if we're on some whacked-out platform which uses
1957 IEEE formats but isn't strictly little-endian or big-
1958 endian, we will fall back to the portable shifts & masks
1959 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001960
1961#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 {
1963 double x = 9006104071832581.0;
1964 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1965 detected_double_format = ieee_big_endian_format;
1966 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1967 detected_double_format = ieee_little_endian_format;
1968 else
1969 detected_double_format = unknown_format;
1970 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001971#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001973#endif
1974
1975#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 {
1977 float y = 16711938.0;
1978 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1979 detected_float_format = ieee_big_endian_format;
1980 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1981 detected_float_format = ieee_little_endian_format;
1982 else
1983 detected_float_format = unknown_format;
1984 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001985#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001987#endif
1988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 double_format = detected_double_format;
1990 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001993 if (FloatInfoType.tp_name == NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001994 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001995 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001996 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02001997 }
1998 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001999}
2000
Georg Brandl2ee470f2008-07-16 12:55:28 +00002001int
2002PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002003{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002004 PyFloatObject *f = free_list, *next;
2005 int i = numfree;
2006 while (f) {
2007 next = (PyFloatObject*) Py_TYPE(f);
2008 PyObject_FREE(f);
2009 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002011 free_list = NULL;
2012 numfree = 0;
2013 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00002014}
2015
2016void
Victor Stinnerbed48172019-08-27 00:12:32 +02002017_PyFloat_Fini(void)
Christian Heimes15ebc882008-02-04 18:48:49 +00002018{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002019 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002020}
Tim Peters9905b942003-03-20 20:53:32 +00002021
David Malcolm49526f42012-06-22 14:55:41 -04002022/* Print summary info about the state of the optimized allocator */
2023void
2024_PyFloat_DebugMallocStats(FILE *out)
2025{
2026 _PyDebugAllocatorStats(out,
2027 "free PyFloatObject",
2028 numfree, sizeof(PyFloatObject));
2029}
2030
2031
Tim Peters9905b942003-03-20 20:53:32 +00002032/*----------------------------------------------------------------------------
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002033 * _PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h.
2034 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
2035 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
2036 * We use:
2037 * bits = (unsigned short)f; Note the truncation
2038 * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
2039 * bits++;
2040 * }
Tim Peters9905b942003-03-20 20:53:32 +00002041 */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002042
2043int
2044_PyFloat_Pack2(double x, unsigned char *p, int le)
2045{
2046 unsigned char sign;
2047 int e;
2048 double f;
2049 unsigned short bits;
2050 int incr = 1;
2051
2052 if (x == 0.0) {
2053 sign = (copysign(1.0, x) == -1.0);
2054 e = 0;
2055 bits = 0;
2056 }
2057 else if (Py_IS_INFINITY(x)) {
2058 sign = (x < 0.0);
2059 e = 0x1f;
2060 bits = 0;
2061 }
2062 else if (Py_IS_NAN(x)) {
2063 /* There are 2046 distinct half-precision NaNs (1022 signaling and
2064 1024 quiet), but there are only two quiet NaNs that don't arise by
2065 quieting a signaling NaN; we get those by setting the topmost bit
2066 of the fraction field and clearing all other fraction bits. We
2067 choose the one with the appropriate sign. */
2068 sign = (copysign(1.0, x) == -1.0);
2069 e = 0x1f;
2070 bits = 512;
2071 }
2072 else {
2073 sign = (x < 0.0);
2074 if (sign) {
2075 x = -x;
2076 }
2077
2078 f = frexp(x, &e);
2079 if (f < 0.5 || f >= 1.0) {
2080 PyErr_SetString(PyExc_SystemError,
2081 "frexp() result out of range");
2082 return -1;
2083 }
2084
2085 /* Normalize f to be in the range [1.0, 2.0) */
2086 f *= 2.0;
2087 e--;
2088
2089 if (e >= 16) {
2090 goto Overflow;
2091 }
2092 else if (e < -25) {
2093 /* |x| < 2**-25. Underflow to zero. */
2094 f = 0.0;
2095 e = 0;
2096 }
2097 else if (e < -14) {
2098 /* |x| < 2**-14. Gradual underflow */
2099 f = ldexp(f, 14 + e);
2100 e = 0;
2101 }
2102 else /* if (!(e == 0 && f == 0.0)) */ {
2103 e += 15;
2104 f -= 1.0; /* Get rid of leading 1 */
2105 }
2106
2107 f *= 1024.0; /* 2**10 */
2108 /* Round to even */
2109 bits = (unsigned short)f; /* Note the truncation */
2110 assert(bits < 1024);
2111 assert(e < 31);
2112 if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2113 ++bits;
2114 if (bits == 1024) {
2115 /* The carry propagated out of a string of 10 1 bits. */
2116 bits = 0;
2117 ++e;
2118 if (e == 31)
2119 goto Overflow;
2120 }
2121 }
2122 }
2123
2124 bits |= (e << 10) | (sign << 15);
2125
2126 /* Write out result. */
2127 if (le) {
2128 p += 1;
2129 incr = -1;
2130 }
2131
2132 /* First byte */
2133 *p = (unsigned char)((bits >> 8) & 0xFF);
2134 p += incr;
2135
2136 /* Second byte */
2137 *p = (unsigned char)(bits & 0xFF);
2138
2139 return 0;
2140
2141 Overflow:
2142 PyErr_SetString(PyExc_OverflowError,
2143 "float too large to pack with e format");
2144 return -1;
2145}
2146
Tim Peters9905b942003-03-20 20:53:32 +00002147int
2148_PyFloat_Pack4(double x, unsigned char *p, int le)
2149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 if (float_format == unknown_format) {
2151 unsigned char sign;
2152 int e;
2153 double f;
2154 unsigned int fbits;
2155 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 if (le) {
2158 p += 3;
2159 incr = -1;
2160 }
Tim Peters9905b942003-03-20 20:53:32 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 if (x < 0) {
2163 sign = 1;
2164 x = -x;
2165 }
2166 else
2167 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 /* Normalize f to be in the range [1.0, 2.0) */
2172 if (0.5 <= f && f < 1.0) {
2173 f *= 2.0;
2174 e--;
2175 }
2176 else if (f == 0.0)
2177 e = 0;
2178 else {
2179 PyErr_SetString(PyExc_SystemError,
2180 "frexp() result out of range");
2181 return -1;
2182 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 if (e >= 128)
2185 goto Overflow;
2186 else if (e < -126) {
2187 /* Gradual underflow */
2188 f = ldexp(f, 126 + e);
2189 e = 0;
2190 }
2191 else if (!(e == 0 && f == 0.0)) {
2192 e += 127;
2193 f -= 1.0; /* Get rid of leading 1 */
2194 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 f *= 8388608.0; /* 2**23 */
2197 fbits = (unsigned int)(f + 0.5); /* Round */
2198 assert(fbits <= 8388608);
2199 if (fbits >> 23) {
2200 /* The carry propagated out of a string of 23 1 bits. */
2201 fbits = 0;
2202 ++e;
2203 if (e >= 255)
2204 goto Overflow;
2205 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 /* First byte */
2208 *p = (sign << 7) | (e >> 1);
2209 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 /* Second byte */
2212 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2213 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 /* Third byte */
2216 *p = (fbits >> 8) & 0xFF;
2217 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 /* Fourth byte */
2220 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 /* Done */
2223 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 }
2226 else {
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002227 float y = (float)x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002229
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002230 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002232
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002233 unsigned char s[sizeof(float)];
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002234 memcpy(s, &y, sizeof(float));
2235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 if ((float_format == ieee_little_endian_format && !le)
2237 || (float_format == ieee_big_endian_format && le)) {
2238 p += 3;
2239 incr = -1;
2240 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 for (i = 0; i < 4; i++) {
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002243 *p = s[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 p += incr;
2245 }
2246 return 0;
2247 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002248 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 PyErr_SetString(PyExc_OverflowError,
2250 "float too large to pack with f format");
2251 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002252}
2253
2254int
2255_PyFloat_Pack8(double x, unsigned char *p, int le)
2256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 if (double_format == unknown_format) {
2258 unsigned char sign;
2259 int e;
2260 double f;
2261 unsigned int fhi, flo;
2262 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if (le) {
2265 p += 7;
2266 incr = -1;
2267 }
Tim Peters9905b942003-03-20 20:53:32 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 if (x < 0) {
2270 sign = 1;
2271 x = -x;
2272 }
2273 else
2274 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 /* Normalize f to be in the range [1.0, 2.0) */
2279 if (0.5 <= f && f < 1.0) {
2280 f *= 2.0;
2281 e--;
2282 }
2283 else if (f == 0.0)
2284 e = 0;
2285 else {
2286 PyErr_SetString(PyExc_SystemError,
2287 "frexp() result out of range");
2288 return -1;
2289 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 if (e >= 1024)
2292 goto Overflow;
2293 else if (e < -1022) {
2294 /* Gradual underflow */
2295 f = ldexp(f, 1022 + e);
2296 e = 0;
2297 }
2298 else if (!(e == 0 && f == 0.0)) {
2299 e += 1023;
2300 f -= 1.0; /* Get rid of leading 1 */
2301 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2304 f *= 268435456.0; /* 2**28 */
2305 fhi = (unsigned int)f; /* Truncate */
2306 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 f -= (double)fhi;
2309 f *= 16777216.0; /* 2**24 */
2310 flo = (unsigned int)(f + 0.5); /* Round */
2311 assert(flo <= 16777216);
2312 if (flo >> 24) {
2313 /* The carry propagated out of a string of 24 1 bits. */
2314 flo = 0;
2315 ++fhi;
2316 if (fhi >> 28) {
2317 /* And it also progagated out of the next 28 bits. */
2318 fhi = 0;
2319 ++e;
2320 if (e >= 2047)
2321 goto Overflow;
2322 }
2323 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 /* First byte */
2326 *p = (sign << 7) | (e >> 4);
2327 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 /* Second byte */
2330 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2331 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 /* Third byte */
2334 *p = (fhi >> 16) & 0xFF;
2335 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 /* Fourth byte */
2338 *p = (fhi >> 8) & 0xFF;
2339 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 /* Fifth byte */
2342 *p = fhi & 0xFF;
2343 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 /* Sixth byte */
2346 *p = (flo >> 16) & 0xFF;
2347 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* Seventh byte */
2350 *p = (flo >> 8) & 0xFF;
2351 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 /* Eighth byte */
2354 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002355 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 /* Done */
2358 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 Overflow:
2361 PyErr_SetString(PyExc_OverflowError,
2362 "float too large to pack with d format");
2363 return -1;
2364 }
2365 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002366 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 if ((double_format == ieee_little_endian_format && !le)
2370 || (double_format == ieee_big_endian_format && le)) {
2371 p += 7;
2372 incr = -1;
2373 }
2374
2375 for (i = 0; i < 8; i++) {
2376 *p = *s++;
2377 p += incr;
2378 }
2379 return 0;
2380 }
Tim Peters9905b942003-03-20 20:53:32 +00002381}
2382
2383double
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002384_PyFloat_Unpack2(const unsigned char *p, int le)
2385{
2386 unsigned char sign;
2387 int e;
2388 unsigned int f;
2389 double x;
2390 int incr = 1;
2391
2392 if (le) {
2393 p += 1;
2394 incr = -1;
2395 }
2396
2397 /* First byte */
2398 sign = (*p >> 7) & 1;
2399 e = (*p & 0x7C) >> 2;
2400 f = (*p & 0x03) << 8;
2401 p += incr;
2402
2403 /* Second byte */
2404 f |= *p;
2405
2406 if (e == 0x1f) {
2407#ifdef PY_NO_SHORT_FLOAT_REPR
2408 if (f == 0) {
2409 /* Infinity */
2410 return sign ? -Py_HUGE_VAL : Py_HUGE_VAL;
2411 }
2412 else {
2413 /* NaN */
2414#ifdef Py_NAN
2415 return sign ? -Py_NAN : Py_NAN;
2416#else
2417 PyErr_SetString(
2418 PyExc_ValueError,
2419 "can't unpack IEEE 754 NaN "
2420 "on platform that does not support NaNs");
2421 return -1;
2422#endif /* #ifdef Py_NAN */
2423 }
2424#else
2425 if (f == 0) {
2426 /* Infinity */
2427 return _Py_dg_infinity(sign);
2428 }
2429 else {
2430 /* NaN */
2431 return _Py_dg_stdnan(sign);
2432 }
2433#endif /* #ifdef PY_NO_SHORT_FLOAT_REPR */
2434 }
2435
2436 x = (double)f / 1024.0;
2437
2438 if (e == 0) {
2439 e = -14;
2440 }
2441 else {
2442 x += 1.0;
2443 e -= 15;
2444 }
2445 x = ldexp(x, e);
2446
2447 if (sign)
2448 x = -x;
2449
2450 return x;
2451}
2452
2453double
Tim Peters9905b942003-03-20 20:53:32 +00002454_PyFloat_Unpack4(const unsigned char *p, int le)
2455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 if (float_format == unknown_format) {
2457 unsigned char sign;
2458 int e;
2459 unsigned int f;
2460 double x;
2461 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 if (le) {
2464 p += 3;
2465 incr = -1;
2466 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 /* First byte */
2469 sign = (*p >> 7) & 1;
2470 e = (*p & 0x7F) << 1;
2471 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 /* Second byte */
2474 e |= (*p >> 7) & 1;
2475 f = (*p & 0x7F) << 16;
2476 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 if (e == 255) {
2479 PyErr_SetString(
2480 PyExc_ValueError,
2481 "can't unpack IEEE 754 special value "
2482 "on non-IEEE platform");
2483 return -1;
2484 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 /* Third byte */
2487 f |= *p << 8;
2488 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 /* Fourth byte */
2491 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 /* XXX This sadly ignores Inf/NaN issues */
2496 if (e == 0)
2497 e = -126;
2498 else {
2499 x += 1.0;
2500 e -= 127;
2501 }
2502 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 if (sign)
2505 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 return x;
2508 }
2509 else {
2510 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 if ((float_format == ieee_little_endian_format && !le)
2513 || (float_format == ieee_big_endian_format && le)) {
2514 char buf[4];
2515 char *d = &buf[3];
2516 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 for (i = 0; i < 4; i++) {
2519 *d-- = *p++;
2520 }
2521 memcpy(&x, buf, 4);
2522 }
2523 else {
2524 memcpy(&x, p, 4);
2525 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 return x;
2528 }
Tim Peters9905b942003-03-20 20:53:32 +00002529}
2530
2531double
2532_PyFloat_Unpack8(const unsigned char *p, int le)
2533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 if (double_format == unknown_format) {
2535 unsigned char sign;
2536 int e;
2537 unsigned int fhi, flo;
2538 double x;
2539 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 if (le) {
2542 p += 7;
2543 incr = -1;
2544 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 /* First byte */
2547 sign = (*p >> 7) & 1;
2548 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 /* Second byte */
2553 e |= (*p >> 4) & 0xF;
2554 fhi = (*p & 0xF) << 24;
2555 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 if (e == 2047) {
2558 PyErr_SetString(
2559 PyExc_ValueError,
2560 "can't unpack IEEE 754 special value "
2561 "on non-IEEE platform");
2562 return -1.0;
2563 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 /* Third byte */
2566 fhi |= *p << 16;
2567 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 /* Fourth byte */
2570 fhi |= *p << 8;
2571 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 /* Fifth byte */
2574 fhi |= *p;
2575 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 /* Sixth byte */
2578 flo = *p << 16;
2579 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 /* Seventh byte */
2582 flo |= *p << 8;
2583 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 /* Eighth byte */
2586 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2589 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 if (e == 0)
2592 e = -1022;
2593 else {
2594 x += 1.0;
2595 e -= 1023;
2596 }
2597 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 if (sign)
2600 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 return x;
2603 }
2604 else {
2605 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 if ((double_format == ieee_little_endian_format && !le)
2608 || (double_format == ieee_big_endian_format && le)) {
2609 char buf[8];
2610 char *d = &buf[7];
2611 int i;
2612
2613 for (i = 0; i < 8; i++) {
2614 *d-- = *p++;
2615 }
2616 memcpy(&x, buf, 8);
2617 }
2618 else {
2619 memcpy(&x, p, 8);
2620 }
2621
2622 return x;
2623 }
Tim Peters9905b942003-03-20 20:53:32 +00002624}