blob: 8d7a55ac6f6401c043da54e1899f762846b58865 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.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\
47A structseq holding information about the float type. It contains low level\n\
48information 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"},
57 {"min", "DBL_MIN -- Minimum positive normalizer float"},
58 {"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"},
67 {"rounds", "FLT_ROUNDS -- addition rounds"},
68 {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 */
Christian Heimesd3afe782013-12-04 09:27:47 +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;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200179 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000180 if (s == NULL) {
181 Py_DECREF(s_buffer);
182 return NULL;
183 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000185 else if (PyBytes_Check(v)) {
186 s = PyBytes_AS_STRING(v);
187 len = PyBytes_GET_SIZE(v);
188 }
189 else if (PyByteArray_Check(v)) {
190 s = PyByteArray_AS_STRING(v);
191 len = PyByteArray_GET_SIZE(v);
192 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200193 else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
194 s = (const char *)view.buf;
195 len = view.len;
Martin Pantereeb896c2015-11-07 02:32:21 +0000196 /* Copy to NUL-terminated buffer. */
197 s_buffer = PyBytes_FromStringAndSize(s, len);
198 if (s_buffer == NULL) {
199 PyBuffer_Release(&view);
200 return NULL;
201 }
202 s = PyBytes_AS_STRING(s_buffer);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200203 }
204 else {
Ezio Melottia5b95992013-11-07 19:18:34 +0200205 PyErr_Format(PyExc_TypeError,
206 "float() argument must be a string or a number, not '%.200s'",
207 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 return NULL;
209 }
Brett Cannona721aba2016-09-09 14:57:09 -0700210 result = _Py_string_to_number_with_underscores(s, len, "float", v, v,
211 float_from_string_inner);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200212 PyBuffer_Release(&view);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000213 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000215}
216
Guido van Rossum234f9421993-06-17 12:35:49 +0000217static void
Fred Drakefd99de62000-07-09 05:02:18 +0000218float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 if (PyFloat_CheckExact(op)) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000221 if (numfree >= PyFloat_MAXFREELIST) {
222 PyObject_FREE(op);
223 return;
224 }
225 numfree++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 Py_TYPE(op) = (struct _typeobject *)free_list;
227 free_list = op;
228 }
229 else
230 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000231}
232
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000233double
Fred Drakefd99de62000-07-09 05:02:18 +0000234PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 PyNumberMethods *nb;
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300237 PyObject *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 if (op == NULL) {
241 PyErr_BadArgument();
242 return -1;
243 }
Tim Petersd2364e82001-11-01 20:09:42 +0000244
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300245 if (PyFloat_Check(op)) {
246 return PyFloat_AS_DOUBLE(op);
247 }
248
249 nb = Py_TYPE(op)->tp_as_number;
250 if (nb == NULL || nb->nb_float == NULL) {
251 PyErr_Format(PyExc_TypeError, "must be real number, not %.50s",
252 op->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 return -1;
254 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000255
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300256 res = (*nb->nb_float) (op);
257 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 return -1;
259 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300260 if (!PyFloat_CheckExact(res)) {
261 if (!PyFloat_Check(res)) {
262 PyErr_Format(PyExc_TypeError,
263 "%.50s.__float__ returned non-float (type %.50s)",
264 op->ob_type->tp_name, res->ob_type->tp_name);
265 Py_DECREF(res);
266 return -1;
267 }
268 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
269 "%.50s.__float__ returned non-float (type %.50s). "
270 "The ability to return an instance of a strict subclass of float "
271 "is deprecated, and may be removed in a future version of Python.",
272 op->ob_type->tp_name, res->ob_type->tp_name)) {
273 Py_DECREF(res);
274 return -1;
275 }
276 }
Tim Petersd2364e82001-11-01 20:09:42 +0000277
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300278 val = PyFloat_AS_DOUBLE(res);
279 Py_DECREF(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000281}
282
Neil Schemenauer32117e52001-01-04 01:44:34 +0000283/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000284 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000285 set to NULL, and the function invoking this macro returns NULL. If
Serhiy Storchaka95949422013-08-27 19:40:23 +0300286 obj is not of float or int type, Py_NotImplemented is incref'ed,
Tim Peters77d8a4f2001-12-11 20:31:34 +0000287 stored in obj, and returned from the function invoking this macro.
288*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289#define CONVERT_TO_DOUBLE(obj, dbl) \
290 if (PyFloat_Check(obj)) \
291 dbl = PyFloat_AS_DOUBLE(obj); \
292 else if (convert_to_double(&(obj), &(dbl)) < 0) \
293 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000294
Eric Smith0923d1d2009-04-16 20:16:10 +0000295/* Methods */
296
Neil Schemenauer32117e52001-01-04 01:44:34 +0000297static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000298convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000299{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200300 PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 if (PyLong_Check(obj)) {
303 *dbl = PyLong_AsDouble(obj);
304 if (*dbl == -1.0 && PyErr_Occurred()) {
305 *v = NULL;
306 return -1;
307 }
308 }
309 else {
310 Py_INCREF(Py_NotImplemented);
311 *v = Py_NotImplemented;
312 return -1;
313 }
314 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000315}
316
Eric Smith0923d1d2009-04-16 20:16:10 +0000317static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000318float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000319{
320 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200321 char *buf;
322
323 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
324 'r', 0,
325 Py_DTSF_ADD_DOT_0,
326 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000327 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000328 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200329 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000330 PyMem_Free(buf);
331 return result;
332}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000333
Tim Peters307fa782004-09-23 08:06:40 +0000334/* Comparison is pretty much a nightmare. When comparing float to float,
335 * we do it as straightforwardly (and long-windedly) as conceivable, so
336 * that, e.g., Python x == y delivers the same result as the platform
337 * C x == y when x and/or y is a NaN.
338 * When mixing float with an integer type, there's no good *uniform* approach.
339 * Converting the double to an integer obviously doesn't work, since we
340 * may lose info from fractional bits. Converting the integer to a double
Serhiy Storchaka95949422013-08-27 19:40:23 +0300341 * also has two failure modes: (1) an int may trigger overflow (too
Tim Peters307fa782004-09-23 08:06:40 +0000342 * 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 +0200343 * 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 +0000344 * 63 bits of precision, but a C double probably has only 53), and then
345 * we can falsely claim equality when low-order integer bits are lost by
346 * coercion to double. So this part is painful too.
347 */
348
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000349static PyObject*
350float_richcompare(PyObject *v, PyObject *w, int op)
351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 double i, j;
353 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 assert(PyFloat_Check(v));
356 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 /* Switch on the type of w. Set i and j to doubles to be compared,
359 * and op to the richcomp to use.
360 */
361 if (PyFloat_Check(w))
362 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 else if (!Py_IS_FINITE(i)) {
365 if (PyLong_Check(w))
366 /* If i is an infinity, its magnitude exceeds any
367 * finite integer, so it doesn't matter which int we
368 * compare i with. If i is a NaN, similarly.
369 */
370 j = 0.0;
371 else
372 goto Unimplemented;
373 }
Tim Peters307fa782004-09-23 08:06:40 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 else if (PyLong_Check(w)) {
376 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
377 int wsign = _PyLong_Sign(w);
378 size_t nbits;
379 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 if (vsign != wsign) {
382 /* Magnitudes are irrelevant -- the signs alone
383 * determine the outcome.
384 */
385 i = (double)vsign;
386 j = (double)wsign;
387 goto Compare;
388 }
389 /* The signs are the same. */
390 /* Convert w to a double if it fits. In particular, 0 fits. */
391 nbits = _PyLong_NumBits(w);
392 if (nbits == (size_t)-1 && PyErr_Occurred()) {
393 /* This long is so large that size_t isn't big enough
394 * to hold the # of bits. Replace with little doubles
395 * that give the same outcome -- w is so large that
396 * its magnitude must exceed the magnitude of any
397 * finite float.
398 */
399 PyErr_Clear();
400 i = (double)vsign;
401 assert(wsign != 0);
402 j = wsign * 2.0;
403 goto Compare;
404 }
405 if (nbits <= 48) {
406 j = PyLong_AsDouble(w);
407 /* It's impossible that <= 48 bits overflowed. */
408 assert(j != -1.0 || ! PyErr_Occurred());
409 goto Compare;
410 }
411 assert(wsign != 0); /* else nbits was 0 */
412 assert(vsign != 0); /* if vsign were 0, then since wsign is
413 * not 0, we would have taken the
414 * vsign != wsign branch at the start */
415 /* We want to work with non-negative numbers. */
416 if (vsign < 0) {
417 /* "Multiply both sides" by -1; this also swaps the
418 * comparator.
419 */
420 i = -i;
421 op = _Py_SwappedOp[op];
422 }
423 assert(i > 0.0);
424 (void) frexp(i, &exponent);
425 /* exponent is the # of bits in v before the radix point;
426 * we know that nbits (the # of bits in w) > 48 at this point
427 */
428 if (exponent < 0 || (size_t)exponent < nbits) {
429 i = 1.0;
430 j = 2.0;
431 goto Compare;
432 }
433 if ((size_t)exponent > nbits) {
434 i = 2.0;
435 j = 1.0;
436 goto Compare;
437 }
438 /* v and w have the same number of bits before the radix
Serhiy Storchaka95949422013-08-27 19:40:23 +0300439 * point. Construct two ints that have the same comparison
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 * outcome.
441 */
442 {
443 double fracpart;
444 double intpart;
445 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 PyObject *vv = NULL;
447 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 if (wsign < 0) {
450 ww = PyNumber_Negative(w);
451 if (ww == NULL)
452 goto Error;
453 }
454 else
455 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 fracpart = modf(i, &intpart);
458 vv = PyLong_FromDouble(intpart);
459 if (vv == NULL)
460 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 if (fracpart != 0.0) {
463 /* Shift left, and or a 1 bit into vv
464 * to represent the lost fraction.
465 */
466 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000467
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300468 temp = PyNumber_Lshift(ww, _PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 if (temp == NULL)
470 goto Error;
471 Py_DECREF(ww);
472 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000473
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300474 temp = PyNumber_Lshift(vv, _PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 if (temp == NULL)
476 goto Error;
477 Py_DECREF(vv);
478 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000479
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300480 temp = PyNumber_Or(vv, _PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (temp == NULL)
482 goto Error;
483 Py_DECREF(vv);
484 vv = temp;
485 }
Tim Peters307fa782004-09-23 08:06:40 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 r = PyObject_RichCompareBool(vv, ww, op);
488 if (r < 0)
489 goto Error;
490 result = PyBool_FromLong(r);
491 Error:
492 Py_XDECREF(vv);
493 Py_XDECREF(ww);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 return result;
495 }
496 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000497
Serhiy Storchaka95949422013-08-27 19:40:23 +0300498 else /* w isn't float or int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000500
501 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 PyFPE_START_PROTECT("richcompare", return NULL)
503 switch (op) {
504 case Py_EQ:
505 r = i == j;
506 break;
507 case Py_NE:
508 r = i != j;
509 break;
510 case Py_LE:
511 r = i <= j;
512 break;
513 case Py_GE:
514 r = i >= j;
515 break;
516 case Py_LT:
517 r = i < j;
518 break;
519 case Py_GT:
520 r = i > j;
521 break;
522 }
523 PyFPE_END_PROTECT(r)
524 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000525
526 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500527 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000528}
529
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000530static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000531float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000534}
535
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000536static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000537float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 double a,b;
540 CONVERT_TO_DOUBLE(v, a);
541 CONVERT_TO_DOUBLE(w, b);
542 PyFPE_START_PROTECT("add", return 0)
543 a = a + b;
544 PyFPE_END_PROTECT(a)
545 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000546}
547
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000549float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 double a,b;
552 CONVERT_TO_DOUBLE(v, a);
553 CONVERT_TO_DOUBLE(w, b);
554 PyFPE_START_PROTECT("subtract", return 0)
555 a = a - b;
556 PyFPE_END_PROTECT(a)
557 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000558}
559
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000560static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000561float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 double a,b;
564 CONVERT_TO_DOUBLE(v, a);
565 CONVERT_TO_DOUBLE(w, b);
566 PyFPE_START_PROTECT("multiply", return 0)
567 a = a * b;
568 PyFPE_END_PROTECT(a)
569 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 PyFPE_START_PROTECT("divide", return 0)
584 a = a / b;
585 PyFPE_END_PROTECT(a)
586 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000587}
588
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000589static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000590float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 double vx, wx;
593 double mod;
594 CONVERT_TO_DOUBLE(v, vx);
595 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (wx == 0.0) {
597 PyErr_SetString(PyExc_ZeroDivisionError,
598 "float modulo");
599 return NULL;
600 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 PyFPE_START_PROTECT("modulo", return 0)
602 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000603 if (mod) {
604 /* ensure the remainder has the same sign as the denominator */
605 if ((wx < 0) != (mod < 0)) {
606 mod += wx;
607 }
608 }
609 else {
610 /* the remainder is zero, and in the presence of signed zeroes
611 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000612 it has the same sign as the denominator. */
613 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 }
615 PyFPE_END_PROTECT(mod)
616 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000617}
618
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000619static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000620float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 double vx, wx;
623 double div, mod, floordiv;
624 CONVERT_TO_DOUBLE(v, vx);
625 CONVERT_TO_DOUBLE(w, wx);
626 if (wx == 0.0) {
627 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
628 return NULL;
629 }
630 PyFPE_START_PROTECT("divmod", return 0)
631 mod = fmod(vx, wx);
632 /* fmod is typically exact, so vx-mod is *mathematically* an
633 exact multiple of wx. But this is fp arithmetic, and fp
634 vx - mod is an approximation; the result is that div may
635 not be an exact integral value after the division, although
636 it will always be very close to one.
637 */
638 div = (vx - mod) / wx;
639 if (mod) {
640 /* ensure the remainder has the same sign as the denominator */
641 if ((wx < 0) != (mod < 0)) {
642 mod += wx;
643 div -= 1.0;
644 }
645 }
646 else {
647 /* the remainder is zero, and in the presence of signed zeroes
648 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000649 it has the same sign as the denominator. */
650 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 }
652 /* snap quotient to nearest integral value */
653 if (div) {
654 floordiv = floor(div);
655 if (div - floordiv > 0.5)
656 floordiv += 1.0;
657 }
658 else {
659 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000660 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 }
662 PyFPE_END_PROTECT(floordiv)
663 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000664}
665
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000666static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000667float_floor_div(PyObject *v, PyObject *w)
668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 t = float_divmod(v, w);
672 if (t == NULL || t == Py_NotImplemented)
673 return t;
674 assert(PyTuple_CheckExact(t));
675 r = PyTuple_GET_ITEM(t, 0);
676 Py_INCREF(r);
677 Py_DECREF(t);
678 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000679}
680
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000681/* determine whether x is an odd integer or not; assumes that
682 x is not an infinity or nan. */
683#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
684
Tim Peters63a35712001-12-11 19:57:24 +0000685static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000686float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 double iv, iw, ix;
689 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 if ((PyObject *)z != Py_None) {
692 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
693 "allowed unless all arguments are integers");
694 return NULL;
695 }
Tim Peters32f453e2001-09-03 08:35:41 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 CONVERT_TO_DOUBLE(v, iv);
698 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 /* Sort out special cases here instead of relying on pow() */
701 if (iw == 0) { /* v**0 is 1, even 0**0 */
702 return PyFloat_FromDouble(1.0);
703 }
704 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
705 return PyFloat_FromDouble(iv);
706 }
707 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
708 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
709 }
710 if (Py_IS_INFINITY(iw)) {
711 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
712 * abs(v) > 1 (including case where v infinite)
713 *
714 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
715 * abs(v) > 1 (including case where v infinite)
716 */
717 iv = fabs(iv);
718 if (iv == 1.0)
719 return PyFloat_FromDouble(1.0);
720 else if ((iw > 0.0) == (iv > 1.0))
721 return PyFloat_FromDouble(fabs(iw)); /* return inf */
722 else
723 return PyFloat_FromDouble(0.0);
724 }
725 if (Py_IS_INFINITY(iv)) {
726 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
727 * both cases, we need to add the appropriate sign if w is
728 * an odd integer.
729 */
730 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
731 if (iw > 0.0)
732 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
733 else
734 return PyFloat_FromDouble(iw_is_odd ?
735 copysign(0.0, iv) : 0.0);
736 }
737 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
738 (already dealt with above), and an error
739 if w is negative. */
740 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
741 if (iw < 0.0) {
742 PyErr_SetString(PyExc_ZeroDivisionError,
743 "0.0 cannot be raised to a "
744 "negative power");
745 return NULL;
746 }
747 /* use correct sign if iw is odd */
748 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
749 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 if (iv < 0.0) {
752 /* Whether this is an error is a mess, and bumps into libm
753 * bugs so we have to figure it out ourselves.
754 */
755 if (iw != floor(iw)) {
756 /* Negative numbers raised to fractional powers
757 * become complex.
758 */
759 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
760 }
761 /* iw is an exact integer, albeit perhaps a very large
762 * one. Replace iv by its absolute value and remember
763 * to negate the pow result if iw is odd.
764 */
765 iv = -iv;
766 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
767 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
770 /* (-1) ** large_integer also ends up here. Here's an
771 * extract from the comments for the previous
772 * implementation explaining why this special case is
773 * necessary:
774 *
775 * -1 raised to an exact integer should never be exceptional.
776 * Alas, some libms (chiefly glibc as of early 2003) return
777 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
778 * happen to be representable in a *C* integer. That's a
779 * bug.
780 */
781 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
782 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 /* Now iv and iw are finite, iw is nonzero, and iv is
785 * positive and not equal to 1.0. We finally allow
786 * the platform pow to step in and do the rest.
787 */
788 errno = 0;
789 PyFPE_START_PROTECT("pow", return NULL)
790 ix = pow(iv, iw);
791 PyFPE_END_PROTECT(ix)
792 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;
845 PyFPE_START_PROTECT("is_integer", return NULL)
846 o = (floor(x) == x) ? Py_True : Py_False;
847 PyFPE_END_PROTECT(x)
848 if (errno != 0) {
849 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
850 PyExc_ValueError);
851 return NULL;
852 }
853 Py_INCREF(o);
854 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000855}
856
857#if 0
858static PyObject *
859float_is_inf(PyObject *v)
860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 double x = PyFloat_AsDouble(v);
862 if (x == -1.0 && PyErr_Occurred())
863 return NULL;
864 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000865}
866
867static PyObject *
868float_is_nan(PyObject *v)
869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 double x = PyFloat_AsDouble(v);
871 if (x == -1.0 && PyErr_Occurred())
872 return NULL;
873 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000874}
875
876static PyObject *
877float_is_finite(PyObject *v)
878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 double x = PyFloat_AsDouble(v);
880 if (x == -1.0 && PyErr_Occurred())
881 return NULL;
882 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000883}
884#endif
885
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200886/*[clinic input]
887float.__trunc__
888
889Return the Integral closest to x between 0 and x.
890[clinic start generated code]*/
891
Christian Heimes53876d92008-04-19 00:31:39 +0000892static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200893float___trunc___impl(PyObject *self)
894/*[clinic end generated code: output=dd3e289dd4c6b538 input=591b9ba0d650fdff]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000895{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +0200896 double x = PyFloat_AsDouble(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 (void)modf(x, &wholepart);
900 /* Try to get out cheap if this fits in a Python int. The attempt
901 * to cast to long must be protected, as C doesn't define what
902 * happens if the double is too big to fit in a long. Some rare
903 * systems raise an exception then (RISCOS was mentioned as one,
904 * and someone using a non-default option on Sun also bumped into
905 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
906 * still be vulnerable: if a long has more bits of precision than
907 * a double, casting MIN/MAX to double may yield an approximation,
908 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
909 * yield true from the C expression wholepart<=LONG_MAX, despite
910 * that wholepart is actually greater than LONG_MAX.
911 */
912 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
913 const long aslong = (long)wholepart;
914 return PyLong_FromLong(aslong);
915 }
916 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000917}
918
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000919/* double_round: rounds a finite double to the closest multiple of
920 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
921 ndigits <= 323). Returns a Python float, or sets a Python error and
922 returns NULL on failure (OverflowError and memory errors are possible). */
923
924#ifndef PY_NO_SHORT_FLOAT_REPR
925/* version of double_round that uses the correctly-rounded string<->double
926 conversions from Python/dtoa.c */
927
928static PyObject *
929double_round(double x, int ndigits) {
930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 double rounded;
932 Py_ssize_t buflen, mybuflen=100;
933 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
934 int decpt, sign;
935 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000936 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000939 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000941 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 if (buf == NULL) {
943 PyErr_NoMemory();
944 return NULL;
945 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
948 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
949 buflen = buf_end - buf;
950 if (buflen + 8 > mybuflen) {
951 mybuflen = buflen+8;
952 mybuf = (char *)PyMem_Malloc(mybuflen);
953 if (mybuf == NULL) {
954 PyErr_NoMemory();
955 goto exit;
956 }
957 }
958 /* copy buf to mybuf, adding exponent, sign and leading 0 */
959 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
960 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 /* and convert the resulting string back to a double */
963 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000964 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000966 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 if (errno == ERANGE && fabs(rounded) >= 1.)
968 PyErr_SetString(PyExc_OverflowError,
969 "rounded value too large to represent");
970 else
971 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 /* done computing value; now clean up */
974 if (mybuf != shortbuf)
975 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000976 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 _Py_dg_freedtoa(buf);
978 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000979}
980
981#else /* PY_NO_SHORT_FLOAT_REPR */
982
983/* fallback version, to be used when correctly rounded binary<->decimal
984 conversions aren't available */
985
986static PyObject *
987double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 double pow1, pow2, y, z;
989 if (ndigits >= 0) {
990 if (ndigits > 22) {
991 /* pow1 and pow2 are each safe from overflow, but
992 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
993 pow1 = pow(10.0, (double)(ndigits-22));
994 pow2 = 1e22;
995 }
996 else {
997 pow1 = pow(10.0, (double)ndigits);
998 pow2 = 1.0;
999 }
1000 y = (x*pow1)*pow2;
1001 /* if y overflows, then rounded value is exactly x */
1002 if (!Py_IS_FINITE(y))
1003 return PyFloat_FromDouble(x);
1004 }
1005 else {
1006 pow1 = pow(10.0, (double)-ndigits);
1007 pow2 = 1.0; /* unused; silences a gcc compiler warning */
1008 y = x / pow1;
1009 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 z = round(y);
1012 if (fabs(y-z) == 0.5)
1013 /* halfway between two integers; use round-half-even */
1014 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 if (ndigits >= 0)
1017 z = (z / pow2) / pow1;
1018 else
1019 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 /* if computation resulted in overflow, raise OverflowError */
1022 if (!Py_IS_FINITE(z)) {
1023 PyErr_SetString(PyExc_OverflowError,
1024 "overflow occurred during round");
1025 return NULL;
1026 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001029}
1030
1031#endif /* PY_NO_SHORT_FLOAT_REPR */
1032
1033/* round a Python float v to the closest multiple of 10**-ndigits */
1034
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001035/*[clinic input]
1036float.__round__
1037
1038 ndigits as o_ndigits: object = NULL
1039 /
1040
1041Return the Integral closest to x, rounding half toward even.
1042
1043When an argument is passed, work like built-in round(x, ndigits).
1044[clinic start generated code]*/
1045
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001046static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001047float___round___impl(PyObject *self, PyObject *o_ndigits)
1048/*[clinic end generated code: output=374c36aaa0f13980 input=1ca2316b510293b8]*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 double x, rounded;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001052
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001053 x = PyFloat_AsDouble(self);
Steve Dowercb39d1f2015-04-15 16:10:59 -04001054 if (o_ndigits == NULL || o_ndigits == Py_None) {
1055 /* single-argument round or with None ndigits:
1056 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 rounded = round(x);
1058 if (fabs(x-rounded) == 0.5)
1059 /* halfway case: round to even */
1060 rounded = 2.0*round(x/2.0);
1061 return PyLong_FromDouble(rounded);
1062 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 /* interpret second argument as a Py_ssize_t; clips on overflow */
1065 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1066 if (ndigits == -1 && PyErr_Occurred())
1067 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 /* nans and infinities round to themselves */
1070 if (!Py_IS_FINITE(x))
1071 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1074 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1075 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001076#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1077#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 if (ndigits > NDIGITS_MAX)
1079 /* return x */
1080 return PyFloat_FromDouble(x);
1081 else if (ndigits < NDIGITS_MIN)
1082 /* return 0.0, but with sign of x */
1083 return PyFloat_FromDouble(0.0*x);
1084 else
1085 /* finite x, and ndigits is not unreasonably large */
1086 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001087#undef NDIGITS_MAX
1088#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001089}
1090
1091static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001092float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 if (PyFloat_CheckExact(v))
1095 Py_INCREF(v);
1096 else
1097 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1098 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001099}
1100
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001101/*[clinic input]
1102float.conjugate
1103
1104Return self, the complex conjugate of any float.
1105[clinic start generated code]*/
1106
1107static PyObject *
1108float_conjugate_impl(PyObject *self)
1109/*[clinic end generated code: output=8ca292c2479194af input=82ba6f37a9ff91dd]*/
1110{
1111 return float_float(self);
1112}
1113
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001114/* turn ASCII hex characters into integer values and vice versa */
1115
1116static char
1117char_from_hex(int x)
1118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001120 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001121}
1122
1123static int
1124hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 int x;
1126 switch(c) {
1127 case '0':
1128 x = 0;
1129 break;
1130 case '1':
1131 x = 1;
1132 break;
1133 case '2':
1134 x = 2;
1135 break;
1136 case '3':
1137 x = 3;
1138 break;
1139 case '4':
1140 x = 4;
1141 break;
1142 case '5':
1143 x = 5;
1144 break;
1145 case '6':
1146 x = 6;
1147 break;
1148 case '7':
1149 x = 7;
1150 break;
1151 case '8':
1152 x = 8;
1153 break;
1154 case '9':
1155 x = 9;
1156 break;
1157 case 'a':
1158 case 'A':
1159 x = 10;
1160 break;
1161 case 'b':
1162 case 'B':
1163 x = 11;
1164 break;
1165 case 'c':
1166 case 'C':
1167 x = 12;
1168 break;
1169 case 'd':
1170 case 'D':
1171 x = 13;
1172 break;
1173 case 'e':
1174 case 'E':
1175 x = 14;
1176 break;
1177 case 'f':
1178 case 'F':
1179 x = 15;
1180 break;
1181 default:
1182 x = -1;
1183 break;
1184 }
1185 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001186}
1187
1188/* convert a float to a hexadecimal string */
1189
1190/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1191 of the form 4k+1. */
1192#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1193
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001194/*[clinic input]
1195float.hex
1196
1197Return a hexadecimal representation of a floating-point number.
1198
1199>>> (-0.1).hex()
1200'-0x1.999999999999ap-4'
1201>>> 3.14159.hex()
1202'0x1.921f9f01b866ep+1'
1203[clinic start generated code]*/
1204
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001205static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001206float_hex_impl(PyObject *self)
1207/*[clinic end generated code: output=0ebc9836e4d302d4 input=bec1271a33d47e67]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 double x, m;
1210 int e, shift, i, si, esign;
1211 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1212 trailing NUL byte. */
1213 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001214
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001215 CONVERT_TO_DOUBLE(self, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001218 return float_repr((PyFloatObject *)self);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001221 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 return PyUnicode_FromString("-0x0.0p+0");
1223 else
1224 return PyUnicode_FromString("0x0.0p+0");
1225 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001228 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 m = ldexp(m, shift);
1230 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 si = 0;
1233 s[si] = char_from_hex((int)m);
1234 si++;
1235 m -= (int)m;
1236 s[si] = '.';
1237 si++;
1238 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1239 m *= 16.0;
1240 s[si] = char_from_hex((int)m);
1241 si++;
1242 m -= (int)m;
1243 }
1244 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 if (e < 0) {
1247 esign = (int)'-';
1248 e = -e;
1249 }
1250 else
1251 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 if (x < 0.0)
1254 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1255 else
1256 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001257}
1258
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001259/* Convert a hexadecimal string to a float. */
1260
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001261/*[clinic input]
1262@classmethod
1263float.fromhex
1264
1265 string: object
1266 /
1267
1268Create a floating-point number from a hexadecimal string.
1269
1270>>> float.fromhex('0x1.ffffp10')
12712047.984375
1272>>> float.fromhex('-0x1p-1074')
1273-5e-324
1274[clinic start generated code]*/
1275
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001276static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001277float_fromhex(PyTypeObject *type, PyObject *string)
1278/*[clinic end generated code: output=46c0274d22b78e82 input=0407bebd354bca89]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001279{
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001280 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 double x;
1282 long exp, top_exp, lsb, key_digit;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001283 const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 int half_eps, digit, round_up, negate=0;
1285 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 /*
1288 * For the sake of simplicity and correctness, we impose an artificial
1289 * limit on ndigits, the total number of hex digits in the coefficient
1290 * The limit is chosen to ensure that, writing exp for the exponent,
1291 *
1292 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1293 * guaranteed to overflow (provided it's nonzero)
1294 *
1295 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1296 * guaranteed to underflow to 0.
1297 *
1298 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1299 * overflow in the calculation of exp and top_exp below.
1300 *
1301 * More specifically, ndigits is assumed to satisfy the following
1302 * inequalities:
1303 *
1304 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1305 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1306 *
1307 * If either of these inequalities is not satisfied, a ValueError is
1308 * raised. Otherwise, write x for the value of the hex string, and
1309 * assume x is nonzero. Then
1310 *
1311 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1312 *
1313 * Now if exp > LONG_MAX/2 then:
1314 *
1315 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1316 * = DBL_MAX_EXP
1317 *
1318 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1319 * double, so overflows. If exp < LONG_MIN/2, then
1320 *
1321 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1322 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1323 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1324 *
1325 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1326 * when converted to a C double.
1327 *
1328 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1329 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1330 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001331
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001332 s = PyUnicode_AsUTF8AndSize(string, &length);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 if (s == NULL)
1334 return NULL;
1335 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 /********************
1338 * Parse the string *
1339 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 /* leading whitespace */
1342 while (Py_ISSPACE(*s))
1343 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 /* infinities and nans */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001346 x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 if (coeff_end != s) {
1348 s = coeff_end;
1349 goto finished;
1350 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 /* optional sign */
1353 if (*s == '-') {
1354 s++;
1355 negate = 1;
1356 }
1357 else if (*s == '+')
1358 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 /* [0x] */
1361 s_store = s;
1362 if (*s == '0') {
1363 s++;
1364 if (*s == 'x' || *s == 'X')
1365 s++;
1366 else
1367 s = s_store;
1368 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 /* coefficient: <integer> [. <fraction>] */
1371 coeff_start = s;
1372 while (hex_from_char(*s) >= 0)
1373 s++;
1374 s_store = s;
1375 if (*s == '.') {
1376 s++;
1377 while (hex_from_char(*s) >= 0)
1378 s++;
1379 coeff_end = s-1;
1380 }
1381 else
1382 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 /* ndigits = total # of hex digits; fdigits = # after point */
1385 ndigits = coeff_end - coeff_start;
1386 fdigits = coeff_end - s_store;
1387 if (ndigits == 0)
1388 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001389 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1390 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 /* [p <exponent>] */
1394 if (*s == 'p' || *s == 'P') {
1395 s++;
1396 exp_start = s;
1397 if (*s == '-' || *s == '+')
1398 s++;
1399 if (!('0' <= *s && *s <= '9'))
1400 goto parse_error;
1401 s++;
1402 while ('0' <= *s && *s <= '9')
1403 s++;
1404 exp = strtol(exp_start, NULL, 10);
1405 }
1406 else
1407 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001408
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001409/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1411 coeff_end-(j) : \
1412 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 /*******************************************
1415 * Compute rounded value of the hex string *
1416 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 /* Discard leading zeros, and catch extreme overflow and underflow */
1419 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1420 ndigits--;
1421 if (ndigits == 0 || exp < LONG_MIN/2) {
1422 x = 0.0;
1423 goto finished;
1424 }
1425 if (exp > LONG_MAX/2)
1426 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 /* Adjust exponent for fractional part. */
1429 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1432 top_exp = exp + 4*((long)ndigits - 1);
1433 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1434 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 /* catch almost all nonextreme cases of overflow and underflow here */
1437 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1438 x = 0.0;
1439 goto finished;
1440 }
1441 if (top_exp > DBL_MAX_EXP)
1442 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 /* lsb = exponent of least significant bit of the *rounded* value.
1445 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001446 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 x = 0.0;
1449 if (exp >= lsb) {
1450 /* no rounding required */
1451 for (i = ndigits-1; i >= 0; i--)
1452 x = 16.0*x + HEX_DIGIT(i);
1453 x = ldexp(x, (int)(exp));
1454 goto finished;
1455 }
1456 /* rounding required. key_digit is the index of the hex digit
1457 containing the first bit to be rounded away. */
1458 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1459 key_digit = (lsb - exp - 1) / 4;
1460 for (i = ndigits-1; i > key_digit; i--)
1461 x = 16.0*x + HEX_DIGIT(i);
1462 digit = HEX_DIGIT(key_digit);
1463 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1466 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1467 if ((digit & half_eps) != 0) {
1468 round_up = 0;
1469 if ((digit & (3*half_eps-1)) != 0 ||
1470 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1471 round_up = 1;
1472 else
1473 for (i = key_digit-1; i >= 0; i--)
1474 if (HEX_DIGIT(i) != 0) {
1475 round_up = 1;
1476 break;
1477 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001478 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 x += 2*half_eps;
1480 if (top_exp == DBL_MAX_EXP &&
1481 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1482 /* overflow corner case: pre-rounded value <
1483 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1484 goto overflow_error;
1485 }
1486 }
1487 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001488
1489 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 /* optional trailing whitespace leading to the end of the string */
1491 while (Py_ISSPACE(*s))
1492 s++;
1493 if (s != s_end)
1494 goto parse_error;
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001495 result = PyFloat_FromDouble(negate ? -x : x);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001496 if (type != &PyFloat_Type && result != NULL) {
1497 Py_SETREF(result, PyObject_CallFunctionObjArgs((PyObject *)type, result, NULL));
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001498 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001500
1501 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 PyErr_SetString(PyExc_OverflowError,
1503 "hexadecimal value too large to represent as a float");
1504 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001505
1506 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 PyErr_SetString(PyExc_ValueError,
1508 "invalid hexadecimal floating-point string");
1509 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001510
1511 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 PyErr_SetString(PyExc_ValueError,
1513 "hexadecimal string too long to convert");
1514 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001515}
1516
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001517/*[clinic input]
1518float.as_integer_ratio
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001519
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001520Return integer ratio.
1521
1522Return a pair of integers, whose ratio is exactly equal to the original float
1523and with a positive denominator.
1524
1525Raise OverflowError on infinities and a ValueError on NaNs.
1526
1527>>> (10.0).as_integer_ratio()
1528(10, 1)
1529>>> (0.0).as_integer_ratio()
1530(0, 1)
1531>>> (-.25).as_integer_ratio()
1532(-1, 4)
1533[clinic start generated code]*/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001534
Christian Heimes26855632008-01-27 23:50:43 +00001535static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001536float_as_integer_ratio_impl(PyObject *self)
1537/*[clinic end generated code: output=65f25f0d8d30a712 input=e21d08b4630c2e44]*/
Christian Heimes26855632008-01-27 23:50:43 +00001538{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001539 double self_double;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 double float_part;
1541 int exponent;
1542 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 PyObject *py_exponent = NULL;
1545 PyObject *numerator = NULL;
1546 PyObject *denominator = NULL;
1547 PyObject *result_pair = NULL;
1548 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001549
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001550 CONVERT_TO_DOUBLE(self, self_double);
Christian Heimes26855632008-01-27 23:50:43 +00001551
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001552 if (Py_IS_INFINITY(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001553 PyErr_SetString(PyExc_OverflowError,
1554 "cannot convert Infinity to integer ratio");
1555 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001557 if (Py_IS_NAN(self_double)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001558 PyErr_SetString(PyExc_ValueError,
1559 "cannot convert NaN to integer ratio");
1560 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 }
Christian Heimes26855632008-01-27 23:50:43 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001564 float_part = frexp(self_double, &exponent); /* self_double == float_part * 2**exponent exactly */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1568 float_part *= 2.0;
1569 exponent--;
1570 }
1571 /* self == float_part * 2**exponent exactly and float_part is integral.
1572 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1573 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 numerator = PyLong_FromDouble(float_part);
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001576 if (numerator == NULL)
1577 goto error;
1578 denominator = PyLong_FromLong(1);
1579 if (denominator == NULL)
1580 goto error;
1581 py_exponent = PyLong_FromLong(Py_ABS(exponent));
1582 if (py_exponent == NULL)
1583 goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 /* fold in 2**exponent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 if (exponent > 0) {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001587 Py_SETREF(numerator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001588 long_methods->nb_lshift(numerator, py_exponent));
1589 if (numerator == NULL)
1590 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 }
1592 else {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001593 Py_SETREF(denominator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001594 long_methods->nb_lshift(denominator, py_exponent));
1595 if (denominator == NULL)
1596 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 }
1598
1599 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001600
Christian Heimes26855632008-01-27 23:50:43 +00001601error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 Py_XDECREF(py_exponent);
1603 Py_XDECREF(denominator);
1604 Py_XDECREF(numerator);
1605 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001606}
1607
Jeremy Hylton938ace62002-07-17 16:30:39 +00001608static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001609float_subtype_new(PyTypeObject *type, PyObject *x);
1610
1611/*[clinic input]
1612@classmethod
1613float.__new__ as float_new
Serhiy Storchakaba85d692017-03-30 09:09:41 +03001614 x: object(c_default="_PyLong_Zero") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001615 /
1616
1617Convert a string or number to a floating point number, if possible.
1618[clinic start generated code]*/
Guido van Rossumbef14172001-08-29 15:47:46 +00001619
Tim Peters6d6c1a32001-08-02 04:15:00 +00001620static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001621float_new_impl(PyTypeObject *type, PyObject *x)
Serhiy Storchakabae68812017-04-05 12:00:42 +03001622/*[clinic end generated code: output=ccf1e8dc460ba6ba input=540ee77c204ff87a]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00001623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 if (type != &PyFloat_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001625 return float_subtype_new(type, x); /* Wimp out */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 /* If it's a string, but not a string subclass, use
1627 PyFloat_FromString. */
1628 if (PyUnicode_CheckExact(x))
1629 return PyFloat_FromString(x);
1630 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631}
1632
Guido van Rossumbef14172001-08-29 15:47:46 +00001633/* Wimpy, slow approach to tp_new calls for subtypes of float:
1634 first create a regular float from whatever arguments we got,
1635 then allocate a subtype instance and initialize its ob_fval
1636 from the regular float. The regular float is then thrown away.
1637*/
1638static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001639float_subtype_new(PyTypeObject *type, PyObject *x)
Guido van Rossumbef14172001-08-29 15:47:46 +00001640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 assert(PyType_IsSubtype(type, &PyFloat_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001644 tmp = float_new_impl(&PyFloat_Type, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 if (tmp == NULL)
1646 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001647 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 newobj = type->tp_alloc(type, 0);
1649 if (newobj == NULL) {
1650 Py_DECREF(tmp);
1651 return NULL;
1652 }
1653 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1654 Py_DECREF(tmp);
1655 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001656}
1657
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001658/*[clinic input]
1659float.__getnewargs__
1660[clinic start generated code]*/
1661
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001662static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001663float___getnewargs___impl(PyObject *self)
1664/*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001665{
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001666 return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001667}
1668
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001669/* this is for the benefit of the pack/unpack routines below */
1670
1671typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001673} float_format_type;
1674
1675static float_format_type double_format, float_format;
1676static float_format_type detected_double_format, detected_float_format;
1677
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001678/*[clinic input]
1679@classmethod
1680float.__getformat__
1681
1682 typestr: str
1683 Must be 'double' or 'float'.
1684 /
1685
1686You probably don't want to use this function.
1687
1688It exists mainly to be used in Python's test suite.
1689
1690This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
1691little-endian' best describes the format of floating point numbers used by the
1692C type named by typestr.
1693[clinic start generated code]*/
1694
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001695static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001696float___getformat___impl(PyTypeObject *type, const char *typestr)
1697/*[clinic end generated code: output=2bfb987228cc9628 input=d5a52600f835ad67]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001700
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001701 if (strcmp(typestr, "double") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 r = double_format;
1703 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001704 else if (strcmp(typestr, "float") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 r = float_format;
1706 }
1707 else {
1708 PyErr_SetString(PyExc_ValueError,
1709 "__getformat__() argument 1 must be "
1710 "'double' or 'float'");
1711 return NULL;
1712 }
1713
1714 switch (r) {
1715 case unknown_format:
1716 return PyUnicode_FromString("unknown");
1717 case ieee_little_endian_format:
1718 return PyUnicode_FromString("IEEE, little-endian");
1719 case ieee_big_endian_format:
1720 return PyUnicode_FromString("IEEE, big-endian");
1721 default:
1722 Py_FatalError("insane float_format or double_format");
1723 return NULL;
1724 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001725}
1726
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001727/*[clinic input]
1728@classmethod
1729float.__set_format__
1730
1731 typestr: str
1732 Must be 'double' or 'float'.
1733 fmt: str
1734 Must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian',
1735 and in addition can only be one of the latter two if it appears to
1736 match the underlying C reality.
1737 /
1738
1739You probably don't want to use this function.
1740
1741It exists mainly to be used in Python's test suite.
1742
1743Override the automatic determination of C-level floating point type.
1744This affects how floats are converted to and from binary strings.
1745[clinic start generated code]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001746
1747static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001748float___set_format___impl(PyTypeObject *type, const char *typestr,
1749 const char *fmt)
1750/*[clinic end generated code: output=504460f5dc85acbd input=5306fa2b81a997e4]*/
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 float_format_type f;
1753 float_format_type detected;
1754 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (strcmp(typestr, "double") == 0) {
1757 p = &double_format;
1758 detected = detected_double_format;
1759 }
1760 else if (strcmp(typestr, "float") == 0) {
1761 p = &float_format;
1762 detected = detected_float_format;
1763 }
1764 else {
1765 PyErr_SetString(PyExc_ValueError,
1766 "__setformat__() argument 1 must "
1767 "be 'double' or 'float'");
1768 return NULL;
1769 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001770
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001771 if (strcmp(fmt, "unknown") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 f = unknown_format;
1773 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001774 else if (strcmp(fmt, "IEEE, little-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 f = ieee_little_endian_format;
1776 }
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001777 else if (strcmp(fmt, "IEEE, big-endian") == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 f = ieee_big_endian_format;
1779 }
1780 else {
1781 PyErr_SetString(PyExc_ValueError,
1782 "__setformat__() argument 2 must be "
1783 "'unknown', 'IEEE, little-endian' or "
1784 "'IEEE, big-endian'");
1785 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 if (f != unknown_format && f != detected) {
1790 PyErr_Format(PyExc_ValueError,
1791 "can only set %s format to 'unknown' or the "
1792 "detected platform value", typestr);
1793 return NULL;
1794 }
1795
1796 *p = f;
1797 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001798}
1799
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001800static PyObject *
1801float_getreal(PyObject *v, void *closure)
1802{
1803 return float_float(v);
1804}
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001805
Guido van Rossumb43daf72007-08-01 18:08:08 +00001806static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001807float_getimag(PyObject *v, void *closure)
Guido van Rossumb43daf72007-08-01 18:08:08 +00001808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001810}
1811
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001812/*[clinic input]
1813float.__format__
1814
1815 format_spec: unicode
1816 /
1817
1818Formats the float according to format_spec.
1819[clinic start generated code]*/
1820
Eric Smith8c663262007-08-25 02:26:07 +00001821static PyObject *
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001822float___format___impl(PyObject *self, PyObject *format_spec)
1823/*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/
Eric Smith8c663262007-08-25 02:26:07 +00001824{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001825 _PyUnicodeWriter writer;
1826 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001827
Victor Stinner8f674cc2013-04-17 23:02:17 +02001828 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001829 ret = _PyFloat_FormatAdvancedWriter(
1830 &writer,
1831 self,
1832 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1833 if (ret == -1) {
1834 _PyUnicodeWriter_Dealloc(&writer);
1835 return NULL;
1836 }
1837 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001838}
1839
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001840static PyMethodDef float_methods[] = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001841 FLOAT_CONJUGATE_METHODDEF
1842 FLOAT___TRUNC___METHODDEF
1843 FLOAT___ROUND___METHODDEF
1844 FLOAT_AS_INTEGER_RATIO_METHODDEF
1845 FLOAT_FROMHEX_METHODDEF
1846 FLOAT_HEX_METHODDEF
1847 FLOAT_IS_INTEGER_METHODDEF
Christian Heimes53876d92008-04-19 00:31:39 +00001848#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001850 "Return True if the float is positive or negative infinite."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001852 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001854 "Return True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001855#endif
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001856 FLOAT___GETNEWARGS___METHODDEF
1857 FLOAT___GETFORMAT___METHODDEF
1858 FLOAT___SET_FORMAT___METHODDEF
1859 FLOAT___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001861};
1862
Guido van Rossumb43daf72007-08-01 18:08:08 +00001863static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 {"real",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001865 float_getreal, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001866 "the real part of a complex number",
1867 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 {"imag",
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001869 float_getimag, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001870 "the imaginary part of a complex number",
1871 NULL},
1872 {NULL} /* Sentinel */
1873};
1874
Tim Peters6d6c1a32001-08-02 04:15:00 +00001875
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001876static PyNumberMethods float_as_number = {
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001877 float_add, /* nb_add */
1878 float_sub, /* nb_subtract */
1879 float_mul, /* nb_multiply */
1880 float_rem, /* nb_remainder */
1881 float_divmod, /* nb_divmod */
1882 float_pow, /* nb_power */
1883 (unaryfunc)float_neg, /* nb_negative */
1884 float_float, /* nb_positive */
1885 (unaryfunc)float_abs, /* nb_absolute */
1886 (inquiry)float_bool, /* nb_bool */
1887 0, /* nb_invert */
1888 0, /* nb_lshift */
1889 0, /* nb_rshift */
1890 0, /* nb_and */
1891 0, /* nb_xor */
1892 0, /* nb_or */
1893 float___trunc___impl, /* nb_int */
1894 0, /* nb_reserved */
1895 float_float, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 0, /* nb_inplace_add */
1897 0, /* nb_inplace_subtract */
1898 0, /* nb_inplace_multiply */
1899 0, /* nb_inplace_remainder */
1900 0, /* nb_inplace_power */
1901 0, /* nb_inplace_lshift */
1902 0, /* nb_inplace_rshift */
1903 0, /* nb_inplace_and */
1904 0, /* nb_inplace_xor */
1905 0, /* nb_inplace_or */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001906 float_floor_div, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 float_div, /* nb_true_divide */
1908 0, /* nb_inplace_floor_divide */
1909 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001910};
1911
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001912PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1914 "float",
1915 sizeof(PyFloatObject),
1916 0,
1917 (destructor)float_dealloc, /* tp_dealloc */
1918 0, /* tp_print */
1919 0, /* tp_getattr */
1920 0, /* tp_setattr */
1921 0, /* tp_reserved */
1922 (reprfunc)float_repr, /* tp_repr */
1923 &float_as_number, /* tp_as_number */
1924 0, /* tp_as_sequence */
1925 0, /* tp_as_mapping */
1926 (hashfunc)float_hash, /* tp_hash */
1927 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001928 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 PyObject_GenericGetAttr, /* tp_getattro */
1930 0, /* tp_setattro */
1931 0, /* tp_as_buffer */
Serhiy Storchakab5c51d32017-03-11 09:21:05 +02001932 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001933 float_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 0, /* tp_traverse */
1935 0, /* tp_clear */
1936 float_richcompare, /* tp_richcompare */
1937 0, /* tp_weaklistoffset */
1938 0, /* tp_iter */
1939 0, /* tp_iternext */
1940 float_methods, /* tp_methods */
1941 0, /* tp_members */
1942 float_getset, /* tp_getset */
1943 0, /* tp_base */
1944 0, /* tp_dict */
1945 0, /* tp_descr_get */
1946 0, /* tp_descr_set */
1947 0, /* tp_dictoffset */
1948 0, /* tp_init */
1949 0, /* tp_alloc */
1950 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001951};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001952
Victor Stinner1c8f0592013-07-22 22:24:54 +02001953int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001954_PyFloat_Init(void)
1955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 /* We attempt to determine if this machine is using IEEE
1957 floating point formats by peering at the bits of some
1958 carefully chosen values. If it looks like we are on an
1959 IEEE platform, the float packing/unpacking routines can
1960 just copy bits, if not they resort to arithmetic & shifts
1961 and masks. The shifts & masks approach works on all finite
1962 values, but what happens to infinities, NaNs and signed
1963 zeroes on packing is an accident, and attempting to unpack
1964 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 Note that if we're on some whacked-out platform which uses
1967 IEEE formats but isn't strictly little-endian or big-
1968 endian, we will fall back to the portable shifts & masks
1969 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001970
1971#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 {
1973 double x = 9006104071832581.0;
1974 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1975 detected_double_format = ieee_big_endian_format;
1976 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1977 detected_double_format = ieee_little_endian_format;
1978 else
1979 detected_double_format = unknown_format;
1980 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001981#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001983#endif
1984
1985#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 {
1987 float y = 16711938.0;
1988 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1989 detected_float_format = ieee_big_endian_format;
1990 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1991 detected_float_format = ieee_little_endian_format;
1992 else
1993 detected_float_format = unknown_format;
1994 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001995#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001997#endif
1998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 double_format = detected_double_format;
2000 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002003 if (FloatInfoType.tp_name == NULL) {
2004 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0)
2005 return 0;
2006 }
2007 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002008}
2009
Georg Brandl2ee470f2008-07-16 12:55:28 +00002010int
2011PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002012{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002013 PyFloatObject *f = free_list, *next;
2014 int i = numfree;
2015 while (f) {
2016 next = (PyFloatObject*) Py_TYPE(f);
2017 PyObject_FREE(f);
2018 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002020 free_list = NULL;
2021 numfree = 0;
2022 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00002023}
2024
2025void
2026PyFloat_Fini(void)
2027{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00002028 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002029}
Tim Peters9905b942003-03-20 20:53:32 +00002030
David Malcolm49526f42012-06-22 14:55:41 -04002031/* Print summary info about the state of the optimized allocator */
2032void
2033_PyFloat_DebugMallocStats(FILE *out)
2034{
2035 _PyDebugAllocatorStats(out,
2036 "free PyFloatObject",
2037 numfree, sizeof(PyFloatObject));
2038}
2039
2040
Tim Peters9905b942003-03-20 20:53:32 +00002041/*----------------------------------------------------------------------------
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002042 * _PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h.
2043 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
2044 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
2045 * We use:
2046 * bits = (unsigned short)f; Note the truncation
2047 * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
2048 * bits++;
2049 * }
Tim Peters9905b942003-03-20 20:53:32 +00002050 */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002051
2052int
2053_PyFloat_Pack2(double x, unsigned char *p, int le)
2054{
2055 unsigned char sign;
2056 int e;
2057 double f;
2058 unsigned short bits;
2059 int incr = 1;
2060
2061 if (x == 0.0) {
2062 sign = (copysign(1.0, x) == -1.0);
2063 e = 0;
2064 bits = 0;
2065 }
2066 else if (Py_IS_INFINITY(x)) {
2067 sign = (x < 0.0);
2068 e = 0x1f;
2069 bits = 0;
2070 }
2071 else if (Py_IS_NAN(x)) {
2072 /* There are 2046 distinct half-precision NaNs (1022 signaling and
2073 1024 quiet), but there are only two quiet NaNs that don't arise by
2074 quieting a signaling NaN; we get those by setting the topmost bit
2075 of the fraction field and clearing all other fraction bits. We
2076 choose the one with the appropriate sign. */
2077 sign = (copysign(1.0, x) == -1.0);
2078 e = 0x1f;
2079 bits = 512;
2080 }
2081 else {
2082 sign = (x < 0.0);
2083 if (sign) {
2084 x = -x;
2085 }
2086
2087 f = frexp(x, &e);
2088 if (f < 0.5 || f >= 1.0) {
2089 PyErr_SetString(PyExc_SystemError,
2090 "frexp() result out of range");
2091 return -1;
2092 }
2093
2094 /* Normalize f to be in the range [1.0, 2.0) */
2095 f *= 2.0;
2096 e--;
2097
2098 if (e >= 16) {
2099 goto Overflow;
2100 }
2101 else if (e < -25) {
2102 /* |x| < 2**-25. Underflow to zero. */
2103 f = 0.0;
2104 e = 0;
2105 }
2106 else if (e < -14) {
2107 /* |x| < 2**-14. Gradual underflow */
2108 f = ldexp(f, 14 + e);
2109 e = 0;
2110 }
2111 else /* if (!(e == 0 && f == 0.0)) */ {
2112 e += 15;
2113 f -= 1.0; /* Get rid of leading 1 */
2114 }
2115
2116 f *= 1024.0; /* 2**10 */
2117 /* Round to even */
2118 bits = (unsigned short)f; /* Note the truncation */
2119 assert(bits < 1024);
2120 assert(e < 31);
2121 if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2122 ++bits;
2123 if (bits == 1024) {
2124 /* The carry propagated out of a string of 10 1 bits. */
2125 bits = 0;
2126 ++e;
2127 if (e == 31)
2128 goto Overflow;
2129 }
2130 }
2131 }
2132
2133 bits |= (e << 10) | (sign << 15);
2134
2135 /* Write out result. */
2136 if (le) {
2137 p += 1;
2138 incr = -1;
2139 }
2140
2141 /* First byte */
2142 *p = (unsigned char)((bits >> 8) & 0xFF);
2143 p += incr;
2144
2145 /* Second byte */
2146 *p = (unsigned char)(bits & 0xFF);
2147
2148 return 0;
2149
2150 Overflow:
2151 PyErr_SetString(PyExc_OverflowError,
2152 "float too large to pack with e format");
2153 return -1;
2154}
2155
Tim Peters9905b942003-03-20 20:53:32 +00002156int
2157_PyFloat_Pack4(double x, unsigned char *p, int le)
2158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 if (float_format == unknown_format) {
2160 unsigned char sign;
2161 int e;
2162 double f;
2163 unsigned int fbits;
2164 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 if (le) {
2167 p += 3;
2168 incr = -1;
2169 }
Tim Peters9905b942003-03-20 20:53:32 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 if (x < 0) {
2172 sign = 1;
2173 x = -x;
2174 }
2175 else
2176 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 /* Normalize f to be in the range [1.0, 2.0) */
2181 if (0.5 <= f && f < 1.0) {
2182 f *= 2.0;
2183 e--;
2184 }
2185 else if (f == 0.0)
2186 e = 0;
2187 else {
2188 PyErr_SetString(PyExc_SystemError,
2189 "frexp() result out of range");
2190 return -1;
2191 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 if (e >= 128)
2194 goto Overflow;
2195 else if (e < -126) {
2196 /* Gradual underflow */
2197 f = ldexp(f, 126 + e);
2198 e = 0;
2199 }
2200 else if (!(e == 0 && f == 0.0)) {
2201 e += 127;
2202 f -= 1.0; /* Get rid of leading 1 */
2203 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 f *= 8388608.0; /* 2**23 */
2206 fbits = (unsigned int)(f + 0.5); /* Round */
2207 assert(fbits <= 8388608);
2208 if (fbits >> 23) {
2209 /* The carry propagated out of a string of 23 1 bits. */
2210 fbits = 0;
2211 ++e;
2212 if (e >= 255)
2213 goto Overflow;
2214 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 /* First byte */
2217 *p = (sign << 7) | (e >> 1);
2218 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 /* Second byte */
2221 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2222 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* Third byte */
2225 *p = (fbits >> 8) & 0xFF;
2226 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 /* Fourth byte */
2229 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 /* Done */
2232 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 }
2235 else {
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002236 float y = (float)x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002238
Benjamin Peterson2bb69a52017-09-10 23:50:46 -07002239 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002241
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002242 unsigned char s[sizeof(float)];
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002243 memcpy(s, &y, sizeof(float));
2244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 if ((float_format == ieee_little_endian_format && !le)
2246 || (float_format == ieee_big_endian_format && le)) {
2247 p += 3;
2248 incr = -1;
2249 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 for (i = 0; i < 4; i++) {
Benjamin Petersona853a8b2017-09-07 11:13:59 -07002252 *p = s[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 p += incr;
2254 }
2255 return 0;
2256 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002257 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 PyErr_SetString(PyExc_OverflowError,
2259 "float too large to pack with f format");
2260 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002261}
2262
2263int
2264_PyFloat_Pack8(double x, unsigned char *p, int le)
2265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 if (double_format == unknown_format) {
2267 unsigned char sign;
2268 int e;
2269 double f;
2270 unsigned int fhi, flo;
2271 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 if (le) {
2274 p += 7;
2275 incr = -1;
2276 }
Tim Peters9905b942003-03-20 20:53:32 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 if (x < 0) {
2279 sign = 1;
2280 x = -x;
2281 }
2282 else
2283 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 /* Normalize f to be in the range [1.0, 2.0) */
2288 if (0.5 <= f && f < 1.0) {
2289 f *= 2.0;
2290 e--;
2291 }
2292 else if (f == 0.0)
2293 e = 0;
2294 else {
2295 PyErr_SetString(PyExc_SystemError,
2296 "frexp() result out of range");
2297 return -1;
2298 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 if (e >= 1024)
2301 goto Overflow;
2302 else if (e < -1022) {
2303 /* Gradual underflow */
2304 f = ldexp(f, 1022 + e);
2305 e = 0;
2306 }
2307 else if (!(e == 0 && f == 0.0)) {
2308 e += 1023;
2309 f -= 1.0; /* Get rid of leading 1 */
2310 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2313 f *= 268435456.0; /* 2**28 */
2314 fhi = (unsigned int)f; /* Truncate */
2315 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 f -= (double)fhi;
2318 f *= 16777216.0; /* 2**24 */
2319 flo = (unsigned int)(f + 0.5); /* Round */
2320 assert(flo <= 16777216);
2321 if (flo >> 24) {
2322 /* The carry propagated out of a string of 24 1 bits. */
2323 flo = 0;
2324 ++fhi;
2325 if (fhi >> 28) {
2326 /* And it also progagated out of the next 28 bits. */
2327 fhi = 0;
2328 ++e;
2329 if (e >= 2047)
2330 goto Overflow;
2331 }
2332 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 /* First byte */
2335 *p = (sign << 7) | (e >> 4);
2336 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 /* Second byte */
2339 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2340 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 /* Third byte */
2343 *p = (fhi >> 16) & 0xFF;
2344 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 /* Fourth byte */
2347 *p = (fhi >> 8) & 0xFF;
2348 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 /* Fifth byte */
2351 *p = fhi & 0xFF;
2352 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 /* Sixth byte */
2355 *p = (flo >> 16) & 0xFF;
2356 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 /* Seventh byte */
2359 *p = (flo >> 8) & 0xFF;
2360 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 /* Eighth byte */
2363 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002364 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 /* Done */
2367 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 Overflow:
2370 PyErr_SetString(PyExc_OverflowError,
2371 "float too large to pack with d format");
2372 return -1;
2373 }
2374 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002375 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 if ((double_format == ieee_little_endian_format && !le)
2379 || (double_format == ieee_big_endian_format && le)) {
2380 p += 7;
2381 incr = -1;
2382 }
2383
2384 for (i = 0; i < 8; i++) {
2385 *p = *s++;
2386 p += incr;
2387 }
2388 return 0;
2389 }
Tim Peters9905b942003-03-20 20:53:32 +00002390}
2391
2392double
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002393_PyFloat_Unpack2(const unsigned char *p, int le)
2394{
2395 unsigned char sign;
2396 int e;
2397 unsigned int f;
2398 double x;
2399 int incr = 1;
2400
2401 if (le) {
2402 p += 1;
2403 incr = -1;
2404 }
2405
2406 /* First byte */
2407 sign = (*p >> 7) & 1;
2408 e = (*p & 0x7C) >> 2;
2409 f = (*p & 0x03) << 8;
2410 p += incr;
2411
2412 /* Second byte */
2413 f |= *p;
2414
2415 if (e == 0x1f) {
2416#ifdef PY_NO_SHORT_FLOAT_REPR
2417 if (f == 0) {
2418 /* Infinity */
2419 return sign ? -Py_HUGE_VAL : Py_HUGE_VAL;
2420 }
2421 else {
2422 /* NaN */
2423#ifdef Py_NAN
2424 return sign ? -Py_NAN : Py_NAN;
2425#else
2426 PyErr_SetString(
2427 PyExc_ValueError,
2428 "can't unpack IEEE 754 NaN "
2429 "on platform that does not support NaNs");
2430 return -1;
2431#endif /* #ifdef Py_NAN */
2432 }
2433#else
2434 if (f == 0) {
2435 /* Infinity */
2436 return _Py_dg_infinity(sign);
2437 }
2438 else {
2439 /* NaN */
2440 return _Py_dg_stdnan(sign);
2441 }
2442#endif /* #ifdef PY_NO_SHORT_FLOAT_REPR */
2443 }
2444
2445 x = (double)f / 1024.0;
2446
2447 if (e == 0) {
2448 e = -14;
2449 }
2450 else {
2451 x += 1.0;
2452 e -= 15;
2453 }
2454 x = ldexp(x, e);
2455
2456 if (sign)
2457 x = -x;
2458
2459 return x;
2460}
2461
2462double
Tim Peters9905b942003-03-20 20:53:32 +00002463_PyFloat_Unpack4(const unsigned char *p, int le)
2464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 if (float_format == unknown_format) {
2466 unsigned char sign;
2467 int e;
2468 unsigned int f;
2469 double x;
2470 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 if (le) {
2473 p += 3;
2474 incr = -1;
2475 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 /* First byte */
2478 sign = (*p >> 7) & 1;
2479 e = (*p & 0x7F) << 1;
2480 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 /* Second byte */
2483 e |= (*p >> 7) & 1;
2484 f = (*p & 0x7F) << 16;
2485 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 if (e == 255) {
2488 PyErr_SetString(
2489 PyExc_ValueError,
2490 "can't unpack IEEE 754 special value "
2491 "on non-IEEE platform");
2492 return -1;
2493 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 /* Third byte */
2496 f |= *p << 8;
2497 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 /* Fourth byte */
2500 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 /* XXX This sadly ignores Inf/NaN issues */
2505 if (e == 0)
2506 e = -126;
2507 else {
2508 x += 1.0;
2509 e -= 127;
2510 }
2511 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 if (sign)
2514 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 return x;
2517 }
2518 else {
2519 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 if ((float_format == ieee_little_endian_format && !le)
2522 || (float_format == ieee_big_endian_format && le)) {
2523 char buf[4];
2524 char *d = &buf[3];
2525 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 for (i = 0; i < 4; i++) {
2528 *d-- = *p++;
2529 }
2530 memcpy(&x, buf, 4);
2531 }
2532 else {
2533 memcpy(&x, p, 4);
2534 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 return x;
2537 }
Tim Peters9905b942003-03-20 20:53:32 +00002538}
2539
2540double
2541_PyFloat_Unpack8(const unsigned char *p, int le)
2542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 if (double_format == unknown_format) {
2544 unsigned char sign;
2545 int e;
2546 unsigned int fhi, flo;
2547 double x;
2548 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 if (le) {
2551 p += 7;
2552 incr = -1;
2553 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 /* First byte */
2556 sign = (*p >> 7) & 1;
2557 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 /* Second byte */
2562 e |= (*p >> 4) & 0xF;
2563 fhi = (*p & 0xF) << 24;
2564 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 if (e == 2047) {
2567 PyErr_SetString(
2568 PyExc_ValueError,
2569 "can't unpack IEEE 754 special value "
2570 "on non-IEEE platform");
2571 return -1.0;
2572 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 /* Third byte */
2575 fhi |= *p << 16;
2576 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 /* Fourth byte */
2579 fhi |= *p << 8;
2580 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 /* Fifth byte */
2583 fhi |= *p;
2584 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 /* Sixth byte */
2587 flo = *p << 16;
2588 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 /* Seventh byte */
2591 flo |= *p << 8;
2592 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 /* Eighth byte */
2595 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2598 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 if (e == 0)
2601 e = -1022;
2602 else {
2603 x += 1.0;
2604 e -= 1023;
2605 }
2606 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 if (sign)
2609 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 return x;
2612 }
2613 else {
2614 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 if ((double_format == ieee_little_endian_format && !le)
2617 || (double_format == ieee_big_endian_format && le)) {
2618 char buf[8];
2619 char *d = &buf[7];
2620 int i;
2621
2622 for (i = 0; i < 8; i++) {
2623 *d-- = *p++;
2624 }
2625 memcpy(&x, buf, 8);
2626 }
2627 else {
2628 memcpy(&x, p, 8);
2629 }
2630
2631 return x;
2632 }
Tim Peters9905b942003-03-20 20:53:32 +00002633}