floatobject.c 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632
  1. /* Float object implementation */
  2. /* XXX There should be overflow checks here, but it's hard to check
  3. for any kind of float exception without losing portability. */
  4. #include "Python.h"
  5. #include "pycore_dtoa.h" // _Py_dg_dtoa()
  6. #include "pycore_floatobject.h" // _PyFloat_FormatAdvancedWriter()
  7. #include "pycore_initconfig.h" // _PyStatus_OK()
  8. #include "pycore_interp.h" // _PyInterpreterState.float_state
  9. #include "pycore_long.h" // _PyLong_GetOne()
  10. #include "pycore_object.h" // _PyObject_Init()
  11. #include "pycore_pymath.h" // _PY_SHORT_FLOAT_REPR
  12. #include "pycore_pystate.h" // _PyInterpreterState_GET()
  13. #include "pycore_structseq.h" // _PyStructSequence_FiniBuiltin()
  14. #include <ctype.h>
  15. #include <float.h>
  16. #include <stdlib.h> // strtol()
  17. /*[clinic input]
  18. class float "PyObject *" "&PyFloat_Type"
  19. [clinic start generated code]*/
  20. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=dd0003f68f144284]*/
  21. #include "clinic/floatobject.c.h"
  22. #ifndef PyFloat_MAXFREELIST
  23. # define PyFloat_MAXFREELIST 100
  24. #endif
  25. #if PyFloat_MAXFREELIST > 0
  26. static struct _Py_float_state *
  27. get_float_state(void)
  28. {
  29. PyInterpreterState *interp = _PyInterpreterState_GET();
  30. return &interp->float_state;
  31. }
  32. #endif
  33. double
  34. PyFloat_GetMax(void)
  35. {
  36. return DBL_MAX;
  37. }
  38. double
  39. PyFloat_GetMin(void)
  40. {
  41. return DBL_MIN;
  42. }
  43. static PyTypeObject FloatInfoType;
  44. PyDoc_STRVAR(floatinfo__doc__,
  45. "sys.float_info\n\
  46. \n\
  47. A named tuple holding information about the float type. It contains low level\n\
  48. information about the precision and internal representation. Please study\n\
  49. your system's :file:`float.h` for more information.");
  50. static PyStructSequence_Field floatinfo_fields[] = {
  51. {"max", "DBL_MAX -- maximum representable finite float"},
  52. {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
  53. "is representable"},
  54. {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
  55. "is representable"},
  56. {"min", "DBL_MIN -- Minimum positive normalized float"},
  57. {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
  58. "is a normalized float"},
  59. {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
  60. "a normalized float"},
  61. {"dig", "DBL_DIG -- maximum number of decimal digits that "
  62. "can be faithfully represented in a float"},
  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 -- rounding mode used for arithmetic "
  68. "operations"},
  69. {0}
  70. };
  71. static PyStructSequence_Desc floatinfo_desc = {
  72. "sys.float_info", /* name */
  73. floatinfo__doc__, /* doc */
  74. floatinfo_fields, /* fields */
  75. 11
  76. };
  77. PyObject *
  78. PyFloat_GetInfo(void)
  79. {
  80. PyObject* floatinfo;
  81. int pos = 0;
  82. floatinfo = PyStructSequence_New(&FloatInfoType);
  83. if (floatinfo == NULL) {
  84. return NULL;
  85. }
  86. #define SetFlag(CALL) \
  87. do { \
  88. PyObject *flag = (CALL); \
  89. if (flag == NULL) { \
  90. Py_CLEAR(floatinfo); \
  91. return NULL; \
  92. } \
  93. PyStructSequence_SET_ITEM(floatinfo, pos++, flag); \
  94. } while (0)
  95. #define SetIntFlag(FLAG) SetFlag(PyLong_FromLong((FLAG)))
  96. #define SetDblFlag(FLAG) SetFlag(PyFloat_FromDouble((FLAG)))
  97. SetDblFlag(DBL_MAX);
  98. SetIntFlag(DBL_MAX_EXP);
  99. SetIntFlag(DBL_MAX_10_EXP);
  100. SetDblFlag(DBL_MIN);
  101. SetIntFlag(DBL_MIN_EXP);
  102. SetIntFlag(DBL_MIN_10_EXP);
  103. SetIntFlag(DBL_DIG);
  104. SetIntFlag(DBL_MANT_DIG);
  105. SetDblFlag(DBL_EPSILON);
  106. SetIntFlag(FLT_RADIX);
  107. SetIntFlag(FLT_ROUNDS);
  108. #undef SetIntFlag
  109. #undef SetDblFlag
  110. #undef SetFlag
  111. return floatinfo;
  112. }
  113. PyObject *
  114. PyFloat_FromDouble(double fval)
  115. {
  116. PyFloatObject *op;
  117. #if PyFloat_MAXFREELIST > 0
  118. struct _Py_float_state *state = get_float_state();
  119. op = state->free_list;
  120. if (op != NULL) {
  121. #ifdef Py_DEBUG
  122. // PyFloat_FromDouble() must not be called after _PyFloat_Fini()
  123. assert(state->numfree != -1);
  124. #endif
  125. state->free_list = (PyFloatObject *) Py_TYPE(op);
  126. state->numfree--;
  127. OBJECT_STAT_INC(from_freelist);
  128. }
  129. else
  130. #endif
  131. {
  132. op = PyObject_Malloc(sizeof(PyFloatObject));
  133. if (!op) {
  134. return PyErr_NoMemory();
  135. }
  136. }
  137. _PyObject_Init((PyObject*)op, &PyFloat_Type);
  138. op->ob_fval = fval;
  139. return (PyObject *) op;
  140. }
  141. static PyObject *
  142. float_from_string_inner(const char *s, Py_ssize_t len, void *obj)
  143. {
  144. double x;
  145. const char *end;
  146. const char *last = s + len;
  147. /* strip leading whitespace */
  148. while (s < last && Py_ISSPACE(*s)) {
  149. s++;
  150. }
  151. if (s == last) {
  152. PyErr_Format(PyExc_ValueError,
  153. "could not convert string to float: "
  154. "%R", obj);
  155. return NULL;
  156. }
  157. /* strip trailing whitespace */
  158. while (s < last - 1 && Py_ISSPACE(last[-1])) {
  159. last--;
  160. }
  161. /* We don't care about overflow or underflow. If the platform
  162. * supports them, infinities and signed zeroes (on underflow) are
  163. * fine. */
  164. x = PyOS_string_to_double(s, (char **)&end, NULL);
  165. if (end != last) {
  166. PyErr_Format(PyExc_ValueError,
  167. "could not convert string to float: "
  168. "%R", obj);
  169. return NULL;
  170. }
  171. else if (x == -1.0 && PyErr_Occurred()) {
  172. return NULL;
  173. }
  174. else {
  175. return PyFloat_FromDouble(x);
  176. }
  177. }
  178. PyObject *
  179. PyFloat_FromString(PyObject *v)
  180. {
  181. const char *s;
  182. PyObject *s_buffer = NULL;
  183. Py_ssize_t len;
  184. Py_buffer view = {NULL, NULL};
  185. PyObject *result = NULL;
  186. if (PyUnicode_Check(v)) {
  187. s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
  188. if (s_buffer == NULL)
  189. return NULL;
  190. assert(PyUnicode_IS_ASCII(s_buffer));
  191. /* Simply get a pointer to existing ASCII characters. */
  192. s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
  193. assert(s != NULL);
  194. }
  195. else if (PyBytes_Check(v)) {
  196. s = PyBytes_AS_STRING(v);
  197. len = PyBytes_GET_SIZE(v);
  198. }
  199. else if (PyByteArray_Check(v)) {
  200. s = PyByteArray_AS_STRING(v);
  201. len = PyByteArray_GET_SIZE(v);
  202. }
  203. else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
  204. s = (const char *)view.buf;
  205. len = view.len;
  206. /* Copy to NUL-terminated buffer. */
  207. s_buffer = PyBytes_FromStringAndSize(s, len);
  208. if (s_buffer == NULL) {
  209. PyBuffer_Release(&view);
  210. return NULL;
  211. }
  212. s = PyBytes_AS_STRING(s_buffer);
  213. }
  214. else {
  215. PyErr_Format(PyExc_TypeError,
  216. "float() argument must be a string or a real number, not '%.200s'",
  217. Py_TYPE(v)->tp_name);
  218. return NULL;
  219. }
  220. result = _Py_string_to_number_with_underscores(s, len, "float", v, v,
  221. float_from_string_inner);
  222. PyBuffer_Release(&view);
  223. Py_XDECREF(s_buffer);
  224. return result;
  225. }
  226. void
  227. _PyFloat_ExactDealloc(PyObject *obj)
  228. {
  229. assert(PyFloat_CheckExact(obj));
  230. PyFloatObject *op = (PyFloatObject *)obj;
  231. #if PyFloat_MAXFREELIST > 0
  232. struct _Py_float_state *state = get_float_state();
  233. #ifdef Py_DEBUG
  234. // float_dealloc() must not be called after _PyFloat_Fini()
  235. assert(state->numfree != -1);
  236. #endif
  237. if (state->numfree >= PyFloat_MAXFREELIST) {
  238. PyObject_Free(op);
  239. return;
  240. }
  241. state->numfree++;
  242. Py_SET_TYPE(op, (PyTypeObject *)state->free_list);
  243. state->free_list = op;
  244. OBJECT_STAT_INC(to_freelist);
  245. #else
  246. PyObject_Free(op);
  247. #endif
  248. }
  249. static void
  250. float_dealloc(PyObject *op)
  251. {
  252. assert(PyFloat_Check(op));
  253. #if PyFloat_MAXFREELIST > 0
  254. if (PyFloat_CheckExact(op)) {
  255. _PyFloat_ExactDealloc(op);
  256. }
  257. else
  258. #endif
  259. {
  260. Py_TYPE(op)->tp_free(op);
  261. }
  262. }
  263. double
  264. PyFloat_AsDouble(PyObject *op)
  265. {
  266. PyNumberMethods *nb;
  267. PyObject *res;
  268. double val;
  269. if (op == NULL) {
  270. PyErr_BadArgument();
  271. return -1;
  272. }
  273. if (PyFloat_Check(op)) {
  274. return PyFloat_AS_DOUBLE(op);
  275. }
  276. nb = Py_TYPE(op)->tp_as_number;
  277. if (nb == NULL || nb->nb_float == NULL) {
  278. if (nb && nb->nb_index) {
  279. PyObject *res = _PyNumber_Index(op);
  280. if (!res) {
  281. return -1;
  282. }
  283. double val = PyLong_AsDouble(res);
  284. Py_DECREF(res);
  285. return val;
  286. }
  287. PyErr_Format(PyExc_TypeError, "must be real number, not %.50s",
  288. Py_TYPE(op)->tp_name);
  289. return -1;
  290. }
  291. res = (*nb->nb_float) (op);
  292. if (res == NULL) {
  293. return -1;
  294. }
  295. if (!PyFloat_CheckExact(res)) {
  296. if (!PyFloat_Check(res)) {
  297. PyErr_Format(PyExc_TypeError,
  298. "%.50s.__float__ returned non-float (type %.50s)",
  299. Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name);
  300. Py_DECREF(res);
  301. return -1;
  302. }
  303. if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
  304. "%.50s.__float__ returned non-float (type %.50s). "
  305. "The ability to return an instance of a strict subclass of float "
  306. "is deprecated, and may be removed in a future version of Python.",
  307. Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name)) {
  308. Py_DECREF(res);
  309. return -1;
  310. }
  311. }
  312. val = PyFloat_AS_DOUBLE(res);
  313. Py_DECREF(res);
  314. return val;
  315. }
  316. /* Macro and helper that convert PyObject obj to a C double and store
  317. the value in dbl. If conversion to double raises an exception, obj is
  318. set to NULL, and the function invoking this macro returns NULL. If
  319. obj is not of float or int type, Py_NotImplemented is incref'ed,
  320. stored in obj, and returned from the function invoking this macro.
  321. */
  322. #define CONVERT_TO_DOUBLE(obj, dbl) \
  323. if (PyFloat_Check(obj)) \
  324. dbl = PyFloat_AS_DOUBLE(obj); \
  325. else if (convert_to_double(&(obj), &(dbl)) < 0) \
  326. return obj;
  327. /* Methods */
  328. static int
  329. convert_to_double(PyObject **v, double *dbl)
  330. {
  331. PyObject *obj = *v;
  332. if (PyLong_Check(obj)) {
  333. *dbl = PyLong_AsDouble(obj);
  334. if (*dbl == -1.0 && PyErr_Occurred()) {
  335. *v = NULL;
  336. return -1;
  337. }
  338. }
  339. else {
  340. *v = Py_NewRef(Py_NotImplemented);
  341. return -1;
  342. }
  343. return 0;
  344. }
  345. static PyObject *
  346. float_repr(PyFloatObject *v)
  347. {
  348. PyObject *result;
  349. char *buf;
  350. buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
  351. 'r', 0,
  352. Py_DTSF_ADD_DOT_0,
  353. NULL);
  354. if (!buf)
  355. return PyErr_NoMemory();
  356. result = _PyUnicode_FromASCII(buf, strlen(buf));
  357. PyMem_Free(buf);
  358. return result;
  359. }
  360. /* Comparison is pretty much a nightmare. When comparing float to float,
  361. * we do it as straightforwardly (and long-windedly) as conceivable, so
  362. * that, e.g., Python x == y delivers the same result as the platform
  363. * C x == y when x and/or y is a NaN.
  364. * When mixing float with an integer type, there's no good *uniform* approach.
  365. * Converting the double to an integer obviously doesn't work, since we
  366. * may lose info from fractional bits. Converting the integer to a double
  367. * also has two failure modes: (1) an int may trigger overflow (too
  368. * large to fit in the dynamic range of a C double); (2) even a C long may have
  369. * more bits than fit in a C double (e.g., on a 64-bit box long may have
  370. * 63 bits of precision, but a C double probably has only 53), and then
  371. * we can falsely claim equality when low-order integer bits are lost by
  372. * coercion to double. So this part is painful too.
  373. */
  374. static PyObject*
  375. float_richcompare(PyObject *v, PyObject *w, int op)
  376. {
  377. double i, j;
  378. int r = 0;
  379. assert(PyFloat_Check(v));
  380. i = PyFloat_AS_DOUBLE(v);
  381. /* Switch on the type of w. Set i and j to doubles to be compared,
  382. * and op to the richcomp to use.
  383. */
  384. if (PyFloat_Check(w))
  385. j = PyFloat_AS_DOUBLE(w);
  386. else if (!Py_IS_FINITE(i)) {
  387. if (PyLong_Check(w))
  388. /* If i is an infinity, its magnitude exceeds any
  389. * finite integer, so it doesn't matter which int we
  390. * compare i with. If i is a NaN, similarly.
  391. */
  392. j = 0.0;
  393. else
  394. goto Unimplemented;
  395. }
  396. else if (PyLong_Check(w)) {
  397. int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
  398. int wsign = _PyLong_Sign(w);
  399. size_t nbits;
  400. int exponent;
  401. if (vsign != wsign) {
  402. /* Magnitudes are irrelevant -- the signs alone
  403. * determine the outcome.
  404. */
  405. i = (double)vsign;
  406. j = (double)wsign;
  407. goto Compare;
  408. }
  409. /* The signs are the same. */
  410. /* Convert w to a double if it fits. In particular, 0 fits. */
  411. nbits = _PyLong_NumBits(w);
  412. if (nbits == (size_t)-1 && PyErr_Occurred()) {
  413. /* This long is so large that size_t isn't big enough
  414. * to hold the # of bits. Replace with little doubles
  415. * that give the same outcome -- w is so large that
  416. * its magnitude must exceed the magnitude of any
  417. * finite float.
  418. */
  419. PyErr_Clear();
  420. i = (double)vsign;
  421. assert(wsign != 0);
  422. j = wsign * 2.0;
  423. goto Compare;
  424. }
  425. if (nbits <= 48) {
  426. j = PyLong_AsDouble(w);
  427. /* It's impossible that <= 48 bits overflowed. */
  428. assert(j != -1.0 || ! PyErr_Occurred());
  429. goto Compare;
  430. }
  431. assert(wsign != 0); /* else nbits was 0 */
  432. assert(vsign != 0); /* if vsign were 0, then since wsign is
  433. * not 0, we would have taken the
  434. * vsign != wsign branch at the start */
  435. /* We want to work with non-negative numbers. */
  436. if (vsign < 0) {
  437. /* "Multiply both sides" by -1; this also swaps the
  438. * comparator.
  439. */
  440. i = -i;
  441. op = _Py_SwappedOp[op];
  442. }
  443. assert(i > 0.0);
  444. (void) frexp(i, &exponent);
  445. /* exponent is the # of bits in v before the radix point;
  446. * we know that nbits (the # of bits in w) > 48 at this point
  447. */
  448. if (exponent < 0 || (size_t)exponent < nbits) {
  449. i = 1.0;
  450. j = 2.0;
  451. goto Compare;
  452. }
  453. if ((size_t)exponent > nbits) {
  454. i = 2.0;
  455. j = 1.0;
  456. goto Compare;
  457. }
  458. /* v and w have the same number of bits before the radix
  459. * point. Construct two ints that have the same comparison
  460. * outcome.
  461. */
  462. {
  463. double fracpart;
  464. double intpart;
  465. PyObject *result = NULL;
  466. PyObject *vv = NULL;
  467. PyObject *ww = w;
  468. if (wsign < 0) {
  469. ww = PyNumber_Negative(w);
  470. if (ww == NULL)
  471. goto Error;
  472. }
  473. else
  474. Py_INCREF(ww);
  475. fracpart = modf(i, &intpart);
  476. vv = PyLong_FromDouble(intpart);
  477. if (vv == NULL)
  478. goto Error;
  479. if (fracpart != 0.0) {
  480. /* Shift left, and or a 1 bit into vv
  481. * to represent the lost fraction.
  482. */
  483. PyObject *temp;
  484. temp = _PyLong_Lshift(ww, 1);
  485. if (temp == NULL)
  486. goto Error;
  487. Py_SETREF(ww, temp);
  488. temp = _PyLong_Lshift(vv, 1);
  489. if (temp == NULL)
  490. goto Error;
  491. Py_SETREF(vv, temp);
  492. temp = PyNumber_Or(vv, _PyLong_GetOne());
  493. if (temp == NULL)
  494. goto Error;
  495. Py_SETREF(vv, temp);
  496. }
  497. r = PyObject_RichCompareBool(vv, ww, op);
  498. if (r < 0)
  499. goto Error;
  500. result = PyBool_FromLong(r);
  501. Error:
  502. Py_XDECREF(vv);
  503. Py_XDECREF(ww);
  504. return result;
  505. }
  506. } /* else if (PyLong_Check(w)) */
  507. else /* w isn't float or int */
  508. goto Unimplemented;
  509. Compare:
  510. switch (op) {
  511. case Py_EQ:
  512. r = i == j;
  513. break;
  514. case Py_NE:
  515. r = i != j;
  516. break;
  517. case Py_LE:
  518. r = i <= j;
  519. break;
  520. case Py_GE:
  521. r = i >= j;
  522. break;
  523. case Py_LT:
  524. r = i < j;
  525. break;
  526. case Py_GT:
  527. r = i > j;
  528. break;
  529. }
  530. return PyBool_FromLong(r);
  531. Unimplemented:
  532. Py_RETURN_NOTIMPLEMENTED;
  533. }
  534. static Py_hash_t
  535. float_hash(PyFloatObject *v)
  536. {
  537. return _Py_HashDouble((PyObject *)v, v->ob_fval);
  538. }
  539. static PyObject *
  540. float_add(PyObject *v, PyObject *w)
  541. {
  542. double a,b;
  543. CONVERT_TO_DOUBLE(v, a);
  544. CONVERT_TO_DOUBLE(w, b);
  545. a = a + b;
  546. return PyFloat_FromDouble(a);
  547. }
  548. static PyObject *
  549. float_sub(PyObject *v, PyObject *w)
  550. {
  551. double a,b;
  552. CONVERT_TO_DOUBLE(v, a);
  553. CONVERT_TO_DOUBLE(w, b);
  554. a = a - b;
  555. return PyFloat_FromDouble(a);
  556. }
  557. static PyObject *
  558. float_mul(PyObject *v, PyObject *w)
  559. {
  560. double a,b;
  561. CONVERT_TO_DOUBLE(v, a);
  562. CONVERT_TO_DOUBLE(w, b);
  563. a = a * b;
  564. return PyFloat_FromDouble(a);
  565. }
  566. static PyObject *
  567. float_div(PyObject *v, PyObject *w)
  568. {
  569. double a,b;
  570. CONVERT_TO_DOUBLE(v, a);
  571. CONVERT_TO_DOUBLE(w, b);
  572. if (b == 0.0) {
  573. PyErr_SetString(PyExc_ZeroDivisionError,
  574. "float division by zero");
  575. return NULL;
  576. }
  577. a = a / b;
  578. return PyFloat_FromDouble(a);
  579. }
  580. static PyObject *
  581. float_rem(PyObject *v, PyObject *w)
  582. {
  583. double vx, wx;
  584. double mod;
  585. CONVERT_TO_DOUBLE(v, vx);
  586. CONVERT_TO_DOUBLE(w, wx);
  587. if (wx == 0.0) {
  588. PyErr_SetString(PyExc_ZeroDivisionError,
  589. "float modulo");
  590. return NULL;
  591. }
  592. mod = fmod(vx, wx);
  593. if (mod) {
  594. /* ensure the remainder has the same sign as the denominator */
  595. if ((wx < 0) != (mod < 0)) {
  596. mod += wx;
  597. }
  598. }
  599. else {
  600. /* the remainder is zero, and in the presence of signed zeroes
  601. fmod returns different results across platforms; ensure
  602. it has the same sign as the denominator. */
  603. mod = copysign(0.0, wx);
  604. }
  605. return PyFloat_FromDouble(mod);
  606. }
  607. static void
  608. _float_div_mod(double vx, double wx, double *floordiv, double *mod)
  609. {
  610. double div;
  611. *mod = fmod(vx, wx);
  612. /* fmod is typically exact, so vx-mod is *mathematically* an
  613. exact multiple of wx. But this is fp arithmetic, and fp
  614. vx - mod is an approximation; the result is that div may
  615. not be an exact integral value after the division, although
  616. it will always be very close to one.
  617. */
  618. div = (vx - *mod) / wx;
  619. if (*mod) {
  620. /* ensure the remainder has the same sign as the denominator */
  621. if ((wx < 0) != (*mod < 0)) {
  622. *mod += wx;
  623. div -= 1.0;
  624. }
  625. }
  626. else {
  627. /* the remainder is zero, and in the presence of signed zeroes
  628. fmod returns different results across platforms; ensure
  629. it has the same sign as the denominator. */
  630. *mod = copysign(0.0, wx);
  631. }
  632. /* snap quotient to nearest integral value */
  633. if (div) {
  634. *floordiv = floor(div);
  635. if (div - *floordiv > 0.5) {
  636. *floordiv += 1.0;
  637. }
  638. }
  639. else {
  640. /* div is zero - get the same sign as the true quotient */
  641. *floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
  642. }
  643. }
  644. static PyObject *
  645. float_divmod(PyObject *v, PyObject *w)
  646. {
  647. double vx, wx;
  648. double mod, floordiv;
  649. CONVERT_TO_DOUBLE(v, vx);
  650. CONVERT_TO_DOUBLE(w, wx);
  651. if (wx == 0.0) {
  652. PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
  653. return NULL;
  654. }
  655. _float_div_mod(vx, wx, &floordiv, &mod);
  656. return Py_BuildValue("(dd)", floordiv, mod);
  657. }
  658. static PyObject *
  659. float_floor_div(PyObject *v, PyObject *w)
  660. {
  661. double vx, wx;
  662. double mod, floordiv;
  663. CONVERT_TO_DOUBLE(v, vx);
  664. CONVERT_TO_DOUBLE(w, wx);
  665. if (wx == 0.0) {
  666. PyErr_SetString(PyExc_ZeroDivisionError, "float floor division by zero");
  667. return NULL;
  668. }
  669. _float_div_mod(vx, wx, &floordiv, &mod);
  670. return PyFloat_FromDouble(floordiv);
  671. }
  672. /* determine whether x is an odd integer or not; assumes that
  673. x is not an infinity or nan. */
  674. #define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
  675. static PyObject *
  676. float_pow(PyObject *v, PyObject *w, PyObject *z)
  677. {
  678. double iv, iw, ix;
  679. int negate_result = 0;
  680. if ((PyObject *)z != Py_None) {
  681. PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
  682. "allowed unless all arguments are integers");
  683. return NULL;
  684. }
  685. CONVERT_TO_DOUBLE(v, iv);
  686. CONVERT_TO_DOUBLE(w, iw);
  687. /* Sort out special cases here instead of relying on pow() */
  688. if (iw == 0) { /* v**0 is 1, even 0**0 */
  689. return PyFloat_FromDouble(1.0);
  690. }
  691. if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
  692. return PyFloat_FromDouble(iv);
  693. }
  694. if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
  695. return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
  696. }
  697. if (Py_IS_INFINITY(iw)) {
  698. /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
  699. * abs(v) > 1 (including case where v infinite)
  700. *
  701. * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
  702. * abs(v) > 1 (including case where v infinite)
  703. */
  704. iv = fabs(iv);
  705. if (iv == 1.0)
  706. return PyFloat_FromDouble(1.0);
  707. else if ((iw > 0.0) == (iv > 1.0))
  708. return PyFloat_FromDouble(fabs(iw)); /* return inf */
  709. else
  710. return PyFloat_FromDouble(0.0);
  711. }
  712. if (Py_IS_INFINITY(iv)) {
  713. /* (+-inf)**w is: inf for w positive, 0 for w negative; in
  714. * both cases, we need to add the appropriate sign if w is
  715. * an odd integer.
  716. */
  717. int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
  718. if (iw > 0.0)
  719. return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
  720. else
  721. return PyFloat_FromDouble(iw_is_odd ?
  722. copysign(0.0, iv) : 0.0);
  723. }
  724. if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
  725. (already dealt with above), and an error
  726. if w is negative. */
  727. int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
  728. if (iw < 0.0) {
  729. PyErr_SetString(PyExc_ZeroDivisionError,
  730. "0.0 cannot be raised to a "
  731. "negative power");
  732. return NULL;
  733. }
  734. /* use correct sign if iw is odd */
  735. return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
  736. }
  737. if (iv < 0.0) {
  738. /* Whether this is an error is a mess, and bumps into libm
  739. * bugs so we have to figure it out ourselves.
  740. */
  741. if (iw != floor(iw)) {
  742. /* Negative numbers raised to fractional powers
  743. * become complex.
  744. */
  745. return PyComplex_Type.tp_as_number->nb_power(v, w, z);
  746. }
  747. /* iw is an exact integer, albeit perhaps a very large
  748. * one. Replace iv by its absolute value and remember
  749. * to negate the pow result if iw is odd.
  750. */
  751. iv = -iv;
  752. negate_result = DOUBLE_IS_ODD_INTEGER(iw);
  753. }
  754. if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
  755. /* (-1) ** large_integer also ends up here. Here's an
  756. * extract from the comments for the previous
  757. * implementation explaining why this special case is
  758. * necessary:
  759. *
  760. * -1 raised to an exact integer should never be exceptional.
  761. * Alas, some libms (chiefly glibc as of early 2003) return
  762. * NaN and set EDOM on pow(-1, large_int) if the int doesn't
  763. * happen to be representable in a *C* integer. That's a
  764. * bug.
  765. */
  766. return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
  767. }
  768. /* Now iv and iw are finite, iw is nonzero, and iv is
  769. * positive and not equal to 1.0. We finally allow
  770. * the platform pow to step in and do the rest.
  771. */
  772. errno = 0;
  773. ix = pow(iv, iw);
  774. _Py_ADJUST_ERANGE1(ix);
  775. if (negate_result)
  776. ix = -ix;
  777. if (errno != 0) {
  778. /* We don't expect any errno value other than ERANGE, but
  779. * the range of libm bugs appears unbounded.
  780. */
  781. PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
  782. PyExc_ValueError);
  783. return NULL;
  784. }
  785. return PyFloat_FromDouble(ix);
  786. }
  787. #undef DOUBLE_IS_ODD_INTEGER
  788. static PyObject *
  789. float_neg(PyFloatObject *v)
  790. {
  791. return PyFloat_FromDouble(-v->ob_fval);
  792. }
  793. static PyObject *
  794. float_abs(PyFloatObject *v)
  795. {
  796. return PyFloat_FromDouble(fabs(v->ob_fval));
  797. }
  798. static int
  799. float_bool(PyFloatObject *v)
  800. {
  801. return v->ob_fval != 0.0;
  802. }
  803. /*[clinic input]
  804. float.is_integer
  805. Return True if the float is an integer.
  806. [clinic start generated code]*/
  807. static PyObject *
  808. float_is_integer_impl(PyObject *self)
  809. /*[clinic end generated code: output=7112acf95a4d31ea input=311810d3f777e10d]*/
  810. {
  811. double x = PyFloat_AsDouble(self);
  812. PyObject *o;
  813. if (x == -1.0 && PyErr_Occurred())
  814. return NULL;
  815. if (!Py_IS_FINITE(x))
  816. Py_RETURN_FALSE;
  817. errno = 0;
  818. o = (floor(x) == x) ? Py_True : Py_False;
  819. if (errno != 0) {
  820. PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
  821. PyExc_ValueError);
  822. return NULL;
  823. }
  824. return Py_NewRef(o);
  825. }
  826. /*[clinic input]
  827. float.__trunc__
  828. Return the Integral closest to x between 0 and x.
  829. [clinic start generated code]*/
  830. static PyObject *
  831. float___trunc___impl(PyObject *self)
  832. /*[clinic end generated code: output=dd3e289dd4c6b538 input=591b9ba0d650fdff]*/
  833. {
  834. return PyLong_FromDouble(PyFloat_AS_DOUBLE(self));
  835. }
  836. /*[clinic input]
  837. float.__floor__
  838. Return the floor as an Integral.
  839. [clinic start generated code]*/
  840. static PyObject *
  841. float___floor___impl(PyObject *self)
  842. /*[clinic end generated code: output=e0551dbaea8c01d1 input=77bb13eb12e268df]*/
  843. {
  844. double x = PyFloat_AS_DOUBLE(self);
  845. return PyLong_FromDouble(floor(x));
  846. }
  847. /*[clinic input]
  848. float.__ceil__
  849. Return the ceiling as an Integral.
  850. [clinic start generated code]*/
  851. static PyObject *
  852. float___ceil___impl(PyObject *self)
  853. /*[clinic end generated code: output=a2fd8858f73736f9 input=79e41ae94aa0a516]*/
  854. {
  855. double x = PyFloat_AS_DOUBLE(self);
  856. return PyLong_FromDouble(ceil(x));
  857. }
  858. /* double_round: rounds a finite double to the closest multiple of
  859. 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
  860. ndigits <= 323). Returns a Python float, or sets a Python error and
  861. returns NULL on failure (OverflowError and memory errors are possible). */
  862. #if _PY_SHORT_FLOAT_REPR == 1
  863. /* version of double_round that uses the correctly-rounded string<->double
  864. conversions from Python/dtoa.c */
  865. static PyObject *
  866. double_round(double x, int ndigits) {
  867. double rounded;
  868. Py_ssize_t buflen, mybuflen=100;
  869. char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
  870. int decpt, sign;
  871. PyObject *result = NULL;
  872. _Py_SET_53BIT_PRECISION_HEADER;
  873. /* round to a decimal string */
  874. _Py_SET_53BIT_PRECISION_START;
  875. buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
  876. _Py_SET_53BIT_PRECISION_END;
  877. if (buf == NULL) {
  878. PyErr_NoMemory();
  879. return NULL;
  880. }
  881. /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
  882. buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
  883. buflen = buf_end - buf;
  884. if (buflen + 8 > mybuflen) {
  885. mybuflen = buflen+8;
  886. mybuf = (char *)PyMem_Malloc(mybuflen);
  887. if (mybuf == NULL) {
  888. PyErr_NoMemory();
  889. goto exit;
  890. }
  891. }
  892. /* copy buf to mybuf, adding exponent, sign and leading 0 */
  893. PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
  894. buf, decpt - (int)buflen);
  895. /* and convert the resulting string back to a double */
  896. errno = 0;
  897. _Py_SET_53BIT_PRECISION_START;
  898. rounded = _Py_dg_strtod(mybuf, NULL);
  899. _Py_SET_53BIT_PRECISION_END;
  900. if (errno == ERANGE && fabs(rounded) >= 1.)
  901. PyErr_SetString(PyExc_OverflowError,
  902. "rounded value too large to represent");
  903. else
  904. result = PyFloat_FromDouble(rounded);
  905. /* done computing value; now clean up */
  906. if (mybuf != shortbuf)
  907. PyMem_Free(mybuf);
  908. exit:
  909. _Py_dg_freedtoa(buf);
  910. return result;
  911. }
  912. #else // _PY_SHORT_FLOAT_REPR == 0
  913. /* fallback version, to be used when correctly rounded binary<->decimal
  914. conversions aren't available */
  915. static PyObject *
  916. double_round(double x, int ndigits) {
  917. double pow1, pow2, y, z;
  918. if (ndigits >= 0) {
  919. if (ndigits > 22) {
  920. /* pow1 and pow2 are each safe from overflow, but
  921. pow1*pow2 ~= pow(10.0, ndigits) might overflow */
  922. pow1 = pow(10.0, (double)(ndigits-22));
  923. pow2 = 1e22;
  924. }
  925. else {
  926. pow1 = pow(10.0, (double)ndigits);
  927. pow2 = 1.0;
  928. }
  929. y = (x*pow1)*pow2;
  930. /* if y overflows, then rounded value is exactly x */
  931. if (!Py_IS_FINITE(y))
  932. return PyFloat_FromDouble(x);
  933. }
  934. else {
  935. pow1 = pow(10.0, (double)-ndigits);
  936. pow2 = 1.0; /* unused; silences a gcc compiler warning */
  937. y = x / pow1;
  938. }
  939. z = round(y);
  940. if (fabs(y-z) == 0.5)
  941. /* halfway between two integers; use round-half-even */
  942. z = 2.0*round(y/2.0);
  943. if (ndigits >= 0)
  944. z = (z / pow2) / pow1;
  945. else
  946. z *= pow1;
  947. /* if computation resulted in overflow, raise OverflowError */
  948. if (!Py_IS_FINITE(z)) {
  949. PyErr_SetString(PyExc_OverflowError,
  950. "overflow occurred during round");
  951. return NULL;
  952. }
  953. return PyFloat_FromDouble(z);
  954. }
  955. #endif // _PY_SHORT_FLOAT_REPR == 0
  956. /* round a Python float v to the closest multiple of 10**-ndigits */
  957. /*[clinic input]
  958. float.__round__
  959. ndigits as o_ndigits: object = None
  960. /
  961. Return the Integral closest to x, rounding half toward even.
  962. When an argument is passed, work like built-in round(x, ndigits).
  963. [clinic start generated code]*/
  964. static PyObject *
  965. float___round___impl(PyObject *self, PyObject *o_ndigits)
  966. /*[clinic end generated code: output=374c36aaa0f13980 input=fc0fe25924fbc9ed]*/
  967. {
  968. double x, rounded;
  969. Py_ssize_t ndigits;
  970. x = PyFloat_AsDouble(self);
  971. if (o_ndigits == Py_None) {
  972. /* single-argument round or with None ndigits:
  973. * round to nearest integer */
  974. rounded = round(x);
  975. if (fabs(x-rounded) == 0.5)
  976. /* halfway case: round to even */
  977. rounded = 2.0*round(x/2.0);
  978. return PyLong_FromDouble(rounded);
  979. }
  980. /* interpret second argument as a Py_ssize_t; clips on overflow */
  981. ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
  982. if (ndigits == -1 && PyErr_Occurred())
  983. return NULL;
  984. /* nans and infinities round to themselves */
  985. if (!Py_IS_FINITE(x))
  986. return PyFloat_FromDouble(x);
  987. /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
  988. always rounds to itself. For ndigits < NDIGITS_MIN, x always
  989. rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
  990. #define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
  991. #define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
  992. if (ndigits > NDIGITS_MAX)
  993. /* return x */
  994. return PyFloat_FromDouble(x);
  995. else if (ndigits < NDIGITS_MIN)
  996. /* return 0.0, but with sign of x */
  997. return PyFloat_FromDouble(0.0*x);
  998. else
  999. /* finite x, and ndigits is not unreasonably large */
  1000. return double_round(x, (int)ndigits);
  1001. #undef NDIGITS_MAX
  1002. #undef NDIGITS_MIN
  1003. }
  1004. static PyObject *
  1005. float_float(PyObject *v)
  1006. {
  1007. if (PyFloat_CheckExact(v)) {
  1008. return Py_NewRef(v);
  1009. }
  1010. else {
  1011. return PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
  1012. }
  1013. }
  1014. /*[clinic input]
  1015. float.conjugate
  1016. Return self, the complex conjugate of any float.
  1017. [clinic start generated code]*/
  1018. static PyObject *
  1019. float_conjugate_impl(PyObject *self)
  1020. /*[clinic end generated code: output=8ca292c2479194af input=82ba6f37a9ff91dd]*/
  1021. {
  1022. return float_float(self);
  1023. }
  1024. /* turn ASCII hex characters into integer values and vice versa */
  1025. static char
  1026. char_from_hex(int x)
  1027. {
  1028. assert(0 <= x && x < 16);
  1029. return Py_hexdigits[x];
  1030. }
  1031. static int
  1032. hex_from_char(char c) {
  1033. int x;
  1034. switch(c) {
  1035. case '0':
  1036. x = 0;
  1037. break;
  1038. case '1':
  1039. x = 1;
  1040. break;
  1041. case '2':
  1042. x = 2;
  1043. break;
  1044. case '3':
  1045. x = 3;
  1046. break;
  1047. case '4':
  1048. x = 4;
  1049. break;
  1050. case '5':
  1051. x = 5;
  1052. break;
  1053. case '6':
  1054. x = 6;
  1055. break;
  1056. case '7':
  1057. x = 7;
  1058. break;
  1059. case '8':
  1060. x = 8;
  1061. break;
  1062. case '9':
  1063. x = 9;
  1064. break;
  1065. case 'a':
  1066. case 'A':
  1067. x = 10;
  1068. break;
  1069. case 'b':
  1070. case 'B':
  1071. x = 11;
  1072. break;
  1073. case 'c':
  1074. case 'C':
  1075. x = 12;
  1076. break;
  1077. case 'd':
  1078. case 'D':
  1079. x = 13;
  1080. break;
  1081. case 'e':
  1082. case 'E':
  1083. x = 14;
  1084. break;
  1085. case 'f':
  1086. case 'F':
  1087. x = 15;
  1088. break;
  1089. default:
  1090. x = -1;
  1091. break;
  1092. }
  1093. return x;
  1094. }
  1095. /* convert a float to a hexadecimal string */
  1096. /* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
  1097. of the form 4k+1. */
  1098. #define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
  1099. /*[clinic input]
  1100. float.hex
  1101. Return a hexadecimal representation of a floating-point number.
  1102. >>> (-0.1).hex()
  1103. '-0x1.999999999999ap-4'
  1104. >>> 3.14159.hex()
  1105. '0x1.921f9f01b866ep+1'
  1106. [clinic start generated code]*/
  1107. static PyObject *
  1108. float_hex_impl(PyObject *self)
  1109. /*[clinic end generated code: output=0ebc9836e4d302d4 input=bec1271a33d47e67]*/
  1110. {
  1111. double x, m;
  1112. int e, shift, i, si, esign;
  1113. /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
  1114. trailing NUL byte. */
  1115. char s[(TOHEX_NBITS-1)/4+3];
  1116. CONVERT_TO_DOUBLE(self, x);
  1117. if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
  1118. return float_repr((PyFloatObject *)self);
  1119. if (x == 0.0) {
  1120. if (copysign(1.0, x) == -1.0)
  1121. return PyUnicode_FromString("-0x0.0p+0");
  1122. else
  1123. return PyUnicode_FromString("0x0.0p+0");
  1124. }
  1125. m = frexp(fabs(x), &e);
  1126. shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
  1127. m = ldexp(m, shift);
  1128. e -= shift;
  1129. si = 0;
  1130. s[si] = char_from_hex((int)m);
  1131. si++;
  1132. m -= (int)m;
  1133. s[si] = '.';
  1134. si++;
  1135. for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
  1136. m *= 16.0;
  1137. s[si] = char_from_hex((int)m);
  1138. si++;
  1139. m -= (int)m;
  1140. }
  1141. s[si] = '\0';
  1142. if (e < 0) {
  1143. esign = (int)'-';
  1144. e = -e;
  1145. }
  1146. else
  1147. esign = (int)'+';
  1148. if (x < 0.0)
  1149. return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
  1150. else
  1151. return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
  1152. }
  1153. /* Convert a hexadecimal string to a float. */
  1154. /*[clinic input]
  1155. @classmethod
  1156. float.fromhex
  1157. string: object
  1158. /
  1159. Create a floating-point number from a hexadecimal string.
  1160. >>> float.fromhex('0x1.ffffp10')
  1161. 2047.984375
  1162. >>> float.fromhex('-0x1p-1074')
  1163. -5e-324
  1164. [clinic start generated code]*/
  1165. static PyObject *
  1166. float_fromhex(PyTypeObject *type, PyObject *string)
  1167. /*[clinic end generated code: output=46c0274d22b78e82 input=0407bebd354bca89]*/
  1168. {
  1169. PyObject *result;
  1170. double x;
  1171. long exp, top_exp, lsb, key_digit;
  1172. const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
  1173. int half_eps, digit, round_up, negate=0;
  1174. Py_ssize_t length, ndigits, fdigits, i;
  1175. /*
  1176. * For the sake of simplicity and correctness, we impose an artificial
  1177. * limit on ndigits, the total number of hex digits in the coefficient
  1178. * The limit is chosen to ensure that, writing exp for the exponent,
  1179. *
  1180. * (1) if exp > LONG_MAX/2 then the value of the hex string is
  1181. * guaranteed to overflow (provided it's nonzero)
  1182. *
  1183. * (2) if exp < LONG_MIN/2 then the value of the hex string is
  1184. * guaranteed to underflow to 0.
  1185. *
  1186. * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
  1187. * overflow in the calculation of exp and top_exp below.
  1188. *
  1189. * More specifically, ndigits is assumed to satisfy the following
  1190. * inequalities:
  1191. *
  1192. * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
  1193. * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
  1194. *
  1195. * If either of these inequalities is not satisfied, a ValueError is
  1196. * raised. Otherwise, write x for the value of the hex string, and
  1197. * assume x is nonzero. Then
  1198. *
  1199. * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
  1200. *
  1201. * Now if exp > LONG_MAX/2 then:
  1202. *
  1203. * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
  1204. * = DBL_MAX_EXP
  1205. *
  1206. * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
  1207. * double, so overflows. If exp < LONG_MIN/2, then
  1208. *
  1209. * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
  1210. * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
  1211. * = DBL_MIN_EXP - DBL_MANT_DIG - 1
  1212. *
  1213. * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
  1214. * when converted to a C double.
  1215. *
  1216. * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
  1217. * exp+4*ndigits and exp-4*ndigits are within the range of a long.
  1218. */
  1219. s = PyUnicode_AsUTF8AndSize(string, &length);
  1220. if (s == NULL)
  1221. return NULL;
  1222. s_end = s + length;
  1223. /********************
  1224. * Parse the string *
  1225. ********************/
  1226. /* leading whitespace */
  1227. while (Py_ISSPACE(*s))
  1228. s++;
  1229. /* infinities and nans */
  1230. x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
  1231. if (coeff_end != s) {
  1232. s = coeff_end;
  1233. goto finished;
  1234. }
  1235. /* optional sign */
  1236. if (*s == '-') {
  1237. s++;
  1238. negate = 1;
  1239. }
  1240. else if (*s == '+')
  1241. s++;
  1242. /* [0x] */
  1243. s_store = s;
  1244. if (*s == '0') {
  1245. s++;
  1246. if (*s == 'x' || *s == 'X')
  1247. s++;
  1248. else
  1249. s = s_store;
  1250. }
  1251. /* coefficient: <integer> [. <fraction>] */
  1252. coeff_start = s;
  1253. while (hex_from_char(*s) >= 0)
  1254. s++;
  1255. s_store = s;
  1256. if (*s == '.') {
  1257. s++;
  1258. while (hex_from_char(*s) >= 0)
  1259. s++;
  1260. coeff_end = s-1;
  1261. }
  1262. else
  1263. coeff_end = s;
  1264. /* ndigits = total # of hex digits; fdigits = # after point */
  1265. ndigits = coeff_end - coeff_start;
  1266. fdigits = coeff_end - s_store;
  1267. if (ndigits == 0)
  1268. goto parse_error;
  1269. if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
  1270. LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
  1271. goto insane_length_error;
  1272. /* [p <exponent>] */
  1273. if (*s == 'p' || *s == 'P') {
  1274. s++;
  1275. exp_start = s;
  1276. if (*s == '-' || *s == '+')
  1277. s++;
  1278. if (!('0' <= *s && *s <= '9'))
  1279. goto parse_error;
  1280. s++;
  1281. while ('0' <= *s && *s <= '9')
  1282. s++;
  1283. exp = strtol(exp_start, NULL, 10);
  1284. }
  1285. else
  1286. exp = 0;
  1287. /* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
  1288. #define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
  1289. coeff_end-(j) : \
  1290. coeff_end-1-(j)))
  1291. /*******************************************
  1292. * Compute rounded value of the hex string *
  1293. *******************************************/
  1294. /* Discard leading zeros, and catch extreme overflow and underflow */
  1295. while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
  1296. ndigits--;
  1297. if (ndigits == 0 || exp < LONG_MIN/2) {
  1298. x = 0.0;
  1299. goto finished;
  1300. }
  1301. if (exp > LONG_MAX/2)
  1302. goto overflow_error;
  1303. /* Adjust exponent for fractional part. */
  1304. exp = exp - 4*((long)fdigits);
  1305. /* top_exp = 1 more than exponent of most sig. bit of coefficient */
  1306. top_exp = exp + 4*((long)ndigits - 1);
  1307. for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
  1308. top_exp++;
  1309. /* catch almost all nonextreme cases of overflow and underflow here */
  1310. if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
  1311. x = 0.0;
  1312. goto finished;
  1313. }
  1314. if (top_exp > DBL_MAX_EXP)
  1315. goto overflow_error;
  1316. /* lsb = exponent of least significant bit of the *rounded* value.
  1317. This is top_exp - DBL_MANT_DIG unless result is subnormal. */
  1318. lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
  1319. x = 0.0;
  1320. if (exp >= lsb) {
  1321. /* no rounding required */
  1322. for (i = ndigits-1; i >= 0; i--)
  1323. x = 16.0*x + HEX_DIGIT(i);
  1324. x = ldexp(x, (int)(exp));
  1325. goto finished;
  1326. }
  1327. /* rounding required. key_digit is the index of the hex digit
  1328. containing the first bit to be rounded away. */
  1329. half_eps = 1 << (int)((lsb - exp - 1) % 4);
  1330. key_digit = (lsb - exp - 1) / 4;
  1331. for (i = ndigits-1; i > key_digit; i--)
  1332. x = 16.0*x + HEX_DIGIT(i);
  1333. digit = HEX_DIGIT(key_digit);
  1334. x = 16.0*x + (double)(digit & (16-2*half_eps));
  1335. /* round-half-even: round up if bit lsb-1 is 1 and at least one of
  1336. bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
  1337. if ((digit & half_eps) != 0) {
  1338. round_up = 0;
  1339. if ((digit & (3*half_eps-1)) != 0 || (half_eps == 8 &&
  1340. key_digit+1 < ndigits && (HEX_DIGIT(key_digit+1) & 1) != 0))
  1341. round_up = 1;
  1342. else
  1343. for (i = key_digit-1; i >= 0; i--)
  1344. if (HEX_DIGIT(i) != 0) {
  1345. round_up = 1;
  1346. break;
  1347. }
  1348. if (round_up) {
  1349. x += 2*half_eps;
  1350. if (top_exp == DBL_MAX_EXP &&
  1351. x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
  1352. /* overflow corner case: pre-rounded value <
  1353. 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
  1354. goto overflow_error;
  1355. }
  1356. }
  1357. x = ldexp(x, (int)(exp+4*key_digit));
  1358. finished:
  1359. /* optional trailing whitespace leading to the end of the string */
  1360. while (Py_ISSPACE(*s))
  1361. s++;
  1362. if (s != s_end)
  1363. goto parse_error;
  1364. result = PyFloat_FromDouble(negate ? -x : x);
  1365. if (type != &PyFloat_Type && result != NULL) {
  1366. Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
  1367. }
  1368. return result;
  1369. overflow_error:
  1370. PyErr_SetString(PyExc_OverflowError,
  1371. "hexadecimal value too large to represent as a float");
  1372. return NULL;
  1373. parse_error:
  1374. PyErr_SetString(PyExc_ValueError,
  1375. "invalid hexadecimal floating-point string");
  1376. return NULL;
  1377. insane_length_error:
  1378. PyErr_SetString(PyExc_ValueError,
  1379. "hexadecimal string too long to convert");
  1380. return NULL;
  1381. }
  1382. /*[clinic input]
  1383. float.as_integer_ratio
  1384. Return a pair of integers, whose ratio is exactly equal to the original float.
  1385. The ratio is in lowest terms and has a positive denominator. Raise
  1386. OverflowError on infinities and a ValueError on NaNs.
  1387. >>> (10.0).as_integer_ratio()
  1388. (10, 1)
  1389. >>> (0.0).as_integer_ratio()
  1390. (0, 1)
  1391. >>> (-.25).as_integer_ratio()
  1392. (-1, 4)
  1393. [clinic start generated code]*/
  1394. static PyObject *
  1395. float_as_integer_ratio_impl(PyObject *self)
  1396. /*[clinic end generated code: output=65f25f0d8d30a712 input=d5ba7765655d75bd]*/
  1397. {
  1398. double self_double;
  1399. double float_part;
  1400. int exponent;
  1401. int i;
  1402. PyObject *py_exponent = NULL;
  1403. PyObject *numerator = NULL;
  1404. PyObject *denominator = NULL;
  1405. PyObject *result_pair = NULL;
  1406. PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
  1407. CONVERT_TO_DOUBLE(self, self_double);
  1408. if (Py_IS_INFINITY(self_double)) {
  1409. PyErr_SetString(PyExc_OverflowError,
  1410. "cannot convert Infinity to integer ratio");
  1411. return NULL;
  1412. }
  1413. if (Py_IS_NAN(self_double)) {
  1414. PyErr_SetString(PyExc_ValueError,
  1415. "cannot convert NaN to integer ratio");
  1416. return NULL;
  1417. }
  1418. float_part = frexp(self_double, &exponent); /* self_double == float_part * 2**exponent exactly */
  1419. for (i=0; i<300 && float_part != floor(float_part) ; i++) {
  1420. float_part *= 2.0;
  1421. exponent--;
  1422. }
  1423. /* self == float_part * 2**exponent exactly and float_part is integral.
  1424. If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
  1425. to be truncated by PyLong_FromDouble(). */
  1426. numerator = PyLong_FromDouble(float_part);
  1427. if (numerator == NULL)
  1428. goto error;
  1429. denominator = PyLong_FromLong(1);
  1430. if (denominator == NULL)
  1431. goto error;
  1432. py_exponent = PyLong_FromLong(Py_ABS(exponent));
  1433. if (py_exponent == NULL)
  1434. goto error;
  1435. /* fold in 2**exponent */
  1436. if (exponent > 0) {
  1437. Py_SETREF(numerator,
  1438. long_methods->nb_lshift(numerator, py_exponent));
  1439. if (numerator == NULL)
  1440. goto error;
  1441. }
  1442. else {
  1443. Py_SETREF(denominator,
  1444. long_methods->nb_lshift(denominator, py_exponent));
  1445. if (denominator == NULL)
  1446. goto error;
  1447. }
  1448. result_pair = PyTuple_Pack(2, numerator, denominator);
  1449. error:
  1450. Py_XDECREF(py_exponent);
  1451. Py_XDECREF(denominator);
  1452. Py_XDECREF(numerator);
  1453. return result_pair;
  1454. }
  1455. static PyObject *
  1456. float_subtype_new(PyTypeObject *type, PyObject *x);
  1457. /*[clinic input]
  1458. @classmethod
  1459. float.__new__ as float_new
  1460. x: object(c_default="NULL") = 0
  1461. /
  1462. Convert a string or number to a floating-point number, if possible.
  1463. [clinic start generated code]*/
  1464. static PyObject *
  1465. float_new_impl(PyTypeObject *type, PyObject *x)
  1466. /*[clinic end generated code: output=ccf1e8dc460ba6ba input=55909f888aa0c8a6]*/
  1467. {
  1468. if (type != &PyFloat_Type) {
  1469. if (x == NULL) {
  1470. x = _PyLong_GetZero();
  1471. }
  1472. return float_subtype_new(type, x); /* Wimp out */
  1473. }
  1474. if (x == NULL) {
  1475. return PyFloat_FromDouble(0.0);
  1476. }
  1477. /* If it's a string, but not a string subclass, use
  1478. PyFloat_FromString. */
  1479. if (PyUnicode_CheckExact(x))
  1480. return PyFloat_FromString(x);
  1481. return PyNumber_Float(x);
  1482. }
  1483. /* Wimpy, slow approach to tp_new calls for subtypes of float:
  1484. first create a regular float from whatever arguments we got,
  1485. then allocate a subtype instance and initialize its ob_fval
  1486. from the regular float. The regular float is then thrown away.
  1487. */
  1488. static PyObject *
  1489. float_subtype_new(PyTypeObject *type, PyObject *x)
  1490. {
  1491. PyObject *tmp, *newobj;
  1492. assert(PyType_IsSubtype(type, &PyFloat_Type));
  1493. tmp = float_new_impl(&PyFloat_Type, x);
  1494. if (tmp == NULL)
  1495. return NULL;
  1496. assert(PyFloat_Check(tmp));
  1497. newobj = type->tp_alloc(type, 0);
  1498. if (newobj == NULL) {
  1499. Py_DECREF(tmp);
  1500. return NULL;
  1501. }
  1502. ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
  1503. Py_DECREF(tmp);
  1504. return newobj;
  1505. }
  1506. static PyObject *
  1507. float_vectorcall(PyObject *type, PyObject * const*args,
  1508. size_t nargsf, PyObject *kwnames)
  1509. {
  1510. if (!_PyArg_NoKwnames("float", kwnames)) {
  1511. return NULL;
  1512. }
  1513. Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
  1514. if (!_PyArg_CheckPositional("float", nargs, 0, 1)) {
  1515. return NULL;
  1516. }
  1517. PyObject *x = nargs >= 1 ? args[0] : NULL;
  1518. return float_new_impl(_PyType_CAST(type), x);
  1519. }
  1520. /*[clinic input]
  1521. float.__getnewargs__
  1522. [clinic start generated code]*/
  1523. static PyObject *
  1524. float___getnewargs___impl(PyObject *self)
  1525. /*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/
  1526. {
  1527. return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval);
  1528. }
  1529. /* this is for the benefit of the pack/unpack routines below */
  1530. typedef enum _py_float_format_type float_format_type;
  1531. #define unknown_format _py_float_format_unknown
  1532. #define ieee_big_endian_format _py_float_format_ieee_big_endian
  1533. #define ieee_little_endian_format _py_float_format_ieee_little_endian
  1534. #define float_format (_PyRuntime.float_state.float_format)
  1535. #define double_format (_PyRuntime.float_state.double_format)
  1536. /*[clinic input]
  1537. @classmethod
  1538. float.__getformat__
  1539. typestr: str
  1540. Must be 'double' or 'float'.
  1541. /
  1542. You probably don't want to use this function.
  1543. It exists mainly to be used in Python's test suite.
  1544. This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
  1545. little-endian' best describes the format of floating-point numbers used by the
  1546. C type named by typestr.
  1547. [clinic start generated code]*/
  1548. static PyObject *
  1549. float___getformat___impl(PyTypeObject *type, const char *typestr)
  1550. /*[clinic end generated code: output=2bfb987228cc9628 input=90d5e246409a246e]*/
  1551. {
  1552. float_format_type r;
  1553. if (strcmp(typestr, "double") == 0) {
  1554. r = double_format;
  1555. }
  1556. else if (strcmp(typestr, "float") == 0) {
  1557. r = float_format;
  1558. }
  1559. else {
  1560. PyErr_SetString(PyExc_ValueError,
  1561. "__getformat__() argument 1 must be "
  1562. "'double' or 'float'");
  1563. return NULL;
  1564. }
  1565. switch (r) {
  1566. case unknown_format:
  1567. return PyUnicode_FromString("unknown");
  1568. case ieee_little_endian_format:
  1569. return PyUnicode_FromString("IEEE, little-endian");
  1570. case ieee_big_endian_format:
  1571. return PyUnicode_FromString("IEEE, big-endian");
  1572. default:
  1573. PyErr_SetString(PyExc_RuntimeError,
  1574. "insane float_format or double_format");
  1575. return NULL;
  1576. }
  1577. }
  1578. static PyObject *
  1579. float_getreal(PyObject *v, void *closure)
  1580. {
  1581. return float_float(v);
  1582. }
  1583. static PyObject *
  1584. float_getimag(PyObject *v, void *closure)
  1585. {
  1586. return PyFloat_FromDouble(0.0);
  1587. }
  1588. /*[clinic input]
  1589. float.__format__
  1590. format_spec: unicode
  1591. /
  1592. Formats the float according to format_spec.
  1593. [clinic start generated code]*/
  1594. static PyObject *
  1595. float___format___impl(PyObject *self, PyObject *format_spec)
  1596. /*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/
  1597. {
  1598. _PyUnicodeWriter writer;
  1599. int ret;
  1600. _PyUnicodeWriter_Init(&writer);
  1601. ret = _PyFloat_FormatAdvancedWriter(
  1602. &writer,
  1603. self,
  1604. format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
  1605. if (ret == -1) {
  1606. _PyUnicodeWriter_Dealloc(&writer);
  1607. return NULL;
  1608. }
  1609. return _PyUnicodeWriter_Finish(&writer);
  1610. }
  1611. static PyMethodDef float_methods[] = {
  1612. FLOAT_CONJUGATE_METHODDEF
  1613. FLOAT___TRUNC___METHODDEF
  1614. FLOAT___FLOOR___METHODDEF
  1615. FLOAT___CEIL___METHODDEF
  1616. FLOAT___ROUND___METHODDEF
  1617. FLOAT_AS_INTEGER_RATIO_METHODDEF
  1618. FLOAT_FROMHEX_METHODDEF
  1619. FLOAT_HEX_METHODDEF
  1620. FLOAT_IS_INTEGER_METHODDEF
  1621. FLOAT___GETNEWARGS___METHODDEF
  1622. FLOAT___GETFORMAT___METHODDEF
  1623. FLOAT___FORMAT___METHODDEF
  1624. {NULL, NULL} /* sentinel */
  1625. };
  1626. static PyGetSetDef float_getset[] = {
  1627. {"real",
  1628. float_getreal, (setter)NULL,
  1629. "the real part of a complex number",
  1630. NULL},
  1631. {"imag",
  1632. float_getimag, (setter)NULL,
  1633. "the imaginary part of a complex number",
  1634. NULL},
  1635. {NULL} /* Sentinel */
  1636. };
  1637. static PyNumberMethods float_as_number = {
  1638. float_add, /* nb_add */
  1639. float_sub, /* nb_subtract */
  1640. float_mul, /* nb_multiply */
  1641. float_rem, /* nb_remainder */
  1642. float_divmod, /* nb_divmod */
  1643. float_pow, /* nb_power */
  1644. (unaryfunc)float_neg, /* nb_negative */
  1645. float_float, /* nb_positive */
  1646. (unaryfunc)float_abs, /* nb_absolute */
  1647. (inquiry)float_bool, /* nb_bool */
  1648. 0, /* nb_invert */
  1649. 0, /* nb_lshift */
  1650. 0, /* nb_rshift */
  1651. 0, /* nb_and */
  1652. 0, /* nb_xor */
  1653. 0, /* nb_or */
  1654. float___trunc___impl, /* nb_int */
  1655. 0, /* nb_reserved */
  1656. float_float, /* nb_float */
  1657. 0, /* nb_inplace_add */
  1658. 0, /* nb_inplace_subtract */
  1659. 0, /* nb_inplace_multiply */
  1660. 0, /* nb_inplace_remainder */
  1661. 0, /* nb_inplace_power */
  1662. 0, /* nb_inplace_lshift */
  1663. 0, /* nb_inplace_rshift */
  1664. 0, /* nb_inplace_and */
  1665. 0, /* nb_inplace_xor */
  1666. 0, /* nb_inplace_or */
  1667. float_floor_div, /* nb_floor_divide */
  1668. float_div, /* nb_true_divide */
  1669. 0, /* nb_inplace_floor_divide */
  1670. 0, /* nb_inplace_true_divide */
  1671. };
  1672. PyTypeObject PyFloat_Type = {
  1673. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1674. "float",
  1675. sizeof(PyFloatObject),
  1676. 0,
  1677. (destructor)float_dealloc, /* tp_dealloc */
  1678. 0, /* tp_vectorcall_offset */
  1679. 0, /* tp_getattr */
  1680. 0, /* tp_setattr */
  1681. 0, /* tp_as_async */
  1682. (reprfunc)float_repr, /* tp_repr */
  1683. &float_as_number, /* tp_as_number */
  1684. 0, /* tp_as_sequence */
  1685. 0, /* tp_as_mapping */
  1686. (hashfunc)float_hash, /* tp_hash */
  1687. 0, /* tp_call */
  1688. 0, /* tp_str */
  1689. PyObject_GenericGetAttr, /* tp_getattro */
  1690. 0, /* tp_setattro */
  1691. 0, /* tp_as_buffer */
  1692. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  1693. _Py_TPFLAGS_MATCH_SELF, /* tp_flags */
  1694. float_new__doc__, /* tp_doc */
  1695. 0, /* tp_traverse */
  1696. 0, /* tp_clear */
  1697. float_richcompare, /* tp_richcompare */
  1698. 0, /* tp_weaklistoffset */
  1699. 0, /* tp_iter */
  1700. 0, /* tp_iternext */
  1701. float_methods, /* tp_methods */
  1702. 0, /* tp_members */
  1703. float_getset, /* tp_getset */
  1704. 0, /* tp_base */
  1705. 0, /* tp_dict */
  1706. 0, /* tp_descr_get */
  1707. 0, /* tp_descr_set */
  1708. 0, /* tp_dictoffset */
  1709. 0, /* tp_init */
  1710. 0, /* tp_alloc */
  1711. float_new, /* tp_new */
  1712. .tp_vectorcall = (vectorcallfunc)float_vectorcall,
  1713. };
  1714. static void
  1715. _init_global_state(void)
  1716. {
  1717. float_format_type detected_double_format, detected_float_format;
  1718. /* We attempt to determine if this machine is using IEEE
  1719. floating-point formats by peering at the bits of some
  1720. carefully chosen values. If it looks like we are on an
  1721. IEEE platform, the float packing/unpacking routines can
  1722. just copy bits, if not they resort to arithmetic & shifts
  1723. and masks. The shifts & masks approach works on all finite
  1724. values, but what happens to infinities, NaNs and signed
  1725. zeroes on packing is an accident, and attempting to unpack
  1726. a NaN or an infinity will raise an exception.
  1727. Note that if we're on some whacked-out platform which uses
  1728. IEEE formats but isn't strictly little-endian or big-
  1729. endian, we will fall back to the portable shifts & masks
  1730. method. */
  1731. #if SIZEOF_DOUBLE == 8
  1732. {
  1733. double x = 9006104071832581.0;
  1734. if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
  1735. detected_double_format = ieee_big_endian_format;
  1736. else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
  1737. detected_double_format = ieee_little_endian_format;
  1738. else
  1739. detected_double_format = unknown_format;
  1740. }
  1741. #else
  1742. detected_double_format = unknown_format;
  1743. #endif
  1744. #if SIZEOF_FLOAT == 4
  1745. {
  1746. float y = 16711938.0;
  1747. if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
  1748. detected_float_format = ieee_big_endian_format;
  1749. else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
  1750. detected_float_format = ieee_little_endian_format;
  1751. else
  1752. detected_float_format = unknown_format;
  1753. }
  1754. #else
  1755. detected_float_format = unknown_format;
  1756. #endif
  1757. double_format = detected_double_format;
  1758. float_format = detected_float_format;
  1759. }
  1760. void
  1761. _PyFloat_InitState(PyInterpreterState *interp)
  1762. {
  1763. if (!_Py_IsMainInterpreter(interp)) {
  1764. return;
  1765. }
  1766. _init_global_state();
  1767. }
  1768. PyStatus
  1769. _PyFloat_InitTypes(PyInterpreterState *interp)
  1770. {
  1771. /* Init float info */
  1772. if (_PyStructSequence_InitBuiltin(interp, &FloatInfoType,
  1773. &floatinfo_desc) < 0)
  1774. {
  1775. return _PyStatus_ERR("can't init float info type");
  1776. }
  1777. return _PyStatus_OK();
  1778. }
  1779. void
  1780. _PyFloat_ClearFreeList(PyInterpreterState *interp)
  1781. {
  1782. #if PyFloat_MAXFREELIST > 0
  1783. struct _Py_float_state *state = &interp->float_state;
  1784. PyFloatObject *f = state->free_list;
  1785. while (f != NULL) {
  1786. PyFloatObject *next = (PyFloatObject*) Py_TYPE(f);
  1787. PyObject_Free(f);
  1788. f = next;
  1789. }
  1790. state->free_list = NULL;
  1791. state->numfree = 0;
  1792. #endif
  1793. }
  1794. void
  1795. _PyFloat_Fini(PyInterpreterState *interp)
  1796. {
  1797. _PyFloat_ClearFreeList(interp);
  1798. #if defined(Py_DEBUG) && PyFloat_MAXFREELIST > 0
  1799. struct _Py_float_state *state = &interp->float_state;
  1800. state->numfree = -1;
  1801. #endif
  1802. }
  1803. void
  1804. _PyFloat_FiniType(PyInterpreterState *interp)
  1805. {
  1806. _PyStructSequence_FiniBuiltin(interp, &FloatInfoType);
  1807. }
  1808. /* Print summary info about the state of the optimized allocator */
  1809. void
  1810. _PyFloat_DebugMallocStats(FILE *out)
  1811. {
  1812. #if PyFloat_MAXFREELIST > 0
  1813. struct _Py_float_state *state = get_float_state();
  1814. _PyDebugAllocatorStats(out,
  1815. "free PyFloatObject",
  1816. state->numfree, sizeof(PyFloatObject));
  1817. #endif
  1818. }
  1819. /*----------------------------------------------------------------------------
  1820. * PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h.
  1821. * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
  1822. * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
  1823. * We use:
  1824. * bits = (unsigned short)f; Note the truncation
  1825. * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
  1826. * bits++;
  1827. * }
  1828. */
  1829. int
  1830. PyFloat_Pack2(double x, char *data, int le)
  1831. {
  1832. unsigned char *p = (unsigned char *)data;
  1833. unsigned char sign;
  1834. int e;
  1835. double f;
  1836. unsigned short bits;
  1837. int incr = 1;
  1838. if (x == 0.0) {
  1839. sign = (copysign(1.0, x) == -1.0);
  1840. e = 0;
  1841. bits = 0;
  1842. }
  1843. else if (Py_IS_INFINITY(x)) {
  1844. sign = (x < 0.0);
  1845. e = 0x1f;
  1846. bits = 0;
  1847. }
  1848. else if (Py_IS_NAN(x)) {
  1849. /* There are 2046 distinct half-precision NaNs (1022 signaling and
  1850. 1024 quiet), but there are only two quiet NaNs that don't arise by
  1851. quieting a signaling NaN; we get those by setting the topmost bit
  1852. of the fraction field and clearing all other fraction bits. We
  1853. choose the one with the appropriate sign. */
  1854. sign = (copysign(1.0, x) == -1.0);
  1855. e = 0x1f;
  1856. bits = 512;
  1857. }
  1858. else {
  1859. sign = (x < 0.0);
  1860. if (sign) {
  1861. x = -x;
  1862. }
  1863. f = frexp(x, &e);
  1864. if (f < 0.5 || f >= 1.0) {
  1865. PyErr_SetString(PyExc_SystemError,
  1866. "frexp() result out of range");
  1867. return -1;
  1868. }
  1869. /* Normalize f to be in the range [1.0, 2.0) */
  1870. f *= 2.0;
  1871. e--;
  1872. if (e >= 16) {
  1873. goto Overflow;
  1874. }
  1875. else if (e < -25) {
  1876. /* |x| < 2**-25. Underflow to zero. */
  1877. f = 0.0;
  1878. e = 0;
  1879. }
  1880. else if (e < -14) {
  1881. /* |x| < 2**-14. Gradual underflow */
  1882. f = ldexp(f, 14 + e);
  1883. e = 0;
  1884. }
  1885. else /* if (!(e == 0 && f == 0.0)) */ {
  1886. e += 15;
  1887. f -= 1.0; /* Get rid of leading 1 */
  1888. }
  1889. f *= 1024.0; /* 2**10 */
  1890. /* Round to even */
  1891. bits = (unsigned short)f; /* Note the truncation */
  1892. assert(bits < 1024);
  1893. assert(e < 31);
  1894. if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
  1895. ++bits;
  1896. if (bits == 1024) {
  1897. /* The carry propagated out of a string of 10 1 bits. */
  1898. bits = 0;
  1899. ++e;
  1900. if (e == 31)
  1901. goto Overflow;
  1902. }
  1903. }
  1904. }
  1905. bits |= (e << 10) | (sign << 15);
  1906. /* Write out result. */
  1907. if (le) {
  1908. p += 1;
  1909. incr = -1;
  1910. }
  1911. /* First byte */
  1912. *p = (unsigned char)((bits >> 8) & 0xFF);
  1913. p += incr;
  1914. /* Second byte */
  1915. *p = (unsigned char)(bits & 0xFF);
  1916. return 0;
  1917. Overflow:
  1918. PyErr_SetString(PyExc_OverflowError,
  1919. "float too large to pack with e format");
  1920. return -1;
  1921. }
  1922. int
  1923. PyFloat_Pack4(double x, char *data, int le)
  1924. {
  1925. unsigned char *p = (unsigned char *)data;
  1926. if (float_format == unknown_format) {
  1927. unsigned char sign;
  1928. int e;
  1929. double f;
  1930. unsigned int fbits;
  1931. int incr = 1;
  1932. if (le) {
  1933. p += 3;
  1934. incr = -1;
  1935. }
  1936. if (x < 0) {
  1937. sign = 1;
  1938. x = -x;
  1939. }
  1940. else
  1941. sign = 0;
  1942. f = frexp(x, &e);
  1943. /* Normalize f to be in the range [1.0, 2.0) */
  1944. if (0.5 <= f && f < 1.0) {
  1945. f *= 2.0;
  1946. e--;
  1947. }
  1948. else if (f == 0.0)
  1949. e = 0;
  1950. else {
  1951. PyErr_SetString(PyExc_SystemError,
  1952. "frexp() result out of range");
  1953. return -1;
  1954. }
  1955. if (e >= 128)
  1956. goto Overflow;
  1957. else if (e < -126) {
  1958. /* Gradual underflow */
  1959. f = ldexp(f, 126 + e);
  1960. e = 0;
  1961. }
  1962. else if (!(e == 0 && f == 0.0)) {
  1963. e += 127;
  1964. f -= 1.0; /* Get rid of leading 1 */
  1965. }
  1966. f *= 8388608.0; /* 2**23 */
  1967. fbits = (unsigned int)(f + 0.5); /* Round */
  1968. assert(fbits <= 8388608);
  1969. if (fbits >> 23) {
  1970. /* The carry propagated out of a string of 23 1 bits. */
  1971. fbits = 0;
  1972. ++e;
  1973. if (e >= 255)
  1974. goto Overflow;
  1975. }
  1976. /* First byte */
  1977. *p = (sign << 7) | (e >> 1);
  1978. p += incr;
  1979. /* Second byte */
  1980. *p = (char) (((e & 1) << 7) | (fbits >> 16));
  1981. p += incr;
  1982. /* Third byte */
  1983. *p = (fbits >> 8) & 0xFF;
  1984. p += incr;
  1985. /* Fourth byte */
  1986. *p = fbits & 0xFF;
  1987. /* Done */
  1988. return 0;
  1989. }
  1990. else {
  1991. float y = (float)x;
  1992. int i, incr = 1;
  1993. if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
  1994. goto Overflow;
  1995. unsigned char s[sizeof(float)];
  1996. memcpy(s, &y, sizeof(float));
  1997. if ((float_format == ieee_little_endian_format && !le)
  1998. || (float_format == ieee_big_endian_format && le)) {
  1999. p += 3;
  2000. incr = -1;
  2001. }
  2002. for (i = 0; i < 4; i++) {
  2003. *p = s[i];
  2004. p += incr;
  2005. }
  2006. return 0;
  2007. }
  2008. Overflow:
  2009. PyErr_SetString(PyExc_OverflowError,
  2010. "float too large to pack with f format");
  2011. return -1;
  2012. }
  2013. int
  2014. PyFloat_Pack8(double x, char *data, int le)
  2015. {
  2016. unsigned char *p = (unsigned char *)data;
  2017. if (double_format == unknown_format) {
  2018. unsigned char sign;
  2019. int e;
  2020. double f;
  2021. unsigned int fhi, flo;
  2022. int incr = 1;
  2023. if (le) {
  2024. p += 7;
  2025. incr = -1;
  2026. }
  2027. if (x < 0) {
  2028. sign = 1;
  2029. x = -x;
  2030. }
  2031. else
  2032. sign = 0;
  2033. f = frexp(x, &e);
  2034. /* Normalize f to be in the range [1.0, 2.0) */
  2035. if (0.5 <= f && f < 1.0) {
  2036. f *= 2.0;
  2037. e--;
  2038. }
  2039. else if (f == 0.0)
  2040. e = 0;
  2041. else {
  2042. PyErr_SetString(PyExc_SystemError,
  2043. "frexp() result out of range");
  2044. return -1;
  2045. }
  2046. if (e >= 1024)
  2047. goto Overflow;
  2048. else if (e < -1022) {
  2049. /* Gradual underflow */
  2050. f = ldexp(f, 1022 + e);
  2051. e = 0;
  2052. }
  2053. else if (!(e == 0 && f == 0.0)) {
  2054. e += 1023;
  2055. f -= 1.0; /* Get rid of leading 1 */
  2056. }
  2057. /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
  2058. f *= 268435456.0; /* 2**28 */
  2059. fhi = (unsigned int)f; /* Truncate */
  2060. assert(fhi < 268435456);
  2061. f -= (double)fhi;
  2062. f *= 16777216.0; /* 2**24 */
  2063. flo = (unsigned int)(f + 0.5); /* Round */
  2064. assert(flo <= 16777216);
  2065. if (flo >> 24) {
  2066. /* The carry propagated out of a string of 24 1 bits. */
  2067. flo = 0;
  2068. ++fhi;
  2069. if (fhi >> 28) {
  2070. /* And it also propagated out of the next 28 bits. */
  2071. fhi = 0;
  2072. ++e;
  2073. if (e >= 2047)
  2074. goto Overflow;
  2075. }
  2076. }
  2077. /* First byte */
  2078. *p = (sign << 7) | (e >> 4);
  2079. p += incr;
  2080. /* Second byte */
  2081. *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
  2082. p += incr;
  2083. /* Third byte */
  2084. *p = (fhi >> 16) & 0xFF;
  2085. p += incr;
  2086. /* Fourth byte */
  2087. *p = (fhi >> 8) & 0xFF;
  2088. p += incr;
  2089. /* Fifth byte */
  2090. *p = fhi & 0xFF;
  2091. p += incr;
  2092. /* Sixth byte */
  2093. *p = (flo >> 16) & 0xFF;
  2094. p += incr;
  2095. /* Seventh byte */
  2096. *p = (flo >> 8) & 0xFF;
  2097. p += incr;
  2098. /* Eighth byte */
  2099. *p = flo & 0xFF;
  2100. /* p += incr; */
  2101. /* Done */
  2102. return 0;
  2103. Overflow:
  2104. PyErr_SetString(PyExc_OverflowError,
  2105. "float too large to pack with d format");
  2106. return -1;
  2107. }
  2108. else {
  2109. const unsigned char *s = (unsigned char*)&x;
  2110. int i, incr = 1;
  2111. if ((double_format == ieee_little_endian_format && !le)
  2112. || (double_format == ieee_big_endian_format && le)) {
  2113. p += 7;
  2114. incr = -1;
  2115. }
  2116. for (i = 0; i < 8; i++) {
  2117. *p = *s++;
  2118. p += incr;
  2119. }
  2120. return 0;
  2121. }
  2122. }
  2123. double
  2124. PyFloat_Unpack2(const char *data, int le)
  2125. {
  2126. unsigned char *p = (unsigned char *)data;
  2127. unsigned char sign;
  2128. int e;
  2129. unsigned int f;
  2130. double x;
  2131. int incr = 1;
  2132. if (le) {
  2133. p += 1;
  2134. incr = -1;
  2135. }
  2136. /* First byte */
  2137. sign = (*p >> 7) & 1;
  2138. e = (*p & 0x7C) >> 2;
  2139. f = (*p & 0x03) << 8;
  2140. p += incr;
  2141. /* Second byte */
  2142. f |= *p;
  2143. if (e == 0x1f) {
  2144. if (f == 0) {
  2145. /* Infinity */
  2146. return sign ? -Py_HUGE_VAL : Py_HUGE_VAL;
  2147. }
  2148. else {
  2149. /* NaN */
  2150. return sign ? -fabs(Py_NAN) : fabs(Py_NAN);
  2151. }
  2152. }
  2153. x = (double)f / 1024.0;
  2154. if (e == 0) {
  2155. e = -14;
  2156. }
  2157. else {
  2158. x += 1.0;
  2159. e -= 15;
  2160. }
  2161. x = ldexp(x, e);
  2162. if (sign)
  2163. x = -x;
  2164. return x;
  2165. }
  2166. double
  2167. PyFloat_Unpack4(const char *data, int le)
  2168. {
  2169. unsigned char *p = (unsigned char *)data;
  2170. if (float_format == unknown_format) {
  2171. unsigned char sign;
  2172. int e;
  2173. unsigned int f;
  2174. double x;
  2175. int incr = 1;
  2176. if (le) {
  2177. p += 3;
  2178. incr = -1;
  2179. }
  2180. /* First byte */
  2181. sign = (*p >> 7) & 1;
  2182. e = (*p & 0x7F) << 1;
  2183. p += incr;
  2184. /* Second byte */
  2185. e |= (*p >> 7) & 1;
  2186. f = (*p & 0x7F) << 16;
  2187. p += incr;
  2188. if (e == 255) {
  2189. PyErr_SetString(
  2190. PyExc_ValueError,
  2191. "can't unpack IEEE 754 special value "
  2192. "on non-IEEE platform");
  2193. return -1;
  2194. }
  2195. /* Third byte */
  2196. f |= *p << 8;
  2197. p += incr;
  2198. /* Fourth byte */
  2199. f |= *p;
  2200. x = (double)f / 8388608.0;
  2201. /* XXX This sadly ignores Inf/NaN issues */
  2202. if (e == 0)
  2203. e = -126;
  2204. else {
  2205. x += 1.0;
  2206. e -= 127;
  2207. }
  2208. x = ldexp(x, e);
  2209. if (sign)
  2210. x = -x;
  2211. return x;
  2212. }
  2213. else {
  2214. float x;
  2215. if ((float_format == ieee_little_endian_format && !le)
  2216. || (float_format == ieee_big_endian_format && le)) {
  2217. char buf[4];
  2218. char *d = &buf[3];
  2219. int i;
  2220. for (i = 0; i < 4; i++) {
  2221. *d-- = *p++;
  2222. }
  2223. memcpy(&x, buf, 4);
  2224. }
  2225. else {
  2226. memcpy(&x, p, 4);
  2227. }
  2228. return x;
  2229. }
  2230. }
  2231. double
  2232. PyFloat_Unpack8(const char *data, int le)
  2233. {
  2234. unsigned char *p = (unsigned char *)data;
  2235. if (double_format == unknown_format) {
  2236. unsigned char sign;
  2237. int e;
  2238. unsigned int fhi, flo;
  2239. double x;
  2240. int incr = 1;
  2241. if (le) {
  2242. p += 7;
  2243. incr = -1;
  2244. }
  2245. /* First byte */
  2246. sign = (*p >> 7) & 1;
  2247. e = (*p & 0x7F) << 4;
  2248. p += incr;
  2249. /* Second byte */
  2250. e |= (*p >> 4) & 0xF;
  2251. fhi = (*p & 0xF) << 24;
  2252. p += incr;
  2253. if (e == 2047) {
  2254. PyErr_SetString(
  2255. PyExc_ValueError,
  2256. "can't unpack IEEE 754 special value "
  2257. "on non-IEEE platform");
  2258. return -1.0;
  2259. }
  2260. /* Third byte */
  2261. fhi |= *p << 16;
  2262. p += incr;
  2263. /* Fourth byte */
  2264. fhi |= *p << 8;
  2265. p += incr;
  2266. /* Fifth byte */
  2267. fhi |= *p;
  2268. p += incr;
  2269. /* Sixth byte */
  2270. flo = *p << 16;
  2271. p += incr;
  2272. /* Seventh byte */
  2273. flo |= *p << 8;
  2274. p += incr;
  2275. /* Eighth byte */
  2276. flo |= *p;
  2277. x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
  2278. x /= 268435456.0; /* 2**28 */
  2279. if (e == 0)
  2280. e = -1022;
  2281. else {
  2282. x += 1.0;
  2283. e -= 1023;
  2284. }
  2285. x = ldexp(x, e);
  2286. if (sign)
  2287. x = -x;
  2288. return x;
  2289. }
  2290. else {
  2291. double x;
  2292. if ((double_format == ieee_little_endian_format && !le)
  2293. || (double_format == ieee_big_endian_format && le)) {
  2294. char buf[8];
  2295. char *d = &buf[7];
  2296. int i;
  2297. for (i = 0; i < 8; i++) {
  2298. *d-- = *p++;
  2299. }
  2300. memcpy(&x, buf, 8);
  2301. }
  2302. else {
  2303. memcpy(&x, p, 8);
  2304. }
  2305. return x;
  2306. }
  2307. }