dtoa.c 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820
  1. /****************************************************************
  2. *
  3. * The author of this software is David M. Gay.
  4. *
  5. * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
  6. *
  7. * Permission to use, copy, modify, and distribute this software for any
  8. * purpose without fee is hereby granted, provided that this entire notice
  9. * is included in all copies of any software which is or includes a copy
  10. * or modification of this software and in all copies of the supporting
  11. * documentation for such software.
  12. *
  13. * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
  14. * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
  15. * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
  16. * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
  17. *
  18. ***************************************************************/
  19. /****************************************************************
  20. * This is dtoa.c by David M. Gay, downloaded from
  21. * http://www.netlib.org/fp/dtoa.c on April 15, 2009 and modified for
  22. * inclusion into the Python core by Mark E. T. Dickinson and Eric V. Smith.
  23. *
  24. * Please remember to check http://www.netlib.org/fp regularly (and especially
  25. * before any Python release) for bugfixes and updates.
  26. *
  27. * The major modifications from Gay's original code are as follows:
  28. *
  29. * 0. The original code has been specialized to Python's needs by removing
  30. * many of the #ifdef'd sections. In particular, code to support VAX and
  31. * IBM floating-point formats, hex NaNs, hex floats, locale-aware
  32. * treatment of the decimal point, and setting of the inexact flag have
  33. * been removed.
  34. *
  35. * 1. We use PyMem_Malloc and PyMem_Free in place of malloc and free.
  36. *
  37. * 2. The public functions strtod, dtoa and freedtoa all now have
  38. * a _Py_dg_ prefix.
  39. *
  40. * 3. Instead of assuming that PyMem_Malloc always succeeds, we thread
  41. * PyMem_Malloc failures through the code. The functions
  42. *
  43. * Balloc, multadd, s2b, i2b, mult, pow5mult, lshift, diff, d2b
  44. *
  45. * of return type *Bigint all return NULL to indicate a malloc failure.
  46. * Similarly, rv_alloc and nrv_alloc (return type char *) return NULL on
  47. * failure. bigcomp now has return type int (it used to be void) and
  48. * returns -1 on failure and 0 otherwise. _Py_dg_dtoa returns NULL
  49. * on failure. _Py_dg_strtod indicates failure due to malloc failure
  50. * by returning -1.0, setting errno=ENOMEM and *se to s00.
  51. *
  52. * 4. The static variable dtoa_result has been removed. Callers of
  53. * _Py_dg_dtoa are expected to call _Py_dg_freedtoa to free
  54. * the memory allocated by _Py_dg_dtoa.
  55. *
  56. * 5. The code has been reformatted to better fit with Python's
  57. * C style guide (PEP 7).
  58. *
  59. * 6. A bug in the memory allocation has been fixed: to avoid FREEing memory
  60. * that hasn't been MALLOC'ed, private_mem should only be used when k <=
  61. * Kmax.
  62. *
  63. * 7. _Py_dg_strtod has been modified so that it doesn't accept strings with
  64. * leading whitespace.
  65. *
  66. * 8. A corner case where _Py_dg_dtoa didn't strip trailing zeros has been
  67. * fixed. (bugs.python.org/issue40780)
  68. *
  69. ***************************************************************/
  70. /* Please send bug reports for the original dtoa.c code to David M. Gay (dmg
  71. * at acm dot org, with " at " changed at "@" and " dot " changed to ".").
  72. * Please report bugs for this modified version using the Python issue tracker
  73. * (http://bugs.python.org). */
  74. /* On a machine with IEEE extended-precision registers, it is
  75. * necessary to specify double-precision (53-bit) rounding precision
  76. * before invoking strtod or dtoa. If the machine uses (the equivalent
  77. * of) Intel 80x87 arithmetic, the call
  78. * _control87(PC_53, MCW_PC);
  79. * does this with many compilers. Whether this or another call is
  80. * appropriate depends on the compiler; for this to work, it may be
  81. * necessary to #include "float.h" or another system-dependent header
  82. * file.
  83. */
  84. /* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
  85. *
  86. * This strtod returns a nearest machine number to the input decimal
  87. * string (or sets errno to ERANGE). With IEEE arithmetic, ties are
  88. * broken by the IEEE round-even rule. Otherwise ties are broken by
  89. * biased rounding (add half and chop).
  90. *
  91. * Inspired loosely by William D. Clinger's paper "How to Read Floating
  92. * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
  93. *
  94. * Modifications:
  95. *
  96. * 1. We only require IEEE, IBM, or VAX double-precision
  97. * arithmetic (not IEEE double-extended).
  98. * 2. We get by with floating-point arithmetic in a case that
  99. * Clinger missed -- when we're computing d * 10^n
  100. * for a small integer d and the integer n is not too
  101. * much larger than 22 (the maximum integer k for which
  102. * we can represent 10^k exactly), we may be able to
  103. * compute (d*10^k) * 10^(e-k) with just one roundoff.
  104. * 3. Rather than a bit-at-a-time adjustment of the binary
  105. * result in the hard case, we use floating-point
  106. * arithmetic to determine the adjustment to within
  107. * one bit; only in really hard cases do we need to
  108. * compute a second residual.
  109. * 4. Because of 3., we don't need a large table of powers of 10
  110. * for ten-to-e (just some small tables, e.g. of 10^k
  111. * for 0 <= k <= 22).
  112. */
  113. /* Linking of Python's #defines to Gay's #defines starts here. */
  114. #include "Python.h"
  115. #include "pycore_dtoa.h" // _PY_SHORT_FLOAT_REPR
  116. #include "pycore_pystate.h" // _PyInterpreterState_GET()
  117. #include <stdlib.h> // exit()
  118. /* if _PY_SHORT_FLOAT_REPR == 0, then don't even try to compile
  119. the following code */
  120. #if _PY_SHORT_FLOAT_REPR == 1
  121. #include "float.h"
  122. #define MALLOC PyMem_Malloc
  123. #define FREE PyMem_Free
  124. /* This code should also work for ARM mixed-endian format on little-endian
  125. machines, where doubles have byte order 45670123 (in increasing address
  126. order, 0 being the least significant byte). */
  127. #ifdef DOUBLE_IS_LITTLE_ENDIAN_IEEE754
  128. # define IEEE_8087
  129. #endif
  130. #if defined(DOUBLE_IS_BIG_ENDIAN_IEEE754) || \
  131. defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754)
  132. # define IEEE_MC68k
  133. #endif
  134. #if defined(IEEE_8087) + defined(IEEE_MC68k) != 1
  135. #error "Exactly one of IEEE_8087 or IEEE_MC68k should be defined."
  136. #endif
  137. /* The code below assumes that the endianness of integers matches the
  138. endianness of the two 32-bit words of a double. Check this. */
  139. #if defined(WORDS_BIGENDIAN) && (defined(DOUBLE_IS_LITTLE_ENDIAN_IEEE754) || \
  140. defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754))
  141. #error "doubles and ints have incompatible endianness"
  142. #endif
  143. #if !defined(WORDS_BIGENDIAN) && defined(DOUBLE_IS_BIG_ENDIAN_IEEE754)
  144. #error "doubles and ints have incompatible endianness"
  145. #endif
  146. // ULong is defined in pycore_dtoa.h.
  147. typedef int32_t Long;
  148. typedef uint64_t ULLong;
  149. #undef DEBUG
  150. #ifdef Py_DEBUG
  151. #define DEBUG
  152. #endif
  153. /* End Python #define linking */
  154. #ifdef DEBUG
  155. #define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
  156. #endif
  157. #ifdef __cplusplus
  158. extern "C" {
  159. #endif
  160. typedef union { double d; ULong L[2]; } U;
  161. #ifdef IEEE_8087
  162. #define word0(x) (x)->L[1]
  163. #define word1(x) (x)->L[0]
  164. #else
  165. #define word0(x) (x)->L[0]
  166. #define word1(x) (x)->L[1]
  167. #endif
  168. #define dval(x) (x)->d
  169. #ifndef STRTOD_DIGLIM
  170. #define STRTOD_DIGLIM 40
  171. #endif
  172. /* maximum permitted exponent value for strtod; exponents larger than
  173. MAX_ABS_EXP in absolute value get truncated to +-MAX_ABS_EXP. MAX_ABS_EXP
  174. should fit into an int. */
  175. #ifndef MAX_ABS_EXP
  176. #define MAX_ABS_EXP 1100000000U
  177. #endif
  178. /* Bound on length of pieces of input strings in _Py_dg_strtod; specifically,
  179. this is used to bound the total number of digits ignoring leading zeros and
  180. the number of digits that follow the decimal point. Ideally, MAX_DIGITS
  181. should satisfy MAX_DIGITS + 400 < MAX_ABS_EXP; that ensures that the
  182. exponent clipping in _Py_dg_strtod can't affect the value of the output. */
  183. #ifndef MAX_DIGITS
  184. #define MAX_DIGITS 1000000000U
  185. #endif
  186. /* Guard against trying to use the above values on unusual platforms with ints
  187. * of width less than 32 bits. */
  188. #if MAX_ABS_EXP > INT_MAX
  189. #error "MAX_ABS_EXP should fit in an int"
  190. #endif
  191. #if MAX_DIGITS > INT_MAX
  192. #error "MAX_DIGITS should fit in an int"
  193. #endif
  194. /* The following definition of Storeinc is appropriate for MIPS processors.
  195. * An alternative that might be better on some machines is
  196. * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
  197. */
  198. #if defined(IEEE_8087)
  199. #define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \
  200. ((unsigned short *)a)[0] = (unsigned short)c, a++)
  201. #else
  202. #define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \
  203. ((unsigned short *)a)[1] = (unsigned short)c, a++)
  204. #endif
  205. /* #define P DBL_MANT_DIG */
  206. /* Ten_pmax = floor(P*log(2)/log(5)) */
  207. /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
  208. /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
  209. /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
  210. #define Exp_shift 20
  211. #define Exp_shift1 20
  212. #define Exp_msk1 0x100000
  213. #define Exp_msk11 0x100000
  214. #define Exp_mask 0x7ff00000
  215. #define P 53
  216. #define Nbits 53
  217. #define Bias 1023
  218. #define Emax 1023
  219. #define Emin (-1022)
  220. #define Etiny (-1074) /* smallest denormal is 2**Etiny */
  221. #define Exp_1 0x3ff00000
  222. #define Exp_11 0x3ff00000
  223. #define Ebits 11
  224. #define Frac_mask 0xfffff
  225. #define Frac_mask1 0xfffff
  226. #define Ten_pmax 22
  227. #define Bletch 0x10
  228. #define Bndry_mask 0xfffff
  229. #define Bndry_mask1 0xfffff
  230. #define Sign_bit 0x80000000
  231. #define Log2P 1
  232. #define Tiny0 0
  233. #define Tiny1 1
  234. #define Quick_max 14
  235. #define Int_max 14
  236. #ifndef Flt_Rounds
  237. #ifdef FLT_ROUNDS
  238. #define Flt_Rounds FLT_ROUNDS
  239. #else
  240. #define Flt_Rounds 1
  241. #endif
  242. #endif /*Flt_Rounds*/
  243. #define Rounding Flt_Rounds
  244. #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
  245. #define Big1 0xffffffff
  246. /* Bits of the representation of positive infinity. */
  247. #define POSINF_WORD0 0x7ff00000
  248. #define POSINF_WORD1 0
  249. /* struct BCinfo is used to pass information from _Py_dg_strtod to bigcomp */
  250. typedef struct BCinfo BCinfo;
  251. struct
  252. BCinfo {
  253. int e0, nd, nd0, scale;
  254. };
  255. #define FFFFFFFF 0xffffffffUL
  256. /* struct Bigint is used to represent arbitrary-precision integers. These
  257. integers are stored in sign-magnitude format, with the magnitude stored as
  258. an array of base 2**32 digits. Bigints are always normalized: if x is a
  259. Bigint then x->wds >= 1, and either x->wds == 1 or x[wds-1] is nonzero.
  260. The Bigint fields are as follows:
  261. - next is a header used by Balloc and Bfree to keep track of lists
  262. of freed Bigints; it's also used for the linked list of
  263. powers of 5 of the form 5**2**i used by pow5mult.
  264. - k indicates which pool this Bigint was allocated from
  265. - maxwds is the maximum number of words space was allocated for
  266. (usually maxwds == 2**k)
  267. - sign is 1 for negative Bigints, 0 for positive. The sign is unused
  268. (ignored on inputs, set to 0 on outputs) in almost all operations
  269. involving Bigints: a notable exception is the diff function, which
  270. ignores signs on inputs but sets the sign of the output correctly.
  271. - wds is the actual number of significant words
  272. - x contains the vector of words (digits) for this Bigint, from least
  273. significant (x[0]) to most significant (x[wds-1]).
  274. */
  275. // struct Bigint is defined in pycore_dtoa.h.
  276. typedef struct Bigint Bigint;
  277. #ifndef Py_USING_MEMORY_DEBUGGER
  278. /* Memory management: memory is allocated from, and returned to, Kmax+1 pools
  279. of memory, where pool k (0 <= k <= Kmax) is for Bigints b with b->maxwds ==
  280. 1 << k. These pools are maintained as linked lists, with freelist[k]
  281. pointing to the head of the list for pool k.
  282. On allocation, if there's no free slot in the appropriate pool, MALLOC is
  283. called to get more memory. This memory is not returned to the system until
  284. Python quits. There's also a private memory pool that's allocated from
  285. in preference to using MALLOC.
  286. For Bigints with more than (1 << Kmax) digits (which implies at least 1233
  287. decimal digits), memory is directly allocated using MALLOC, and freed using
  288. FREE.
  289. XXX: it would be easy to bypass this memory-management system and
  290. translate each call to Balloc into a call to PyMem_Malloc, and each
  291. Bfree to PyMem_Free. Investigate whether this has any significant
  292. performance on impact. */
  293. #define freelist interp->dtoa.freelist
  294. #define private_mem interp->dtoa.preallocated
  295. #define pmem_next interp->dtoa.preallocated_next
  296. /* Allocate space for a Bigint with up to 1<<k digits */
  297. static Bigint *
  298. Balloc(int k)
  299. {
  300. int x;
  301. Bigint *rv;
  302. unsigned int len;
  303. PyInterpreterState *interp = _PyInterpreterState_GET();
  304. if (k <= Bigint_Kmax && (rv = freelist[k]))
  305. freelist[k] = rv->next;
  306. else {
  307. x = 1 << k;
  308. len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
  309. /sizeof(double);
  310. if (k <= Bigint_Kmax &&
  311. pmem_next - private_mem + len <= (Py_ssize_t)Bigint_PREALLOC_SIZE
  312. ) {
  313. rv = (Bigint*)pmem_next;
  314. pmem_next += len;
  315. }
  316. else {
  317. rv = (Bigint*)MALLOC(len*sizeof(double));
  318. if (rv == NULL)
  319. return NULL;
  320. }
  321. rv->k = k;
  322. rv->maxwds = x;
  323. }
  324. rv->sign = rv->wds = 0;
  325. return rv;
  326. }
  327. /* Free a Bigint allocated with Balloc */
  328. static void
  329. Bfree(Bigint *v)
  330. {
  331. if (v) {
  332. if (v->k > Bigint_Kmax)
  333. FREE((void*)v);
  334. else {
  335. PyInterpreterState *interp = _PyInterpreterState_GET();
  336. v->next = freelist[v->k];
  337. freelist[v->k] = v;
  338. }
  339. }
  340. }
  341. #undef pmem_next
  342. #undef private_mem
  343. #undef freelist
  344. #else
  345. /* Alternative versions of Balloc and Bfree that use PyMem_Malloc and
  346. PyMem_Free directly in place of the custom memory allocation scheme above.
  347. These are provided for the benefit of memory debugging tools like
  348. Valgrind. */
  349. /* Allocate space for a Bigint with up to 1<<k digits */
  350. static Bigint *
  351. Balloc(int k)
  352. {
  353. int x;
  354. Bigint *rv;
  355. unsigned int len;
  356. x = 1 << k;
  357. len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
  358. /sizeof(double);
  359. rv = (Bigint*)MALLOC(len*sizeof(double));
  360. if (rv == NULL)
  361. return NULL;
  362. rv->k = k;
  363. rv->maxwds = x;
  364. rv->sign = rv->wds = 0;
  365. return rv;
  366. }
  367. /* Free a Bigint allocated with Balloc */
  368. static void
  369. Bfree(Bigint *v)
  370. {
  371. if (v) {
  372. FREE((void*)v);
  373. }
  374. }
  375. #endif /* Py_USING_MEMORY_DEBUGGER */
  376. #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
  377. y->wds*sizeof(Long) + 2*sizeof(int))
  378. /* Multiply a Bigint b by m and add a. Either modifies b in place and returns
  379. a pointer to the modified b, or Bfrees b and returns a pointer to a copy.
  380. On failure, return NULL. In this case, b will have been already freed. */
  381. static Bigint *
  382. multadd(Bigint *b, int m, int a) /* multiply by m and add a */
  383. {
  384. int i, wds;
  385. ULong *x;
  386. ULLong carry, y;
  387. Bigint *b1;
  388. wds = b->wds;
  389. x = b->x;
  390. i = 0;
  391. carry = a;
  392. do {
  393. y = *x * (ULLong)m + carry;
  394. carry = y >> 32;
  395. *x++ = (ULong)(y & FFFFFFFF);
  396. }
  397. while(++i < wds);
  398. if (carry) {
  399. if (wds >= b->maxwds) {
  400. b1 = Balloc(b->k+1);
  401. if (b1 == NULL){
  402. Bfree(b);
  403. return NULL;
  404. }
  405. Bcopy(b1, b);
  406. Bfree(b);
  407. b = b1;
  408. }
  409. b->x[wds++] = (ULong)carry;
  410. b->wds = wds;
  411. }
  412. return b;
  413. }
  414. /* convert a string s containing nd decimal digits (possibly containing a
  415. decimal separator at position nd0, which is ignored) to a Bigint. This
  416. function carries on where the parsing code in _Py_dg_strtod leaves off: on
  417. entry, y9 contains the result of converting the first 9 digits. Returns
  418. NULL on failure. */
  419. static Bigint *
  420. s2b(const char *s, int nd0, int nd, ULong y9)
  421. {
  422. Bigint *b;
  423. int i, k;
  424. Long x, y;
  425. x = (nd + 8) / 9;
  426. for(k = 0, y = 1; x > y; y <<= 1, k++) ;
  427. b = Balloc(k);
  428. if (b == NULL)
  429. return NULL;
  430. b->x[0] = y9;
  431. b->wds = 1;
  432. if (nd <= 9)
  433. return b;
  434. s += 9;
  435. for (i = 9; i < nd0; i++) {
  436. b = multadd(b, 10, *s++ - '0');
  437. if (b == NULL)
  438. return NULL;
  439. }
  440. s++;
  441. for(; i < nd; i++) {
  442. b = multadd(b, 10, *s++ - '0');
  443. if (b == NULL)
  444. return NULL;
  445. }
  446. return b;
  447. }
  448. /* count leading 0 bits in the 32-bit integer x. */
  449. static int
  450. hi0bits(ULong x)
  451. {
  452. int k = 0;
  453. if (!(x & 0xffff0000)) {
  454. k = 16;
  455. x <<= 16;
  456. }
  457. if (!(x & 0xff000000)) {
  458. k += 8;
  459. x <<= 8;
  460. }
  461. if (!(x & 0xf0000000)) {
  462. k += 4;
  463. x <<= 4;
  464. }
  465. if (!(x & 0xc0000000)) {
  466. k += 2;
  467. x <<= 2;
  468. }
  469. if (!(x & 0x80000000)) {
  470. k++;
  471. if (!(x & 0x40000000))
  472. return 32;
  473. }
  474. return k;
  475. }
  476. /* count trailing 0 bits in the 32-bit integer y, and shift y right by that
  477. number of bits. */
  478. static int
  479. lo0bits(ULong *y)
  480. {
  481. int k;
  482. ULong x = *y;
  483. if (x & 7) {
  484. if (x & 1)
  485. return 0;
  486. if (x & 2) {
  487. *y = x >> 1;
  488. return 1;
  489. }
  490. *y = x >> 2;
  491. return 2;
  492. }
  493. k = 0;
  494. if (!(x & 0xffff)) {
  495. k = 16;
  496. x >>= 16;
  497. }
  498. if (!(x & 0xff)) {
  499. k += 8;
  500. x >>= 8;
  501. }
  502. if (!(x & 0xf)) {
  503. k += 4;
  504. x >>= 4;
  505. }
  506. if (!(x & 0x3)) {
  507. k += 2;
  508. x >>= 2;
  509. }
  510. if (!(x & 1)) {
  511. k++;
  512. x >>= 1;
  513. if (!x)
  514. return 32;
  515. }
  516. *y = x;
  517. return k;
  518. }
  519. /* convert a small nonnegative integer to a Bigint */
  520. static Bigint *
  521. i2b(int i)
  522. {
  523. Bigint *b;
  524. b = Balloc(1);
  525. if (b == NULL)
  526. return NULL;
  527. b->x[0] = i;
  528. b->wds = 1;
  529. return b;
  530. }
  531. /* multiply two Bigints. Returns a new Bigint, or NULL on failure. Ignores
  532. the signs of a and b. */
  533. static Bigint *
  534. mult(Bigint *a, Bigint *b)
  535. {
  536. Bigint *c;
  537. int k, wa, wb, wc;
  538. ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
  539. ULong y;
  540. ULLong carry, z;
  541. if ((!a->x[0] && a->wds == 1) || (!b->x[0] && b->wds == 1)) {
  542. c = Balloc(0);
  543. if (c == NULL)
  544. return NULL;
  545. c->wds = 1;
  546. c->x[0] = 0;
  547. return c;
  548. }
  549. if (a->wds < b->wds) {
  550. c = a;
  551. a = b;
  552. b = c;
  553. }
  554. k = a->k;
  555. wa = a->wds;
  556. wb = b->wds;
  557. wc = wa + wb;
  558. if (wc > a->maxwds)
  559. k++;
  560. c = Balloc(k);
  561. if (c == NULL)
  562. return NULL;
  563. for(x = c->x, xa = x + wc; x < xa; x++)
  564. *x = 0;
  565. xa = a->x;
  566. xae = xa + wa;
  567. xb = b->x;
  568. xbe = xb + wb;
  569. xc0 = c->x;
  570. for(; xb < xbe; xc0++) {
  571. if ((y = *xb++)) {
  572. x = xa;
  573. xc = xc0;
  574. carry = 0;
  575. do {
  576. z = *x++ * (ULLong)y + *xc + carry;
  577. carry = z >> 32;
  578. *xc++ = (ULong)(z & FFFFFFFF);
  579. }
  580. while(x < xae);
  581. *xc = (ULong)carry;
  582. }
  583. }
  584. for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
  585. c->wds = wc;
  586. return c;
  587. }
  588. #ifndef Py_USING_MEMORY_DEBUGGER
  589. /* multiply the Bigint b by 5**k. Returns a pointer to the result, or NULL on
  590. failure; if the returned pointer is distinct from b then the original
  591. Bigint b will have been Bfree'd. Ignores the sign of b. */
  592. static Bigint *
  593. pow5mult(Bigint *b, int k)
  594. {
  595. Bigint *b1, *p5, *p51;
  596. int i;
  597. static const int p05[3] = { 5, 25, 125 };
  598. if ((i = k & 3)) {
  599. b = multadd(b, p05[i-1], 0);
  600. if (b == NULL)
  601. return NULL;
  602. }
  603. if (!(k >>= 2))
  604. return b;
  605. PyInterpreterState *interp = _PyInterpreterState_GET();
  606. p5 = interp->dtoa.p5s;
  607. if (!p5) {
  608. /* first time */
  609. p5 = i2b(625);
  610. if (p5 == NULL) {
  611. Bfree(b);
  612. return NULL;
  613. }
  614. interp->dtoa.p5s = p5;
  615. p5->next = 0;
  616. }
  617. for(;;) {
  618. if (k & 1) {
  619. b1 = mult(b, p5);
  620. Bfree(b);
  621. b = b1;
  622. if (b == NULL)
  623. return NULL;
  624. }
  625. if (!(k >>= 1))
  626. break;
  627. p51 = p5->next;
  628. if (!p51) {
  629. p51 = mult(p5,p5);
  630. if (p51 == NULL) {
  631. Bfree(b);
  632. return NULL;
  633. }
  634. p51->next = 0;
  635. p5->next = p51;
  636. }
  637. p5 = p51;
  638. }
  639. return b;
  640. }
  641. #else
  642. /* Version of pow5mult that doesn't cache powers of 5. Provided for
  643. the benefit of memory debugging tools like Valgrind. */
  644. static Bigint *
  645. pow5mult(Bigint *b, int k)
  646. {
  647. Bigint *b1, *p5, *p51;
  648. int i;
  649. static const int p05[3] = { 5, 25, 125 };
  650. if ((i = k & 3)) {
  651. b = multadd(b, p05[i-1], 0);
  652. if (b == NULL)
  653. return NULL;
  654. }
  655. if (!(k >>= 2))
  656. return b;
  657. p5 = i2b(625);
  658. if (p5 == NULL) {
  659. Bfree(b);
  660. return NULL;
  661. }
  662. for(;;) {
  663. if (k & 1) {
  664. b1 = mult(b, p5);
  665. Bfree(b);
  666. b = b1;
  667. if (b == NULL) {
  668. Bfree(p5);
  669. return NULL;
  670. }
  671. }
  672. if (!(k >>= 1))
  673. break;
  674. p51 = mult(p5, p5);
  675. Bfree(p5);
  676. p5 = p51;
  677. if (p5 == NULL) {
  678. Bfree(b);
  679. return NULL;
  680. }
  681. }
  682. Bfree(p5);
  683. return b;
  684. }
  685. #endif /* Py_USING_MEMORY_DEBUGGER */
  686. /* shift a Bigint b left by k bits. Return a pointer to the shifted result,
  687. or NULL on failure. If the returned pointer is distinct from b then the
  688. original b will have been Bfree'd. Ignores the sign of b. */
  689. static Bigint *
  690. lshift(Bigint *b, int k)
  691. {
  692. int i, k1, n, n1;
  693. Bigint *b1;
  694. ULong *x, *x1, *xe, z;
  695. if (!k || (!b->x[0] && b->wds == 1))
  696. return b;
  697. n = k >> 5;
  698. k1 = b->k;
  699. n1 = n + b->wds + 1;
  700. for(i = b->maxwds; n1 > i; i <<= 1)
  701. k1++;
  702. b1 = Balloc(k1);
  703. if (b1 == NULL) {
  704. Bfree(b);
  705. return NULL;
  706. }
  707. x1 = b1->x;
  708. for(i = 0; i < n; i++)
  709. *x1++ = 0;
  710. x = b->x;
  711. xe = x + b->wds;
  712. if (k &= 0x1f) {
  713. k1 = 32 - k;
  714. z = 0;
  715. do {
  716. *x1++ = *x << k | z;
  717. z = *x++ >> k1;
  718. }
  719. while(x < xe);
  720. if ((*x1 = z))
  721. ++n1;
  722. }
  723. else do
  724. *x1++ = *x++;
  725. while(x < xe);
  726. b1->wds = n1 - 1;
  727. Bfree(b);
  728. return b1;
  729. }
  730. /* Do a three-way compare of a and b, returning -1 if a < b, 0 if a == b and
  731. 1 if a > b. Ignores signs of a and b. */
  732. static int
  733. cmp(Bigint *a, Bigint *b)
  734. {
  735. ULong *xa, *xa0, *xb, *xb0;
  736. int i, j;
  737. i = a->wds;
  738. j = b->wds;
  739. #ifdef DEBUG
  740. if (i > 1 && !a->x[i-1])
  741. Bug("cmp called with a->x[a->wds-1] == 0");
  742. if (j > 1 && !b->x[j-1])
  743. Bug("cmp called with b->x[b->wds-1] == 0");
  744. #endif
  745. if (i -= j)
  746. return i;
  747. xa0 = a->x;
  748. xa = xa0 + j;
  749. xb0 = b->x;
  750. xb = xb0 + j;
  751. for(;;) {
  752. if (*--xa != *--xb)
  753. return *xa < *xb ? -1 : 1;
  754. if (xa <= xa0)
  755. break;
  756. }
  757. return 0;
  758. }
  759. /* Take the difference of Bigints a and b, returning a new Bigint. Returns
  760. NULL on failure. The signs of a and b are ignored, but the sign of the
  761. result is set appropriately. */
  762. static Bigint *
  763. diff(Bigint *a, Bigint *b)
  764. {
  765. Bigint *c;
  766. int i, wa, wb;
  767. ULong *xa, *xae, *xb, *xbe, *xc;
  768. ULLong borrow, y;
  769. i = cmp(a,b);
  770. if (!i) {
  771. c = Balloc(0);
  772. if (c == NULL)
  773. return NULL;
  774. c->wds = 1;
  775. c->x[0] = 0;
  776. return c;
  777. }
  778. if (i < 0) {
  779. c = a;
  780. a = b;
  781. b = c;
  782. i = 1;
  783. }
  784. else
  785. i = 0;
  786. c = Balloc(a->k);
  787. if (c == NULL)
  788. return NULL;
  789. c->sign = i;
  790. wa = a->wds;
  791. xa = a->x;
  792. xae = xa + wa;
  793. wb = b->wds;
  794. xb = b->x;
  795. xbe = xb + wb;
  796. xc = c->x;
  797. borrow = 0;
  798. do {
  799. y = (ULLong)*xa++ - *xb++ - borrow;
  800. borrow = y >> 32 & (ULong)1;
  801. *xc++ = (ULong)(y & FFFFFFFF);
  802. }
  803. while(xb < xbe);
  804. while(xa < xae) {
  805. y = *xa++ - borrow;
  806. borrow = y >> 32 & (ULong)1;
  807. *xc++ = (ULong)(y & FFFFFFFF);
  808. }
  809. while(!*--xc)
  810. wa--;
  811. c->wds = wa;
  812. return c;
  813. }
  814. /* Given a positive normal double x, return the difference between x and the
  815. next double up. Doesn't give correct results for subnormals. */
  816. static double
  817. ulp(U *x)
  818. {
  819. Long L;
  820. U u;
  821. L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
  822. word0(&u) = L;
  823. word1(&u) = 0;
  824. return dval(&u);
  825. }
  826. /* Convert a Bigint to a double plus an exponent */
  827. static double
  828. b2d(Bigint *a, int *e)
  829. {
  830. ULong *xa, *xa0, w, y, z;
  831. int k;
  832. U d;
  833. xa0 = a->x;
  834. xa = xa0 + a->wds;
  835. y = *--xa;
  836. #ifdef DEBUG
  837. if (!y) Bug("zero y in b2d");
  838. #endif
  839. k = hi0bits(y);
  840. *e = 32 - k;
  841. if (k < Ebits) {
  842. word0(&d) = Exp_1 | y >> (Ebits - k);
  843. w = xa > xa0 ? *--xa : 0;
  844. word1(&d) = y << ((32-Ebits) + k) | w >> (Ebits - k);
  845. goto ret_d;
  846. }
  847. z = xa > xa0 ? *--xa : 0;
  848. if (k -= Ebits) {
  849. word0(&d) = Exp_1 | y << k | z >> (32 - k);
  850. y = xa > xa0 ? *--xa : 0;
  851. word1(&d) = z << k | y >> (32 - k);
  852. }
  853. else {
  854. word0(&d) = Exp_1 | y;
  855. word1(&d) = z;
  856. }
  857. ret_d:
  858. return dval(&d);
  859. }
  860. /* Convert a scaled double to a Bigint plus an exponent. Similar to d2b,
  861. except that it accepts the scale parameter used in _Py_dg_strtod (which
  862. should be either 0 or 2*P), and the normalization for the return value is
  863. different (see below). On input, d should be finite and nonnegative, and d
  864. / 2**scale should be exactly representable as an IEEE 754 double.
  865. Returns a Bigint b and an integer e such that
  866. dval(d) / 2**scale = b * 2**e.
  867. Unlike d2b, b is not necessarily odd: b and e are normalized so
  868. that either 2**(P-1) <= b < 2**P and e >= Etiny, or b < 2**P
  869. and e == Etiny. This applies equally to an input of 0.0: in that
  870. case the return values are b = 0 and e = Etiny.
  871. The above normalization ensures that for all possible inputs d,
  872. 2**e gives ulp(d/2**scale).
  873. Returns NULL on failure.
  874. */
  875. static Bigint *
  876. sd2b(U *d, int scale, int *e)
  877. {
  878. Bigint *b;
  879. b = Balloc(1);
  880. if (b == NULL)
  881. return NULL;
  882. /* First construct b and e assuming that scale == 0. */
  883. b->wds = 2;
  884. b->x[0] = word1(d);
  885. b->x[1] = word0(d) & Frac_mask;
  886. *e = Etiny - 1 + (int)((word0(d) & Exp_mask) >> Exp_shift);
  887. if (*e < Etiny)
  888. *e = Etiny;
  889. else
  890. b->x[1] |= Exp_msk1;
  891. /* Now adjust for scale, provided that b != 0. */
  892. if (scale && (b->x[0] || b->x[1])) {
  893. *e -= scale;
  894. if (*e < Etiny) {
  895. scale = Etiny - *e;
  896. *e = Etiny;
  897. /* We can't shift more than P-1 bits without shifting out a 1. */
  898. assert(0 < scale && scale <= P - 1);
  899. if (scale >= 32) {
  900. /* The bits shifted out should all be zero. */
  901. assert(b->x[0] == 0);
  902. b->x[0] = b->x[1];
  903. b->x[1] = 0;
  904. scale -= 32;
  905. }
  906. if (scale) {
  907. /* The bits shifted out should all be zero. */
  908. assert(b->x[0] << (32 - scale) == 0);
  909. b->x[0] = (b->x[0] >> scale) | (b->x[1] << (32 - scale));
  910. b->x[1] >>= scale;
  911. }
  912. }
  913. }
  914. /* Ensure b is normalized. */
  915. if (!b->x[1])
  916. b->wds = 1;
  917. return b;
  918. }
  919. /* Convert a double to a Bigint plus an exponent. Return NULL on failure.
  920. Given a finite nonzero double d, return an odd Bigint b and exponent *e
  921. such that fabs(d) = b * 2**e. On return, *bbits gives the number of
  922. significant bits of b; that is, 2**(*bbits-1) <= b < 2**(*bbits).
  923. If d is zero, then b == 0, *e == -1010, *bbits = 0.
  924. */
  925. static Bigint *
  926. d2b(U *d, int *e, int *bits)
  927. {
  928. Bigint *b;
  929. int de, k;
  930. ULong *x, y, z;
  931. int i;
  932. b = Balloc(1);
  933. if (b == NULL)
  934. return NULL;
  935. x = b->x;
  936. z = word0(d) & Frac_mask;
  937. word0(d) &= 0x7fffffff; /* clear sign bit, which we ignore */
  938. if ((de = (int)(word0(d) >> Exp_shift)))
  939. z |= Exp_msk1;
  940. if ((y = word1(d))) {
  941. if ((k = lo0bits(&y))) {
  942. x[0] = y | z << (32 - k);
  943. z >>= k;
  944. }
  945. else
  946. x[0] = y;
  947. i =
  948. b->wds = (x[1] = z) ? 2 : 1;
  949. }
  950. else {
  951. k = lo0bits(&z);
  952. x[0] = z;
  953. i =
  954. b->wds = 1;
  955. k += 32;
  956. }
  957. if (de) {
  958. *e = de - Bias - (P-1) + k;
  959. *bits = P - k;
  960. }
  961. else {
  962. *e = de - Bias - (P-1) + 1 + k;
  963. *bits = 32*i - hi0bits(x[i-1]);
  964. }
  965. return b;
  966. }
  967. /* Compute the ratio of two Bigints, as a double. The result may have an
  968. error of up to 2.5 ulps. */
  969. static double
  970. ratio(Bigint *a, Bigint *b)
  971. {
  972. U da, db;
  973. int k, ka, kb;
  974. dval(&da) = b2d(a, &ka);
  975. dval(&db) = b2d(b, &kb);
  976. k = ka - kb + 32*(a->wds - b->wds);
  977. if (k > 0)
  978. word0(&da) += k*Exp_msk1;
  979. else {
  980. k = -k;
  981. word0(&db) += k*Exp_msk1;
  982. }
  983. return dval(&da) / dval(&db);
  984. }
  985. static const double
  986. tens[] = {
  987. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  988. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  989. 1e20, 1e21, 1e22
  990. };
  991. static const double
  992. bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
  993. static const double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
  994. 9007199254740992.*9007199254740992.e-256
  995. /* = 2^106 * 1e-256 */
  996. };
  997. /* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
  998. /* flag unnecessarily. It leads to a song and dance at the end of strtod. */
  999. #define Scale_Bit 0x10
  1000. #define n_bigtens 5
  1001. #define ULbits 32
  1002. #define kshift 5
  1003. #define kmask 31
  1004. static int
  1005. dshift(Bigint *b, int p2)
  1006. {
  1007. int rv = hi0bits(b->x[b->wds-1]) - 4;
  1008. if (p2 > 0)
  1009. rv -= p2;
  1010. return rv & kmask;
  1011. }
  1012. /* special case of Bigint division. The quotient is always in the range 0 <=
  1013. quotient < 10, and on entry the divisor S is normalized so that its top 4
  1014. bits (28--31) are zero and bit 27 is set. */
  1015. static int
  1016. quorem(Bigint *b, Bigint *S)
  1017. {
  1018. int n;
  1019. ULong *bx, *bxe, q, *sx, *sxe;
  1020. ULLong borrow, carry, y, ys;
  1021. n = S->wds;
  1022. #ifdef DEBUG
  1023. /*debug*/ if (b->wds > n)
  1024. /*debug*/ Bug("oversize b in quorem");
  1025. #endif
  1026. if (b->wds < n)
  1027. return 0;
  1028. sx = S->x;
  1029. sxe = sx + --n;
  1030. bx = b->x;
  1031. bxe = bx + n;
  1032. q = *bxe / (*sxe + 1); /* ensure q <= true quotient */
  1033. #ifdef DEBUG
  1034. /*debug*/ if (q > 9)
  1035. /*debug*/ Bug("oversized quotient in quorem");
  1036. #endif
  1037. if (q) {
  1038. borrow = 0;
  1039. carry = 0;
  1040. do {
  1041. ys = *sx++ * (ULLong)q + carry;
  1042. carry = ys >> 32;
  1043. y = *bx - (ys & FFFFFFFF) - borrow;
  1044. borrow = y >> 32 & (ULong)1;
  1045. *bx++ = (ULong)(y & FFFFFFFF);
  1046. }
  1047. while(sx <= sxe);
  1048. if (!*bxe) {
  1049. bx = b->x;
  1050. while(--bxe > bx && !*bxe)
  1051. --n;
  1052. b->wds = n;
  1053. }
  1054. }
  1055. if (cmp(b, S) >= 0) {
  1056. q++;
  1057. borrow = 0;
  1058. carry = 0;
  1059. bx = b->x;
  1060. sx = S->x;
  1061. do {
  1062. ys = *sx++ + carry;
  1063. carry = ys >> 32;
  1064. y = *bx - (ys & FFFFFFFF) - borrow;
  1065. borrow = y >> 32 & (ULong)1;
  1066. *bx++ = (ULong)(y & FFFFFFFF);
  1067. }
  1068. while(sx <= sxe);
  1069. bx = b->x;
  1070. bxe = bx + n;
  1071. if (!*bxe) {
  1072. while(--bxe > bx && !*bxe)
  1073. --n;
  1074. b->wds = n;
  1075. }
  1076. }
  1077. return q;
  1078. }
  1079. /* sulp(x) is a version of ulp(x) that takes bc.scale into account.
  1080. Assuming that x is finite and nonnegative (positive zero is fine
  1081. here) and x / 2^bc.scale is exactly representable as a double,
  1082. sulp(x) is equivalent to 2^bc.scale * ulp(x / 2^bc.scale). */
  1083. static double
  1084. sulp(U *x, BCinfo *bc)
  1085. {
  1086. U u;
  1087. if (bc->scale && 2*P + 1 > (int)((word0(x) & Exp_mask) >> Exp_shift)) {
  1088. /* rv/2^bc->scale is subnormal */
  1089. word0(&u) = (P+2)*Exp_msk1;
  1090. word1(&u) = 0;
  1091. return u.d;
  1092. }
  1093. else {
  1094. assert(word0(x) || word1(x)); /* x != 0.0 */
  1095. return ulp(x);
  1096. }
  1097. }
  1098. /* The bigcomp function handles some hard cases for strtod, for inputs
  1099. with more than STRTOD_DIGLIM digits. It's called once an initial
  1100. estimate for the double corresponding to the input string has
  1101. already been obtained by the code in _Py_dg_strtod.
  1102. The bigcomp function is only called after _Py_dg_strtod has found a
  1103. double value rv such that either rv or rv + 1ulp represents the
  1104. correctly rounded value corresponding to the original string. It
  1105. determines which of these two values is the correct one by
  1106. computing the decimal digits of rv + 0.5ulp and comparing them with
  1107. the corresponding digits of s0.
  1108. In the following, write dv for the absolute value of the number represented
  1109. by the input string.
  1110. Inputs:
  1111. s0 points to the first significant digit of the input string.
  1112. rv is a (possibly scaled) estimate for the closest double value to the
  1113. value represented by the original input to _Py_dg_strtod. If
  1114. bc->scale is nonzero, then rv/2^(bc->scale) is the approximation to
  1115. the input value.
  1116. bc is a struct containing information gathered during the parsing and
  1117. estimation steps of _Py_dg_strtod. Description of fields follows:
  1118. bc->e0 gives the exponent of the input value, such that dv = (integer
  1119. given by the bd->nd digits of s0) * 10**e0
  1120. bc->nd gives the total number of significant digits of s0. It will
  1121. be at least 1.
  1122. bc->nd0 gives the number of significant digits of s0 before the
  1123. decimal separator. If there's no decimal separator, bc->nd0 ==
  1124. bc->nd.
  1125. bc->scale is the value used to scale rv to avoid doing arithmetic with
  1126. subnormal values. It's either 0 or 2*P (=106).
  1127. Outputs:
  1128. On successful exit, rv/2^(bc->scale) is the closest double to dv.
  1129. Returns 0 on success, -1 on failure (e.g., due to a failed malloc call). */
  1130. static int
  1131. bigcomp(U *rv, const char *s0, BCinfo *bc)
  1132. {
  1133. Bigint *b, *d;
  1134. int b2, d2, dd, i, nd, nd0, odd, p2, p5;
  1135. nd = bc->nd;
  1136. nd0 = bc->nd0;
  1137. p5 = nd + bc->e0;
  1138. b = sd2b(rv, bc->scale, &p2);
  1139. if (b == NULL)
  1140. return -1;
  1141. /* record whether the lsb of rv/2^(bc->scale) is odd: in the exact halfway
  1142. case, this is used for round to even. */
  1143. odd = b->x[0] & 1;
  1144. /* left shift b by 1 bit and or a 1 into the least significant bit;
  1145. this gives us b * 2**p2 = rv/2^(bc->scale) + 0.5 ulp. */
  1146. b = lshift(b, 1);
  1147. if (b == NULL)
  1148. return -1;
  1149. b->x[0] |= 1;
  1150. p2--;
  1151. p2 -= p5;
  1152. d = i2b(1);
  1153. if (d == NULL) {
  1154. Bfree(b);
  1155. return -1;
  1156. }
  1157. /* Arrange for convenient computation of quotients:
  1158. * shift left if necessary so divisor has 4 leading 0 bits.
  1159. */
  1160. if (p5 > 0) {
  1161. d = pow5mult(d, p5);
  1162. if (d == NULL) {
  1163. Bfree(b);
  1164. return -1;
  1165. }
  1166. }
  1167. else if (p5 < 0) {
  1168. b = pow5mult(b, -p5);
  1169. if (b == NULL) {
  1170. Bfree(d);
  1171. return -1;
  1172. }
  1173. }
  1174. if (p2 > 0) {
  1175. b2 = p2;
  1176. d2 = 0;
  1177. }
  1178. else {
  1179. b2 = 0;
  1180. d2 = -p2;
  1181. }
  1182. i = dshift(d, d2);
  1183. if ((b2 += i) > 0) {
  1184. b = lshift(b, b2);
  1185. if (b == NULL) {
  1186. Bfree(d);
  1187. return -1;
  1188. }
  1189. }
  1190. if ((d2 += i) > 0) {
  1191. d = lshift(d, d2);
  1192. if (d == NULL) {
  1193. Bfree(b);
  1194. return -1;
  1195. }
  1196. }
  1197. /* Compare s0 with b/d: set dd to -1, 0, or 1 according as s0 < b/d, s0 ==
  1198. * b/d, or s0 > b/d. Here the digits of s0 are thought of as representing
  1199. * a number in the range [0.1, 1). */
  1200. if (cmp(b, d) >= 0)
  1201. /* b/d >= 1 */
  1202. dd = -1;
  1203. else {
  1204. i = 0;
  1205. for(;;) {
  1206. b = multadd(b, 10, 0);
  1207. if (b == NULL) {
  1208. Bfree(d);
  1209. return -1;
  1210. }
  1211. dd = s0[i < nd0 ? i : i+1] - '0' - quorem(b, d);
  1212. i++;
  1213. if (dd)
  1214. break;
  1215. if (!b->x[0] && b->wds == 1) {
  1216. /* b/d == 0 */
  1217. dd = i < nd;
  1218. break;
  1219. }
  1220. if (!(i < nd)) {
  1221. /* b/d != 0, but digits of s0 exhausted */
  1222. dd = -1;
  1223. break;
  1224. }
  1225. }
  1226. }
  1227. Bfree(b);
  1228. Bfree(d);
  1229. if (dd > 0 || (dd == 0 && odd))
  1230. dval(rv) += sulp(rv, bc);
  1231. return 0;
  1232. }
  1233. double
  1234. _Py_dg_strtod(const char *s00, char **se)
  1235. {
  1236. int bb2, bb5, bbe, bd2, bd5, bs2, c, dsign, e, e1, error;
  1237. int esign, i, j, k, lz, nd, nd0, odd, sign;
  1238. const char *s, *s0, *s1;
  1239. double aadj, aadj1;
  1240. U aadj2, adj, rv, rv0;
  1241. ULong y, z, abs_exp;
  1242. Long L;
  1243. BCinfo bc;
  1244. Bigint *bb = NULL, *bd = NULL, *bd0 = NULL, *bs = NULL, *delta = NULL;
  1245. size_t ndigits, fraclen;
  1246. double result;
  1247. dval(&rv) = 0.;
  1248. /* Start parsing. */
  1249. c = *(s = s00);
  1250. /* Parse optional sign, if present. */
  1251. sign = 0;
  1252. switch (c) {
  1253. case '-':
  1254. sign = 1;
  1255. /* fall through */
  1256. case '+':
  1257. c = *++s;
  1258. }
  1259. /* Skip leading zeros: lz is true iff there were leading zeros. */
  1260. s1 = s;
  1261. while (c == '0')
  1262. c = *++s;
  1263. lz = s != s1;
  1264. /* Point s0 at the first nonzero digit (if any). fraclen will be the
  1265. number of digits between the decimal point and the end of the
  1266. digit string. ndigits will be the total number of digits ignoring
  1267. leading zeros. */
  1268. s0 = s1 = s;
  1269. while ('0' <= c && c <= '9')
  1270. c = *++s;
  1271. ndigits = s - s1;
  1272. fraclen = 0;
  1273. /* Parse decimal point and following digits. */
  1274. if (c == '.') {
  1275. c = *++s;
  1276. if (!ndigits) {
  1277. s1 = s;
  1278. while (c == '0')
  1279. c = *++s;
  1280. lz = lz || s != s1;
  1281. fraclen += (s - s1);
  1282. s0 = s;
  1283. }
  1284. s1 = s;
  1285. while ('0' <= c && c <= '9')
  1286. c = *++s;
  1287. ndigits += s - s1;
  1288. fraclen += s - s1;
  1289. }
  1290. /* Now lz is true if and only if there were leading zero digits, and
  1291. ndigits gives the total number of digits ignoring leading zeros. A
  1292. valid input must have at least one digit. */
  1293. if (!ndigits && !lz) {
  1294. if (se)
  1295. *se = (char *)s00;
  1296. goto parse_error;
  1297. }
  1298. /* Range check ndigits and fraclen to make sure that they, and values
  1299. computed with them, can safely fit in an int. */
  1300. if (ndigits > MAX_DIGITS || fraclen > MAX_DIGITS) {
  1301. if (se)
  1302. *se = (char *)s00;
  1303. goto parse_error;
  1304. }
  1305. nd = (int)ndigits;
  1306. nd0 = (int)ndigits - (int)fraclen;
  1307. /* Parse exponent. */
  1308. e = 0;
  1309. if (c == 'e' || c == 'E') {
  1310. s00 = s;
  1311. c = *++s;
  1312. /* Exponent sign. */
  1313. esign = 0;
  1314. switch (c) {
  1315. case '-':
  1316. esign = 1;
  1317. /* fall through */
  1318. case '+':
  1319. c = *++s;
  1320. }
  1321. /* Skip zeros. lz is true iff there are leading zeros. */
  1322. s1 = s;
  1323. while (c == '0')
  1324. c = *++s;
  1325. lz = s != s1;
  1326. /* Get absolute value of the exponent. */
  1327. s1 = s;
  1328. abs_exp = 0;
  1329. while ('0' <= c && c <= '9') {
  1330. abs_exp = 10*abs_exp + (c - '0');
  1331. c = *++s;
  1332. }
  1333. /* abs_exp will be correct modulo 2**32. But 10**9 < 2**32, so if
  1334. there are at most 9 significant exponent digits then overflow is
  1335. impossible. */
  1336. if (s - s1 > 9 || abs_exp > MAX_ABS_EXP)
  1337. e = (int)MAX_ABS_EXP;
  1338. else
  1339. e = (int)abs_exp;
  1340. if (esign)
  1341. e = -e;
  1342. /* A valid exponent must have at least one digit. */
  1343. if (s == s1 && !lz)
  1344. s = s00;
  1345. }
  1346. /* Adjust exponent to take into account position of the point. */
  1347. e -= nd - nd0;
  1348. if (nd0 <= 0)
  1349. nd0 = nd;
  1350. /* Finished parsing. Set se to indicate how far we parsed */
  1351. if (se)
  1352. *se = (char *)s;
  1353. /* If all digits were zero, exit with return value +-0.0. Otherwise,
  1354. strip trailing zeros: scan back until we hit a nonzero digit. */
  1355. if (!nd)
  1356. goto ret;
  1357. for (i = nd; i > 0; ) {
  1358. --i;
  1359. if (s0[i < nd0 ? i : i+1] != '0') {
  1360. ++i;
  1361. break;
  1362. }
  1363. }
  1364. e += nd - i;
  1365. nd = i;
  1366. if (nd0 > nd)
  1367. nd0 = nd;
  1368. /* Summary of parsing results. After parsing, and dealing with zero
  1369. * inputs, we have values s0, nd0, nd, e, sign, where:
  1370. *
  1371. * - s0 points to the first significant digit of the input string
  1372. *
  1373. * - nd is the total number of significant digits (here, and
  1374. * below, 'significant digits' means the set of digits of the
  1375. * significand of the input that remain after ignoring leading
  1376. * and trailing zeros).
  1377. *
  1378. * - nd0 indicates the position of the decimal point, if present; it
  1379. * satisfies 1 <= nd0 <= nd. The nd significant digits are in
  1380. * s0[0:nd0] and s0[nd0+1:nd+1] using the usual Python half-open slice
  1381. * notation. (If nd0 < nd, then s0[nd0] contains a '.' character; if
  1382. * nd0 == nd, then s0[nd0] could be any non-digit character.)
  1383. *
  1384. * - e is the adjusted exponent: the absolute value of the number
  1385. * represented by the original input string is n * 10**e, where
  1386. * n is the integer represented by the concatenation of
  1387. * s0[0:nd0] and s0[nd0+1:nd+1]
  1388. *
  1389. * - sign gives the sign of the input: 1 for negative, 0 for positive
  1390. *
  1391. * - the first and last significant digits are nonzero
  1392. */
  1393. /* put first DBL_DIG+1 digits into integer y and z.
  1394. *
  1395. * - y contains the value represented by the first min(9, nd)
  1396. * significant digits
  1397. *
  1398. * - if nd > 9, z contains the value represented by significant digits
  1399. * with indices in [9, min(16, nd)). So y * 10**(min(16, nd) - 9) + z
  1400. * gives the value represented by the first min(16, nd) sig. digits.
  1401. */
  1402. bc.e0 = e1 = e;
  1403. y = z = 0;
  1404. for (i = 0; i < nd; i++) {
  1405. if (i < 9)
  1406. y = 10*y + s0[i < nd0 ? i : i+1] - '0';
  1407. else if (i < DBL_DIG+1)
  1408. z = 10*z + s0[i < nd0 ? i : i+1] - '0';
  1409. else
  1410. break;
  1411. }
  1412. k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
  1413. dval(&rv) = y;
  1414. if (k > 9) {
  1415. dval(&rv) = tens[k - 9] * dval(&rv) + z;
  1416. }
  1417. if (nd <= DBL_DIG
  1418. && Flt_Rounds == 1
  1419. ) {
  1420. if (!e)
  1421. goto ret;
  1422. if (e > 0) {
  1423. if (e <= Ten_pmax) {
  1424. dval(&rv) *= tens[e];
  1425. goto ret;
  1426. }
  1427. i = DBL_DIG - nd;
  1428. if (e <= Ten_pmax + i) {
  1429. /* A fancier test would sometimes let us do
  1430. * this for larger i values.
  1431. */
  1432. e -= i;
  1433. dval(&rv) *= tens[i];
  1434. dval(&rv) *= tens[e];
  1435. goto ret;
  1436. }
  1437. }
  1438. else if (e >= -Ten_pmax) {
  1439. dval(&rv) /= tens[-e];
  1440. goto ret;
  1441. }
  1442. }
  1443. e1 += nd - k;
  1444. bc.scale = 0;
  1445. /* Get starting approximation = rv * 10**e1 */
  1446. if (e1 > 0) {
  1447. if ((i = e1 & 15))
  1448. dval(&rv) *= tens[i];
  1449. if (e1 &= ~15) {
  1450. if (e1 > DBL_MAX_10_EXP)
  1451. goto ovfl;
  1452. e1 >>= 4;
  1453. for(j = 0; e1 > 1; j++, e1 >>= 1)
  1454. if (e1 & 1)
  1455. dval(&rv) *= bigtens[j];
  1456. /* The last multiplication could overflow. */
  1457. word0(&rv) -= P*Exp_msk1;
  1458. dval(&rv) *= bigtens[j];
  1459. if ((z = word0(&rv) & Exp_mask)
  1460. > Exp_msk1*(DBL_MAX_EXP+Bias-P))
  1461. goto ovfl;
  1462. if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
  1463. /* set to largest number */
  1464. /* (Can't trust DBL_MAX) */
  1465. word0(&rv) = Big0;
  1466. word1(&rv) = Big1;
  1467. }
  1468. else
  1469. word0(&rv) += P*Exp_msk1;
  1470. }
  1471. }
  1472. else if (e1 < 0) {
  1473. /* The input decimal value lies in [10**e1, 10**(e1+16)).
  1474. If e1 <= -512, underflow immediately.
  1475. If e1 <= -256, set bc.scale to 2*P.
  1476. So for input value < 1e-256, bc.scale is always set;
  1477. for input value >= 1e-240, bc.scale is never set.
  1478. For input values in [1e-256, 1e-240), bc.scale may or may
  1479. not be set. */
  1480. e1 = -e1;
  1481. if ((i = e1 & 15))
  1482. dval(&rv) /= tens[i];
  1483. if (e1 >>= 4) {
  1484. if (e1 >= 1 << n_bigtens)
  1485. goto undfl;
  1486. if (e1 & Scale_Bit)
  1487. bc.scale = 2*P;
  1488. for(j = 0; e1 > 0; j++, e1 >>= 1)
  1489. if (e1 & 1)
  1490. dval(&rv) *= tinytens[j];
  1491. if (bc.scale && (j = 2*P + 1 - ((word0(&rv) & Exp_mask)
  1492. >> Exp_shift)) > 0) {
  1493. /* scaled rv is denormal; clear j low bits */
  1494. if (j >= 32) {
  1495. word1(&rv) = 0;
  1496. if (j >= 53)
  1497. word0(&rv) = (P+2)*Exp_msk1;
  1498. else
  1499. word0(&rv) &= 0xffffffff << (j-32);
  1500. }
  1501. else
  1502. word1(&rv) &= 0xffffffff << j;
  1503. }
  1504. if (!dval(&rv))
  1505. goto undfl;
  1506. }
  1507. }
  1508. /* Now the hard part -- adjusting rv to the correct value.*/
  1509. /* Put digits into bd: true value = bd * 10^e */
  1510. bc.nd = nd;
  1511. bc.nd0 = nd0; /* Only needed if nd > STRTOD_DIGLIM, but done here */
  1512. /* to silence an erroneous warning about bc.nd0 */
  1513. /* possibly not being initialized. */
  1514. if (nd > STRTOD_DIGLIM) {
  1515. /* ASSERT(STRTOD_DIGLIM >= 18); 18 == one more than the */
  1516. /* minimum number of decimal digits to distinguish double values */
  1517. /* in IEEE arithmetic. */
  1518. /* Truncate input to 18 significant digits, then discard any trailing
  1519. zeros on the result by updating nd, nd0, e and y suitably. (There's
  1520. no need to update z; it's not reused beyond this point.) */
  1521. for (i = 18; i > 0; ) {
  1522. /* scan back until we hit a nonzero digit. significant digit 'i'
  1523. is s0[i] if i < nd0, s0[i+1] if i >= nd0. */
  1524. --i;
  1525. if (s0[i < nd0 ? i : i+1] != '0') {
  1526. ++i;
  1527. break;
  1528. }
  1529. }
  1530. e += nd - i;
  1531. nd = i;
  1532. if (nd0 > nd)
  1533. nd0 = nd;
  1534. if (nd < 9) { /* must recompute y */
  1535. y = 0;
  1536. for(i = 0; i < nd0; ++i)
  1537. y = 10*y + s0[i] - '0';
  1538. for(; i < nd; ++i)
  1539. y = 10*y + s0[i+1] - '0';
  1540. }
  1541. }
  1542. bd0 = s2b(s0, nd0, nd, y);
  1543. if (bd0 == NULL)
  1544. goto failed_malloc;
  1545. /* Notation for the comments below. Write:
  1546. - dv for the absolute value of the number represented by the original
  1547. decimal input string.
  1548. - if we've truncated dv, write tdv for the truncated value.
  1549. Otherwise, set tdv == dv.
  1550. - srv for the quantity rv/2^bc.scale; so srv is the current binary
  1551. approximation to tdv (and dv). It should be exactly representable
  1552. in an IEEE 754 double.
  1553. */
  1554. for(;;) {
  1555. /* This is the main correction loop for _Py_dg_strtod.
  1556. We've got a decimal value tdv, and a floating-point approximation
  1557. srv=rv/2^bc.scale to tdv. The aim is to determine whether srv is
  1558. close enough (i.e., within 0.5 ulps) to tdv, and to compute a new
  1559. approximation if not.
  1560. To determine whether srv is close enough to tdv, compute integers
  1561. bd, bb and bs proportional to tdv, srv and 0.5 ulp(srv)
  1562. respectively, and then use integer arithmetic to determine whether
  1563. |tdv - srv| is less than, equal to, or greater than 0.5 ulp(srv).
  1564. */
  1565. bd = Balloc(bd0->k);
  1566. if (bd == NULL) {
  1567. goto failed_malloc;
  1568. }
  1569. Bcopy(bd, bd0);
  1570. bb = sd2b(&rv, bc.scale, &bbe); /* srv = bb * 2^bbe */
  1571. if (bb == NULL) {
  1572. goto failed_malloc;
  1573. }
  1574. /* Record whether lsb of bb is odd, in case we need this
  1575. for the round-to-even step later. */
  1576. odd = bb->x[0] & 1;
  1577. /* tdv = bd * 10**e; srv = bb * 2**bbe */
  1578. bs = i2b(1);
  1579. if (bs == NULL) {
  1580. goto failed_malloc;
  1581. }
  1582. if (e >= 0) {
  1583. bb2 = bb5 = 0;
  1584. bd2 = bd5 = e;
  1585. }
  1586. else {
  1587. bb2 = bb5 = -e;
  1588. bd2 = bd5 = 0;
  1589. }
  1590. if (bbe >= 0)
  1591. bb2 += bbe;
  1592. else
  1593. bd2 -= bbe;
  1594. bs2 = bb2;
  1595. bb2++;
  1596. bd2++;
  1597. /* At this stage bd5 - bb5 == e == bd2 - bb2 + bbe, bb2 - bs2 == 1,
  1598. and bs == 1, so:
  1599. tdv == bd * 10**e = bd * 2**(bbe - bb2 + bd2) * 5**(bd5 - bb5)
  1600. srv == bb * 2**bbe = bb * 2**(bbe - bb2 + bb2)
  1601. 0.5 ulp(srv) == 2**(bbe-1) = bs * 2**(bbe - bb2 + bs2)
  1602. It follows that:
  1603. M * tdv = bd * 2**bd2 * 5**bd5
  1604. M * srv = bb * 2**bb2 * 5**bb5
  1605. M * 0.5 ulp(srv) = bs * 2**bs2 * 5**bb5
  1606. for some constant M. (Actually, M == 2**(bb2 - bbe) * 5**bb5, but
  1607. this fact is not needed below.)
  1608. */
  1609. /* Remove factor of 2**i, where i = min(bb2, bd2, bs2). */
  1610. i = bb2 < bd2 ? bb2 : bd2;
  1611. if (i > bs2)
  1612. i = bs2;
  1613. if (i > 0) {
  1614. bb2 -= i;
  1615. bd2 -= i;
  1616. bs2 -= i;
  1617. }
  1618. /* Scale bb, bd, bs by the appropriate powers of 2 and 5. */
  1619. if (bb5 > 0) {
  1620. bs = pow5mult(bs, bb5);
  1621. if (bs == NULL) {
  1622. goto failed_malloc;
  1623. }
  1624. Bigint *bb1 = mult(bs, bb);
  1625. Bfree(bb);
  1626. bb = bb1;
  1627. if (bb == NULL) {
  1628. goto failed_malloc;
  1629. }
  1630. }
  1631. if (bb2 > 0) {
  1632. bb = lshift(bb, bb2);
  1633. if (bb == NULL) {
  1634. goto failed_malloc;
  1635. }
  1636. }
  1637. if (bd5 > 0) {
  1638. bd = pow5mult(bd, bd5);
  1639. if (bd == NULL) {
  1640. goto failed_malloc;
  1641. }
  1642. }
  1643. if (bd2 > 0) {
  1644. bd = lshift(bd, bd2);
  1645. if (bd == NULL) {
  1646. goto failed_malloc;
  1647. }
  1648. }
  1649. if (bs2 > 0) {
  1650. bs = lshift(bs, bs2);
  1651. if (bs == NULL) {
  1652. goto failed_malloc;
  1653. }
  1654. }
  1655. /* Now bd, bb and bs are scaled versions of tdv, srv and 0.5 ulp(srv),
  1656. respectively. Compute the difference |tdv - srv|, and compare
  1657. with 0.5 ulp(srv). */
  1658. delta = diff(bb, bd);
  1659. if (delta == NULL) {
  1660. goto failed_malloc;
  1661. }
  1662. dsign = delta->sign;
  1663. delta->sign = 0;
  1664. i = cmp(delta, bs);
  1665. if (bc.nd > nd && i <= 0) {
  1666. if (dsign)
  1667. break; /* Must use bigcomp(). */
  1668. /* Here rv overestimates the truncated decimal value by at most
  1669. 0.5 ulp(rv). Hence rv either overestimates the true decimal
  1670. value by <= 0.5 ulp(rv), or underestimates it by some small
  1671. amount (< 0.1 ulp(rv)); either way, rv is within 0.5 ulps of
  1672. the true decimal value, so it's possible to exit.
  1673. Exception: if scaled rv is a normal exact power of 2, but not
  1674. DBL_MIN, then rv - 0.5 ulp(rv) takes us all the way down to the
  1675. next double, so the correctly rounded result is either rv - 0.5
  1676. ulp(rv) or rv; in this case, use bigcomp to distinguish. */
  1677. if (!word1(&rv) && !(word0(&rv) & Bndry_mask)) {
  1678. /* rv can't be 0, since it's an overestimate for some
  1679. nonzero value. So rv is a normal power of 2. */
  1680. j = (int)(word0(&rv) & Exp_mask) >> Exp_shift;
  1681. /* rv / 2^bc.scale = 2^(j - 1023 - bc.scale); use bigcomp if
  1682. rv / 2^bc.scale >= 2^-1021. */
  1683. if (j - bc.scale >= 2) {
  1684. dval(&rv) -= 0.5 * sulp(&rv, &bc);
  1685. break; /* Use bigcomp. */
  1686. }
  1687. }
  1688. {
  1689. bc.nd = nd;
  1690. i = -1; /* Discarded digits make delta smaller. */
  1691. }
  1692. }
  1693. if (i < 0) {
  1694. /* Error is less than half an ulp -- check for
  1695. * special case of mantissa a power of two.
  1696. */
  1697. if (dsign || word1(&rv) || word0(&rv) & Bndry_mask
  1698. || (word0(&rv) & Exp_mask) <= (2*P+1)*Exp_msk1
  1699. ) {
  1700. break;
  1701. }
  1702. if (!delta->x[0] && delta->wds <= 1) {
  1703. /* exact result */
  1704. break;
  1705. }
  1706. delta = lshift(delta,Log2P);
  1707. if (delta == NULL) {
  1708. goto failed_malloc;
  1709. }
  1710. if (cmp(delta, bs) > 0)
  1711. goto drop_down;
  1712. break;
  1713. }
  1714. if (i == 0) {
  1715. /* exactly half-way between */
  1716. if (dsign) {
  1717. if ((word0(&rv) & Bndry_mask1) == Bndry_mask1
  1718. && word1(&rv) == (
  1719. (bc.scale &&
  1720. (y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1) ?
  1721. (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
  1722. 0xffffffff)) {
  1723. /*boundary case -- increment exponent*/
  1724. word0(&rv) = (word0(&rv) & Exp_mask)
  1725. + Exp_msk1
  1726. ;
  1727. word1(&rv) = 0;
  1728. /* dsign = 0; */
  1729. break;
  1730. }
  1731. }
  1732. else if (!(word0(&rv) & Bndry_mask) && !word1(&rv)) {
  1733. drop_down:
  1734. /* boundary case -- decrement exponent */
  1735. if (bc.scale) {
  1736. L = word0(&rv) & Exp_mask;
  1737. if (L <= (2*P+1)*Exp_msk1) {
  1738. if (L > (P+2)*Exp_msk1)
  1739. /* round even ==> */
  1740. /* accept rv */
  1741. break;
  1742. /* rv = smallest denormal */
  1743. if (bc.nd > nd)
  1744. break;
  1745. goto undfl;
  1746. }
  1747. }
  1748. L = (word0(&rv) & Exp_mask) - Exp_msk1;
  1749. word0(&rv) = L | Bndry_mask1;
  1750. word1(&rv) = 0xffffffff;
  1751. break;
  1752. }
  1753. if (!odd)
  1754. break;
  1755. if (dsign)
  1756. dval(&rv) += sulp(&rv, &bc);
  1757. else {
  1758. dval(&rv) -= sulp(&rv, &bc);
  1759. if (!dval(&rv)) {
  1760. if (bc.nd >nd)
  1761. break;
  1762. goto undfl;
  1763. }
  1764. }
  1765. /* dsign = 1 - dsign; */
  1766. break;
  1767. }
  1768. if ((aadj = ratio(delta, bs)) <= 2.) {
  1769. if (dsign)
  1770. aadj = aadj1 = 1.;
  1771. else if (word1(&rv) || word0(&rv) & Bndry_mask) {
  1772. if (word1(&rv) == Tiny1 && !word0(&rv)) {
  1773. if (bc.nd >nd)
  1774. break;
  1775. goto undfl;
  1776. }
  1777. aadj = 1.;
  1778. aadj1 = -1.;
  1779. }
  1780. else {
  1781. /* special case -- power of FLT_RADIX to be */
  1782. /* rounded down... */
  1783. if (aadj < 2./FLT_RADIX)
  1784. aadj = 1./FLT_RADIX;
  1785. else
  1786. aadj *= 0.5;
  1787. aadj1 = -aadj;
  1788. }
  1789. }
  1790. else {
  1791. aadj *= 0.5;
  1792. aadj1 = dsign ? aadj : -aadj;
  1793. if (Flt_Rounds == 0)
  1794. aadj1 += 0.5;
  1795. }
  1796. y = word0(&rv) & Exp_mask;
  1797. /* Check for overflow */
  1798. if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
  1799. dval(&rv0) = dval(&rv);
  1800. word0(&rv) -= P*Exp_msk1;
  1801. adj.d = aadj1 * ulp(&rv);
  1802. dval(&rv) += adj.d;
  1803. if ((word0(&rv) & Exp_mask) >=
  1804. Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
  1805. if (word0(&rv0) == Big0 && word1(&rv0) == Big1) {
  1806. goto ovfl;
  1807. }
  1808. word0(&rv) = Big0;
  1809. word1(&rv) = Big1;
  1810. goto cont;
  1811. }
  1812. else
  1813. word0(&rv) += P*Exp_msk1;
  1814. }
  1815. else {
  1816. if (bc.scale && y <= 2*P*Exp_msk1) {
  1817. if (aadj <= 0x7fffffff) {
  1818. if ((z = (ULong)aadj) <= 0)
  1819. z = 1;
  1820. aadj = z;
  1821. aadj1 = dsign ? aadj : -aadj;
  1822. }
  1823. dval(&aadj2) = aadj1;
  1824. word0(&aadj2) += (2*P+1)*Exp_msk1 - y;
  1825. aadj1 = dval(&aadj2);
  1826. }
  1827. adj.d = aadj1 * ulp(&rv);
  1828. dval(&rv) += adj.d;
  1829. }
  1830. z = word0(&rv) & Exp_mask;
  1831. if (bc.nd == nd) {
  1832. if (!bc.scale)
  1833. if (y == z) {
  1834. /* Can we stop now? */
  1835. L = (Long)aadj;
  1836. aadj -= L;
  1837. /* The tolerances below are conservative. */
  1838. if (dsign || word1(&rv) || word0(&rv) & Bndry_mask) {
  1839. if (aadj < .4999999 || aadj > .5000001)
  1840. break;
  1841. }
  1842. else if (aadj < .4999999/FLT_RADIX)
  1843. break;
  1844. }
  1845. }
  1846. cont:
  1847. Bfree(bb); bb = NULL;
  1848. Bfree(bd); bd = NULL;
  1849. Bfree(bs); bs = NULL;
  1850. Bfree(delta); delta = NULL;
  1851. }
  1852. if (bc.nd > nd) {
  1853. error = bigcomp(&rv, s0, &bc);
  1854. if (error)
  1855. goto failed_malloc;
  1856. }
  1857. if (bc.scale) {
  1858. word0(&rv0) = Exp_1 - 2*P*Exp_msk1;
  1859. word1(&rv0) = 0;
  1860. dval(&rv) *= dval(&rv0);
  1861. }
  1862. ret:
  1863. result = sign ? -dval(&rv) : dval(&rv);
  1864. goto done;
  1865. parse_error:
  1866. result = 0.0;
  1867. goto done;
  1868. failed_malloc:
  1869. errno = ENOMEM;
  1870. result = -1.0;
  1871. goto done;
  1872. undfl:
  1873. result = sign ? -0.0 : 0.0;
  1874. goto done;
  1875. ovfl:
  1876. errno = ERANGE;
  1877. /* Can't trust HUGE_VAL */
  1878. word0(&rv) = Exp_mask;
  1879. word1(&rv) = 0;
  1880. result = sign ? -dval(&rv) : dval(&rv);
  1881. goto done;
  1882. done:
  1883. Bfree(bb);
  1884. Bfree(bd);
  1885. Bfree(bs);
  1886. Bfree(bd0);
  1887. Bfree(delta);
  1888. return result;
  1889. }
  1890. static char *
  1891. rv_alloc(int i)
  1892. {
  1893. int j, k, *r;
  1894. j = sizeof(ULong);
  1895. for(k = 0;
  1896. sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= (unsigned)i;
  1897. j <<= 1)
  1898. k++;
  1899. r = (int*)Balloc(k);
  1900. if (r == NULL)
  1901. return NULL;
  1902. *r = k;
  1903. return (char *)(r+1);
  1904. }
  1905. static char *
  1906. nrv_alloc(const char *s, char **rve, int n)
  1907. {
  1908. char *rv, *t;
  1909. rv = rv_alloc(n);
  1910. if (rv == NULL)
  1911. return NULL;
  1912. t = rv;
  1913. while((*t = *s++)) t++;
  1914. if (rve)
  1915. *rve = t;
  1916. return rv;
  1917. }
  1918. /* freedtoa(s) must be used to free values s returned by dtoa
  1919. * when MULTIPLE_THREADS is #defined. It should be used in all cases,
  1920. * but for consistency with earlier versions of dtoa, it is optional
  1921. * when MULTIPLE_THREADS is not defined.
  1922. */
  1923. void
  1924. _Py_dg_freedtoa(char *s)
  1925. {
  1926. Bigint *b = (Bigint *)((int *)s - 1);
  1927. b->maxwds = 1 << (b->k = *(int*)b);
  1928. Bfree(b);
  1929. }
  1930. /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
  1931. *
  1932. * Inspired by "How to Print Floating-Point Numbers Accurately" by
  1933. * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
  1934. *
  1935. * Modifications:
  1936. * 1. Rather than iterating, we use a simple numeric overestimate
  1937. * to determine k = floor(log10(d)). We scale relevant
  1938. * quantities using O(log2(k)) rather than O(k) multiplications.
  1939. * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
  1940. * try to generate digits strictly left to right. Instead, we
  1941. * compute with fewer bits and propagate the carry if necessary
  1942. * when rounding the final digit up. This is often faster.
  1943. * 3. Under the assumption that input will be rounded nearest,
  1944. * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
  1945. * That is, we allow equality in stopping tests when the
  1946. * round-nearest rule will give the same floating-point value
  1947. * as would satisfaction of the stopping test with strict
  1948. * inequality.
  1949. * 4. We remove common factors of powers of 2 from relevant
  1950. * quantities.
  1951. * 5. When converting floating-point integers less than 1e16,
  1952. * we use floating-point arithmetic rather than resorting
  1953. * to multiple-precision integers.
  1954. * 6. When asked to produce fewer than 15 digits, we first try
  1955. * to get by with floating-point arithmetic; we resort to
  1956. * multiple-precision integer arithmetic only if we cannot
  1957. * guarantee that the floating-point calculation has given
  1958. * the correctly rounded result. For k requested digits and
  1959. * "uniformly" distributed input, the probability is
  1960. * something like 10^(k-15) that we must resort to the Long
  1961. * calculation.
  1962. */
  1963. /* Additional notes (METD): (1) returns NULL on failure. (2) to avoid memory
  1964. leakage, a successful call to _Py_dg_dtoa should always be matched by a
  1965. call to _Py_dg_freedtoa. */
  1966. char *
  1967. _Py_dg_dtoa(double dd, int mode, int ndigits,
  1968. int *decpt, int *sign, char **rve)
  1969. {
  1970. /* Arguments ndigits, decpt, sign are similar to those
  1971. of ecvt and fcvt; trailing zeros are suppressed from
  1972. the returned string. If not null, *rve is set to point
  1973. to the end of the return value. If d is +-Infinity or NaN,
  1974. then *decpt is set to 9999.
  1975. mode:
  1976. 0 ==> shortest string that yields d when read in
  1977. and rounded to nearest.
  1978. 1 ==> like 0, but with Steele & White stopping rule;
  1979. e.g. with IEEE P754 arithmetic , mode 0 gives
  1980. 1e23 whereas mode 1 gives 9.999999999999999e22.
  1981. 2 ==> max(1,ndigits) significant digits. This gives a
  1982. return value similar to that of ecvt, except
  1983. that trailing zeros are suppressed.
  1984. 3 ==> through ndigits past the decimal point. This
  1985. gives a return value similar to that from fcvt,
  1986. except that trailing zeros are suppressed, and
  1987. ndigits can be negative.
  1988. 4,5 ==> similar to 2 and 3, respectively, but (in
  1989. round-nearest mode) with the tests of mode 0 to
  1990. possibly return a shorter string that rounds to d.
  1991. With IEEE arithmetic and compilation with
  1992. -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
  1993. as modes 2 and 3 when FLT_ROUNDS != 1.
  1994. 6-9 ==> Debugging modes similar to mode - 4: don't try
  1995. fast floating-point estimate (if applicable).
  1996. Values of mode other than 0-9 are treated as mode 0.
  1997. Sufficient space is allocated to the return value
  1998. to hold the suppressed trailing zeros.
  1999. */
  2000. int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
  2001. j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
  2002. spec_case, try_quick;
  2003. Long L;
  2004. int denorm;
  2005. ULong x;
  2006. Bigint *b, *b1, *delta, *mlo, *mhi, *S;
  2007. U d2, eps, u;
  2008. double ds;
  2009. char *s, *s0;
  2010. /* set pointers to NULL, to silence gcc compiler warnings and make
  2011. cleanup easier on error */
  2012. mlo = mhi = S = 0;
  2013. s0 = 0;
  2014. u.d = dd;
  2015. if (word0(&u) & Sign_bit) {
  2016. /* set sign for everything, including 0's and NaNs */
  2017. *sign = 1;
  2018. word0(&u) &= ~Sign_bit; /* clear sign bit */
  2019. }
  2020. else
  2021. *sign = 0;
  2022. /* quick return for Infinities, NaNs and zeros */
  2023. if ((word0(&u) & Exp_mask) == Exp_mask)
  2024. {
  2025. /* Infinity or NaN */
  2026. *decpt = 9999;
  2027. if (!word1(&u) && !(word0(&u) & 0xfffff))
  2028. return nrv_alloc("Infinity", rve, 8);
  2029. return nrv_alloc("NaN", rve, 3);
  2030. }
  2031. if (!dval(&u)) {
  2032. *decpt = 1;
  2033. return nrv_alloc("0", rve, 1);
  2034. }
  2035. /* compute k = floor(log10(d)). The computation may leave k
  2036. one too large, but should never leave k too small. */
  2037. b = d2b(&u, &be, &bbits);
  2038. if (b == NULL)
  2039. goto failed_malloc;
  2040. if ((i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1)))) {
  2041. dval(&d2) = dval(&u);
  2042. word0(&d2) &= Frac_mask1;
  2043. word0(&d2) |= Exp_11;
  2044. /* log(x) ~=~ log(1.5) + (x-1.5)/1.5
  2045. * log10(x) = log(x) / log(10)
  2046. * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
  2047. * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
  2048. *
  2049. * This suggests computing an approximation k to log10(d) by
  2050. *
  2051. * k = (i - Bias)*0.301029995663981
  2052. * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
  2053. *
  2054. * We want k to be too large rather than too small.
  2055. * The error in the first-order Taylor series approximation
  2056. * is in our favor, so we just round up the constant enough
  2057. * to compensate for any error in the multiplication of
  2058. * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
  2059. * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
  2060. * adding 1e-13 to the constant term more than suffices.
  2061. * Hence we adjust the constant term to 0.1760912590558.
  2062. * (We could get a more accurate k by invoking log10,
  2063. * but this is probably not worthwhile.)
  2064. */
  2065. i -= Bias;
  2066. denorm = 0;
  2067. }
  2068. else {
  2069. /* d is denormalized */
  2070. i = bbits + be + (Bias + (P-1) - 1);
  2071. x = i > 32 ? word0(&u) << (64 - i) | word1(&u) >> (i - 32)
  2072. : word1(&u) << (32 - i);
  2073. dval(&d2) = x;
  2074. word0(&d2) -= 31*Exp_msk1; /* adjust exponent */
  2075. i -= (Bias + (P-1) - 1) + 1;
  2076. denorm = 1;
  2077. }
  2078. ds = (dval(&d2)-1.5)*0.289529654602168 + 0.1760912590558 +
  2079. i*0.301029995663981;
  2080. k = (int)ds;
  2081. if (ds < 0. && ds != k)
  2082. k--; /* want k = floor(ds) */
  2083. k_check = 1;
  2084. if (k >= 0 && k <= Ten_pmax) {
  2085. if (dval(&u) < tens[k])
  2086. k--;
  2087. k_check = 0;
  2088. }
  2089. j = bbits - i - 1;
  2090. if (j >= 0) {
  2091. b2 = 0;
  2092. s2 = j;
  2093. }
  2094. else {
  2095. b2 = -j;
  2096. s2 = 0;
  2097. }
  2098. if (k >= 0) {
  2099. b5 = 0;
  2100. s5 = k;
  2101. s2 += k;
  2102. }
  2103. else {
  2104. b2 -= k;
  2105. b5 = -k;
  2106. s5 = 0;
  2107. }
  2108. if (mode < 0 || mode > 9)
  2109. mode = 0;
  2110. try_quick = 1;
  2111. if (mode > 5) {
  2112. mode -= 4;
  2113. try_quick = 0;
  2114. }
  2115. leftright = 1;
  2116. ilim = ilim1 = -1; /* Values for cases 0 and 1; done here to */
  2117. /* silence erroneous "gcc -Wall" warning. */
  2118. switch(mode) {
  2119. case 0:
  2120. case 1:
  2121. i = 18;
  2122. ndigits = 0;
  2123. break;
  2124. case 2:
  2125. leftright = 0;
  2126. /* fall through */
  2127. case 4:
  2128. if (ndigits <= 0)
  2129. ndigits = 1;
  2130. ilim = ilim1 = i = ndigits;
  2131. break;
  2132. case 3:
  2133. leftright = 0;
  2134. /* fall through */
  2135. case 5:
  2136. i = ndigits + k + 1;
  2137. ilim = i;
  2138. ilim1 = i - 1;
  2139. if (i <= 0)
  2140. i = 1;
  2141. }
  2142. s0 = rv_alloc(i);
  2143. if (s0 == NULL)
  2144. goto failed_malloc;
  2145. s = s0;
  2146. if (ilim >= 0 && ilim <= Quick_max && try_quick) {
  2147. /* Try to get by with floating-point arithmetic. */
  2148. i = 0;
  2149. dval(&d2) = dval(&u);
  2150. k0 = k;
  2151. ilim0 = ilim;
  2152. ieps = 2; /* conservative */
  2153. if (k > 0) {
  2154. ds = tens[k&0xf];
  2155. j = k >> 4;
  2156. if (j & Bletch) {
  2157. /* prevent overflows */
  2158. j &= Bletch - 1;
  2159. dval(&u) /= bigtens[n_bigtens-1];
  2160. ieps++;
  2161. }
  2162. for(; j; j >>= 1, i++)
  2163. if (j & 1) {
  2164. ieps++;
  2165. ds *= bigtens[i];
  2166. }
  2167. dval(&u) /= ds;
  2168. }
  2169. else if ((j1 = -k)) {
  2170. dval(&u) *= tens[j1 & 0xf];
  2171. for(j = j1 >> 4; j; j >>= 1, i++)
  2172. if (j & 1) {
  2173. ieps++;
  2174. dval(&u) *= bigtens[i];
  2175. }
  2176. }
  2177. if (k_check && dval(&u) < 1. && ilim > 0) {
  2178. if (ilim1 <= 0)
  2179. goto fast_failed;
  2180. ilim = ilim1;
  2181. k--;
  2182. dval(&u) *= 10.;
  2183. ieps++;
  2184. }
  2185. dval(&eps) = ieps*dval(&u) + 7.;
  2186. word0(&eps) -= (P-1)*Exp_msk1;
  2187. if (ilim == 0) {
  2188. S = mhi = 0;
  2189. dval(&u) -= 5.;
  2190. if (dval(&u) > dval(&eps))
  2191. goto one_digit;
  2192. if (dval(&u) < -dval(&eps))
  2193. goto no_digits;
  2194. goto fast_failed;
  2195. }
  2196. if (leftright) {
  2197. /* Use Steele & White method of only
  2198. * generating digits needed.
  2199. */
  2200. dval(&eps) = 0.5/tens[ilim-1] - dval(&eps);
  2201. for(i = 0;;) {
  2202. L = (Long)dval(&u);
  2203. dval(&u) -= L;
  2204. *s++ = '0' + (int)L;
  2205. if (dval(&u) < dval(&eps))
  2206. goto ret1;
  2207. if (1. - dval(&u) < dval(&eps))
  2208. goto bump_up;
  2209. if (++i >= ilim)
  2210. break;
  2211. dval(&eps) *= 10.;
  2212. dval(&u) *= 10.;
  2213. }
  2214. }
  2215. else {
  2216. /* Generate ilim digits, then fix them up. */
  2217. dval(&eps) *= tens[ilim-1];
  2218. for(i = 1;; i++, dval(&u) *= 10.) {
  2219. L = (Long)(dval(&u));
  2220. if (!(dval(&u) -= L))
  2221. ilim = i;
  2222. *s++ = '0' + (int)L;
  2223. if (i == ilim) {
  2224. if (dval(&u) > 0.5 + dval(&eps))
  2225. goto bump_up;
  2226. else if (dval(&u) < 0.5 - dval(&eps)) {
  2227. while(*--s == '0');
  2228. s++;
  2229. goto ret1;
  2230. }
  2231. break;
  2232. }
  2233. }
  2234. }
  2235. fast_failed:
  2236. s = s0;
  2237. dval(&u) = dval(&d2);
  2238. k = k0;
  2239. ilim = ilim0;
  2240. }
  2241. /* Do we have a "small" integer? */
  2242. if (be >= 0 && k <= Int_max) {
  2243. /* Yes. */
  2244. ds = tens[k];
  2245. if (ndigits < 0 && ilim <= 0) {
  2246. S = mhi = 0;
  2247. if (ilim < 0 || dval(&u) <= 5*ds)
  2248. goto no_digits;
  2249. goto one_digit;
  2250. }
  2251. for(i = 1;; i++, dval(&u) *= 10.) {
  2252. L = (Long)(dval(&u) / ds);
  2253. dval(&u) -= L*ds;
  2254. *s++ = '0' + (int)L;
  2255. if (!dval(&u)) {
  2256. break;
  2257. }
  2258. if (i == ilim) {
  2259. dval(&u) += dval(&u);
  2260. if (dval(&u) > ds || (dval(&u) == ds && L & 1)) {
  2261. bump_up:
  2262. while(*--s == '9')
  2263. if (s == s0) {
  2264. k++;
  2265. *s = '0';
  2266. break;
  2267. }
  2268. ++*s++;
  2269. }
  2270. else {
  2271. /* Strip trailing zeros. This branch was missing from the
  2272. original dtoa.c, leading to surplus trailing zeros in
  2273. some cases. See bugs.python.org/issue40780. */
  2274. while (s > s0 && s[-1] == '0') {
  2275. --s;
  2276. }
  2277. }
  2278. break;
  2279. }
  2280. }
  2281. goto ret1;
  2282. }
  2283. m2 = b2;
  2284. m5 = b5;
  2285. if (leftright) {
  2286. i =
  2287. denorm ? be + (Bias + (P-1) - 1 + 1) :
  2288. 1 + P - bbits;
  2289. b2 += i;
  2290. s2 += i;
  2291. mhi = i2b(1);
  2292. if (mhi == NULL)
  2293. goto failed_malloc;
  2294. }
  2295. if (m2 > 0 && s2 > 0) {
  2296. i = m2 < s2 ? m2 : s2;
  2297. b2 -= i;
  2298. m2 -= i;
  2299. s2 -= i;
  2300. }
  2301. if (b5 > 0) {
  2302. if (leftright) {
  2303. if (m5 > 0) {
  2304. mhi = pow5mult(mhi, m5);
  2305. if (mhi == NULL)
  2306. goto failed_malloc;
  2307. b1 = mult(mhi, b);
  2308. Bfree(b);
  2309. b = b1;
  2310. if (b == NULL)
  2311. goto failed_malloc;
  2312. }
  2313. if ((j = b5 - m5)) {
  2314. b = pow5mult(b, j);
  2315. if (b == NULL)
  2316. goto failed_malloc;
  2317. }
  2318. }
  2319. else {
  2320. b = pow5mult(b, b5);
  2321. if (b == NULL)
  2322. goto failed_malloc;
  2323. }
  2324. }
  2325. S = i2b(1);
  2326. if (S == NULL)
  2327. goto failed_malloc;
  2328. if (s5 > 0) {
  2329. S = pow5mult(S, s5);
  2330. if (S == NULL)
  2331. goto failed_malloc;
  2332. }
  2333. /* Check for special case that d is a normalized power of 2. */
  2334. spec_case = 0;
  2335. if ((mode < 2 || leftright)
  2336. ) {
  2337. if (!word1(&u) && !(word0(&u) & Bndry_mask)
  2338. && word0(&u) & (Exp_mask & ~Exp_msk1)
  2339. ) {
  2340. /* The special case */
  2341. b2 += Log2P;
  2342. s2 += Log2P;
  2343. spec_case = 1;
  2344. }
  2345. }
  2346. /* Arrange for convenient computation of quotients:
  2347. * shift left if necessary so divisor has 4 leading 0 bits.
  2348. *
  2349. * Perhaps we should just compute leading 28 bits of S once
  2350. * and for all and pass them and a shift to quorem, so it
  2351. * can do shifts and ors to compute the numerator for q.
  2352. */
  2353. #define iInc 28
  2354. i = dshift(S, s2);
  2355. b2 += i;
  2356. m2 += i;
  2357. s2 += i;
  2358. if (b2 > 0) {
  2359. b = lshift(b, b2);
  2360. if (b == NULL)
  2361. goto failed_malloc;
  2362. }
  2363. if (s2 > 0) {
  2364. S = lshift(S, s2);
  2365. if (S == NULL)
  2366. goto failed_malloc;
  2367. }
  2368. if (k_check) {
  2369. if (cmp(b,S) < 0) {
  2370. k--;
  2371. b = multadd(b, 10, 0); /* we botched the k estimate */
  2372. if (b == NULL)
  2373. goto failed_malloc;
  2374. if (leftright) {
  2375. mhi = multadd(mhi, 10, 0);
  2376. if (mhi == NULL)
  2377. goto failed_malloc;
  2378. }
  2379. ilim = ilim1;
  2380. }
  2381. }
  2382. if (ilim <= 0 && (mode == 3 || mode == 5)) {
  2383. if (ilim < 0) {
  2384. /* no digits, fcvt style */
  2385. no_digits:
  2386. k = -1 - ndigits;
  2387. goto ret;
  2388. }
  2389. else {
  2390. S = multadd(S, 5, 0);
  2391. if (S == NULL)
  2392. goto failed_malloc;
  2393. if (cmp(b, S) <= 0)
  2394. goto no_digits;
  2395. }
  2396. one_digit:
  2397. *s++ = '1';
  2398. k++;
  2399. goto ret;
  2400. }
  2401. if (leftright) {
  2402. if (m2 > 0) {
  2403. mhi = lshift(mhi, m2);
  2404. if (mhi == NULL)
  2405. goto failed_malloc;
  2406. }
  2407. /* Compute mlo -- check for special case
  2408. * that d is a normalized power of 2.
  2409. */
  2410. mlo = mhi;
  2411. if (spec_case) {
  2412. mhi = Balloc(mhi->k);
  2413. if (mhi == NULL)
  2414. goto failed_malloc;
  2415. Bcopy(mhi, mlo);
  2416. mhi = lshift(mhi, Log2P);
  2417. if (mhi == NULL)
  2418. goto failed_malloc;
  2419. }
  2420. for(i = 1;;i++) {
  2421. dig = quorem(b,S) + '0';
  2422. /* Do we yet have the shortest decimal string
  2423. * that will round to d?
  2424. */
  2425. j = cmp(b, mlo);
  2426. delta = diff(S, mhi);
  2427. if (delta == NULL)
  2428. goto failed_malloc;
  2429. j1 = delta->sign ? 1 : cmp(b, delta);
  2430. Bfree(delta);
  2431. if (j1 == 0 && mode != 1 && !(word1(&u) & 1)
  2432. ) {
  2433. if (dig == '9')
  2434. goto round_9_up;
  2435. if (j > 0)
  2436. dig++;
  2437. *s++ = dig;
  2438. goto ret;
  2439. }
  2440. if (j < 0 || (j == 0 && mode != 1
  2441. && !(word1(&u) & 1)
  2442. )) {
  2443. if (!b->x[0] && b->wds <= 1) {
  2444. goto accept_dig;
  2445. }
  2446. if (j1 > 0) {
  2447. b = lshift(b, 1);
  2448. if (b == NULL)
  2449. goto failed_malloc;
  2450. j1 = cmp(b, S);
  2451. if ((j1 > 0 || (j1 == 0 && dig & 1))
  2452. && dig++ == '9')
  2453. goto round_9_up;
  2454. }
  2455. accept_dig:
  2456. *s++ = dig;
  2457. goto ret;
  2458. }
  2459. if (j1 > 0) {
  2460. if (dig == '9') { /* possible if i == 1 */
  2461. round_9_up:
  2462. *s++ = '9';
  2463. goto roundoff;
  2464. }
  2465. *s++ = dig + 1;
  2466. goto ret;
  2467. }
  2468. *s++ = dig;
  2469. if (i == ilim)
  2470. break;
  2471. b = multadd(b, 10, 0);
  2472. if (b == NULL)
  2473. goto failed_malloc;
  2474. if (mlo == mhi) {
  2475. mlo = mhi = multadd(mhi, 10, 0);
  2476. if (mlo == NULL)
  2477. goto failed_malloc;
  2478. }
  2479. else {
  2480. mlo = multadd(mlo, 10, 0);
  2481. if (mlo == NULL)
  2482. goto failed_malloc;
  2483. mhi = multadd(mhi, 10, 0);
  2484. if (mhi == NULL)
  2485. goto failed_malloc;
  2486. }
  2487. }
  2488. }
  2489. else
  2490. for(i = 1;; i++) {
  2491. *s++ = dig = quorem(b,S) + '0';
  2492. if (!b->x[0] && b->wds <= 1) {
  2493. goto ret;
  2494. }
  2495. if (i >= ilim)
  2496. break;
  2497. b = multadd(b, 10, 0);
  2498. if (b == NULL)
  2499. goto failed_malloc;
  2500. }
  2501. /* Round off last digit */
  2502. b = lshift(b, 1);
  2503. if (b == NULL)
  2504. goto failed_malloc;
  2505. j = cmp(b, S);
  2506. if (j > 0 || (j == 0 && dig & 1)) {
  2507. roundoff:
  2508. while(*--s == '9')
  2509. if (s == s0) {
  2510. k++;
  2511. *s++ = '1';
  2512. goto ret;
  2513. }
  2514. ++*s++;
  2515. }
  2516. else {
  2517. while(*--s == '0');
  2518. s++;
  2519. }
  2520. ret:
  2521. Bfree(S);
  2522. if (mhi) {
  2523. if (mlo && mlo != mhi)
  2524. Bfree(mlo);
  2525. Bfree(mhi);
  2526. }
  2527. ret1:
  2528. Bfree(b);
  2529. *s = 0;
  2530. *decpt = k + 1;
  2531. if (rve)
  2532. *rve = s;
  2533. return s0;
  2534. failed_malloc:
  2535. if (S)
  2536. Bfree(S);
  2537. if (mlo && mlo != mhi)
  2538. Bfree(mlo);
  2539. if (mhi)
  2540. Bfree(mhi);
  2541. if (b)
  2542. Bfree(b);
  2543. if (s0)
  2544. _Py_dg_freedtoa(s0);
  2545. return NULL;
  2546. }
  2547. #ifdef __cplusplus
  2548. }
  2549. #endif
  2550. #endif // _PY_SHORT_FLOAT_REPR == 1