mathmodule.c 129 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160
  1. /* Math module -- standard C math library functions, pi and e */
  2. /* Here are some comments from Tim Peters, extracted from the
  3. discussion attached to http://bugs.python.org/issue1640. They
  4. describe the general aims of the math module with respect to
  5. special values, IEEE-754 floating-point exceptions, and Python
  6. exceptions.
  7. These are the "spirit of 754" rules:
  8. 1. If the mathematical result is a real number, but of magnitude too
  9. large to approximate by a machine float, overflow is signaled and the
  10. result is an infinity (with the appropriate sign).
  11. 2. If the mathematical result is a real number, but of magnitude too
  12. small to approximate by a machine float, underflow is signaled and the
  13. result is a zero (with the appropriate sign).
  14. 3. At a singularity (a value x such that the limit of f(y) as y
  15. approaches x exists and is an infinity), "divide by zero" is signaled
  16. and the result is an infinity (with the appropriate sign). This is
  17. complicated a little by that the left-side and right-side limits may
  18. not be the same; e.g., 1/x approaches +inf or -inf as x approaches 0
  19. from the positive or negative directions. In that specific case, the
  20. sign of the zero determines the result of 1/0.
  21. 4. At a point where a function has no defined result in the extended
  22. reals (i.e., the reals plus an infinity or two), invalid operation is
  23. signaled and a NaN is returned.
  24. And these are what Python has historically /tried/ to do (but not
  25. always successfully, as platform libm behavior varies a lot):
  26. For #1, raise OverflowError.
  27. For #2, return a zero (with the appropriate sign if that happens by
  28. accident ;-)).
  29. For #3 and #4, raise ValueError. It may have made sense to raise
  30. Python's ZeroDivisionError in #3, but historically that's only been
  31. raised for division by zero and mod by zero.
  32. */
  33. /*
  34. In general, on an IEEE-754 platform the aim is to follow the C99
  35. standard, including Annex 'F', whenever possible. Where the
  36. standard recommends raising the 'divide-by-zero' or 'invalid'
  37. floating-point exceptions, Python should raise a ValueError. Where
  38. the standard recommends raising 'overflow', Python should raise an
  39. OverflowError. In all other circumstances a value should be
  40. returned.
  41. */
  42. #ifndef Py_BUILD_CORE_BUILTIN
  43. # define Py_BUILD_CORE_MODULE 1
  44. #endif
  45. #include "Python.h"
  46. #include "pycore_bitutils.h" // _Py_bit_length()
  47. #include "pycore_call.h" // _PyObject_CallNoArgs()
  48. #include "pycore_long.h" // _PyLong_GetZero()
  49. #include "pycore_moduleobject.h" // _PyModule_GetState()
  50. #include "pycore_object.h" // _PyObject_LookupSpecial()
  51. #include "pycore_pymath.h" // _PY_SHORT_FLOAT_REPR
  52. /* For DBL_EPSILON in _math.h */
  53. #include <float.h>
  54. /* For _Py_log1p with workarounds for buggy handling of zeros. */
  55. #include "_math.h"
  56. #include <stdbool.h>
  57. #include "clinic/mathmodule.c.h"
  58. /*[clinic input]
  59. module math
  60. [clinic start generated code]*/
  61. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=76bc7002685dd942]*/
  62. typedef struct {
  63. PyObject *str___ceil__;
  64. PyObject *str___floor__;
  65. PyObject *str___trunc__;
  66. } math_module_state;
  67. static inline math_module_state*
  68. get_math_module_state(PyObject *module)
  69. {
  70. void *state = _PyModule_GetState(module);
  71. assert(state != NULL);
  72. return (math_module_state *)state;
  73. }
  74. /*
  75. Double and triple length extended precision algorithms from:
  76. Accurate Sum and Dot Product
  77. by Takeshi Ogita, Siegfried M. Rump, and Shin’Ichi Oishi
  78. https://doi.org/10.1137/030601818
  79. https://www.tuhh.de/ti3/paper/rump/OgRuOi05.pdf
  80. */
  81. typedef struct{ double hi; double lo; } DoubleLength;
  82. static DoubleLength
  83. dl_fast_sum(double a, double b)
  84. {
  85. /* Algorithm 1.1. Compensated summation of two floating point numbers. */
  86. assert(fabs(a) >= fabs(b));
  87. double x = a + b;
  88. double y = (a - x) + b;
  89. return (DoubleLength) {x, y};
  90. }
  91. static DoubleLength
  92. dl_sum(double a, double b)
  93. {
  94. /* Algorithm 3.1 Error-free transformation of the sum */
  95. double x = a + b;
  96. double z = x - a;
  97. double y = (a - (x - z)) + (b - z);
  98. return (DoubleLength) {x, y};
  99. }
  100. #ifndef UNRELIABLE_FMA
  101. static DoubleLength
  102. dl_mul(double x, double y)
  103. {
  104. /* Algorithm 3.5. Error-free transformation of a product */
  105. double z = x * y;
  106. double zz = fma(x, y, -z);
  107. return (DoubleLength) {z, zz};
  108. }
  109. #else
  110. /*
  111. The default implementation of dl_mul() depends on the C math library
  112. having an accurate fma() function as required by § 7.12.13.1 of the
  113. C99 standard.
  114. The UNRELIABLE_FMA option is provided as a slower but accurate
  115. alternative for builds where the fma() function is found wanting.
  116. The speed penalty may be modest (17% slower on an Apple M1 Max),
  117. so don't hesitate to enable this build option.
  118. The algorithms are from the T. J. Dekker paper:
  119. A Floating-Point Technique for Extending the Available Precision
  120. https://csclub.uwaterloo.ca/~pbarfuss/dekker1971.pdf
  121. */
  122. static DoubleLength
  123. dl_split(double x) {
  124. // Dekker (5.5) and (5.6).
  125. double t = x * 134217729.0; // Veltkamp constant = 2.0 ** 27 + 1
  126. double hi = t - (t - x);
  127. double lo = x - hi;
  128. return (DoubleLength) {hi, lo};
  129. }
  130. static DoubleLength
  131. dl_mul(double x, double y)
  132. {
  133. // Dekker (5.12) and mul12()
  134. DoubleLength xx = dl_split(x);
  135. DoubleLength yy = dl_split(y);
  136. double p = xx.hi * yy.hi;
  137. double q = xx.hi * yy.lo + xx.lo * yy.hi;
  138. double z = p + q;
  139. double zz = p - z + q + xx.lo * yy.lo;
  140. return (DoubleLength) {z, zz};
  141. }
  142. #endif
  143. typedef struct { double hi; double lo; double tiny; } TripleLength;
  144. static const TripleLength tl_zero = {0.0, 0.0, 0.0};
  145. static TripleLength
  146. tl_fma(double x, double y, TripleLength total)
  147. {
  148. /* Algorithm 5.10 with SumKVert for K=3 */
  149. DoubleLength pr = dl_mul(x, y);
  150. DoubleLength sm = dl_sum(total.hi, pr.hi);
  151. DoubleLength r1 = dl_sum(total.lo, pr.lo);
  152. DoubleLength r2 = dl_sum(r1.hi, sm.lo);
  153. return (TripleLength) {sm.hi, r2.hi, total.tiny + r1.lo + r2.lo};
  154. }
  155. static double
  156. tl_to_d(TripleLength total)
  157. {
  158. DoubleLength last = dl_sum(total.lo, total.hi);
  159. return total.tiny + last.lo + last.hi;
  160. }
  161. /*
  162. sin(pi*x), giving accurate results for all finite x (especially x
  163. integral or close to an integer). This is here for use in the
  164. reflection formula for the gamma function. It conforms to IEEE
  165. 754-2008 for finite arguments, but not for infinities or nans.
  166. */
  167. static const double pi = 3.141592653589793238462643383279502884197;
  168. static const double logpi = 1.144729885849400174143427351353058711647;
  169. /* Version of PyFloat_AsDouble() with in-line fast paths
  170. for exact floats and integers. Gives a substantial
  171. speed improvement for extracting float arguments.
  172. */
  173. #define ASSIGN_DOUBLE(target_var, obj, error_label) \
  174. if (PyFloat_CheckExact(obj)) { \
  175. target_var = PyFloat_AS_DOUBLE(obj); \
  176. } \
  177. else if (PyLong_CheckExact(obj)) { \
  178. target_var = PyLong_AsDouble(obj); \
  179. if (target_var == -1.0 && PyErr_Occurred()) { \
  180. goto error_label; \
  181. } \
  182. } \
  183. else { \
  184. target_var = PyFloat_AsDouble(obj); \
  185. if (target_var == -1.0 && PyErr_Occurred()) { \
  186. goto error_label; \
  187. } \
  188. }
  189. static double
  190. m_sinpi(double x)
  191. {
  192. double y, r;
  193. int n;
  194. /* this function should only ever be called for finite arguments */
  195. assert(Py_IS_FINITE(x));
  196. y = fmod(fabs(x), 2.0);
  197. n = (int)round(2.0*y);
  198. assert(0 <= n && n <= 4);
  199. switch (n) {
  200. case 0:
  201. r = sin(pi*y);
  202. break;
  203. case 1:
  204. r = cos(pi*(y-0.5));
  205. break;
  206. case 2:
  207. /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
  208. -0.0 instead of 0.0 when y == 1.0. */
  209. r = sin(pi*(1.0-y));
  210. break;
  211. case 3:
  212. r = -cos(pi*(y-1.5));
  213. break;
  214. case 4:
  215. r = sin(pi*(y-2.0));
  216. break;
  217. default:
  218. Py_UNREACHABLE();
  219. }
  220. return copysign(1.0, x)*r;
  221. }
  222. /* Implementation of the real gamma function. Kept here to work around
  223. issues (see e.g. gh-70309) with quality of libm's tgamma/lgamma implementations
  224. on various platforms (Windows, MacOS). In extensive but non-exhaustive
  225. random tests, this function proved accurate to within <= 10 ulps across the
  226. entire float domain. Note that accuracy may depend on the quality of the
  227. system math functions, the pow function in particular. Special cases
  228. follow C99 annex F. The parameters and method are tailored to platforms
  229. whose double format is the IEEE 754 binary64 format.
  230. Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
  231. and g=6.024680040776729583740234375; these parameters are amongst those
  232. used by the Boost library. Following Boost (again), we re-express the
  233. Lanczos sum as a rational function, and compute it that way. The
  234. coefficients below were computed independently using MPFR, and have been
  235. double-checked against the coefficients in the Boost source code.
  236. For x < 0.0 we use the reflection formula.
  237. There's one minor tweak that deserves explanation: Lanczos' formula for
  238. Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
  239. values, x+g-0.5 can be represented exactly. However, in cases where it
  240. can't be represented exactly the small error in x+g-0.5 can be magnified
  241. significantly by the pow and exp calls, especially for large x. A cheap
  242. correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
  243. involved in the computation of x+g-0.5 (that is, e = computed value of
  244. x+g-0.5 - exact value of x+g-0.5). Here's the proof:
  245. Correction factor
  246. -----------------
  247. Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
  248. double, and e is tiny. Then:
  249. pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
  250. = pow(y, x-0.5)/exp(y) * C,
  251. where the correction_factor C is given by
  252. C = pow(1-e/y, x-0.5) * exp(e)
  253. Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
  254. C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
  255. But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
  256. pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
  257. Note that for accuracy, when computing r*C it's better to do
  258. r + e*g/y*r;
  259. than
  260. r * (1 + e*g/y);
  261. since the addition in the latter throws away most of the bits of
  262. information in e*g/y.
  263. */
  264. #define LANCZOS_N 13
  265. static const double lanczos_g = 6.024680040776729583740234375;
  266. static const double lanczos_g_minus_half = 5.524680040776729583740234375;
  267. static const double lanczos_num_coeffs[LANCZOS_N] = {
  268. 23531376880.410759688572007674451636754734846804940,
  269. 42919803642.649098768957899047001988850926355848959,
  270. 35711959237.355668049440185451547166705960488635843,
  271. 17921034426.037209699919755754458931112671403265390,
  272. 6039542586.3520280050642916443072979210699388420708,
  273. 1439720407.3117216736632230727949123939715485786772,
  274. 248874557.86205415651146038641322942321632125127801,
  275. 31426415.585400194380614231628318205362874684987640,
  276. 2876370.6289353724412254090516208496135991145378768,
  277. 186056.26539522349504029498971604569928220784236328,
  278. 8071.6720023658162106380029022722506138218516325024,
  279. 210.82427775157934587250973392071336271166969580291,
  280. 2.5066282746310002701649081771338373386264310793408
  281. };
  282. /* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
  283. static const double lanczos_den_coeffs[LANCZOS_N] = {
  284. 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
  285. 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
  286. /* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
  287. #define NGAMMA_INTEGRAL 23
  288. static const double gamma_integral[NGAMMA_INTEGRAL] = {
  289. 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
  290. 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
  291. 1307674368000.0, 20922789888000.0, 355687428096000.0,
  292. 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
  293. 51090942171709440000.0, 1124000727777607680000.0,
  294. };
  295. /* Lanczos' sum L_g(x), for positive x */
  296. static double
  297. lanczos_sum(double x)
  298. {
  299. double num = 0.0, den = 0.0;
  300. int i;
  301. assert(x > 0.0);
  302. /* evaluate the rational function lanczos_sum(x). For large
  303. x, the obvious algorithm risks overflow, so we instead
  304. rescale the denominator and numerator of the rational
  305. function by x**(1-LANCZOS_N) and treat this as a
  306. rational function in 1/x. This also reduces the error for
  307. larger x values. The choice of cutoff point (5.0 below) is
  308. somewhat arbitrary; in tests, smaller cutoff values than
  309. this resulted in lower accuracy. */
  310. if (x < 5.0) {
  311. for (i = LANCZOS_N; --i >= 0; ) {
  312. num = num * x + lanczos_num_coeffs[i];
  313. den = den * x + lanczos_den_coeffs[i];
  314. }
  315. }
  316. else {
  317. for (i = 0; i < LANCZOS_N; i++) {
  318. num = num / x + lanczos_num_coeffs[i];
  319. den = den / x + lanczos_den_coeffs[i];
  320. }
  321. }
  322. return num/den;
  323. }
  324. static double
  325. m_tgamma(double x)
  326. {
  327. double absx, r, y, z, sqrtpow;
  328. /* special cases */
  329. if (!Py_IS_FINITE(x)) {
  330. if (Py_IS_NAN(x) || x > 0.0)
  331. return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
  332. else {
  333. errno = EDOM;
  334. return Py_NAN; /* tgamma(-inf) = nan, invalid */
  335. }
  336. }
  337. if (x == 0.0) {
  338. errno = EDOM;
  339. /* tgamma(+-0.0) = +-inf, divide-by-zero */
  340. return copysign(Py_INFINITY, x);
  341. }
  342. /* integer arguments */
  343. if (x == floor(x)) {
  344. if (x < 0.0) {
  345. errno = EDOM; /* tgamma(n) = nan, invalid for */
  346. return Py_NAN; /* negative integers n */
  347. }
  348. if (x <= NGAMMA_INTEGRAL)
  349. return gamma_integral[(int)x - 1];
  350. }
  351. absx = fabs(x);
  352. /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
  353. if (absx < 1e-20) {
  354. r = 1.0/x;
  355. if (Py_IS_INFINITY(r))
  356. errno = ERANGE;
  357. return r;
  358. }
  359. /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
  360. x > 200, and underflows to +-0.0 for x < -200, not a negative
  361. integer. */
  362. if (absx > 200.0) {
  363. if (x < 0.0) {
  364. return 0.0/m_sinpi(x);
  365. }
  366. else {
  367. errno = ERANGE;
  368. return Py_HUGE_VAL;
  369. }
  370. }
  371. y = absx + lanczos_g_minus_half;
  372. /* compute error in sum */
  373. if (absx > lanczos_g_minus_half) {
  374. /* note: the correction can be foiled by an optimizing
  375. compiler that (incorrectly) thinks that an expression like
  376. a + b - a - b can be optimized to 0.0. This shouldn't
  377. happen in a standards-conforming compiler. */
  378. double q = y - absx;
  379. z = q - lanczos_g_minus_half;
  380. }
  381. else {
  382. double q = y - lanczos_g_minus_half;
  383. z = q - absx;
  384. }
  385. z = z * lanczos_g / y;
  386. if (x < 0.0) {
  387. r = -pi / m_sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
  388. r -= z * r;
  389. if (absx < 140.0) {
  390. r /= pow(y, absx - 0.5);
  391. }
  392. else {
  393. sqrtpow = pow(y, absx / 2.0 - 0.25);
  394. r /= sqrtpow;
  395. r /= sqrtpow;
  396. }
  397. }
  398. else {
  399. r = lanczos_sum(absx) / exp(y);
  400. r += z * r;
  401. if (absx < 140.0) {
  402. r *= pow(y, absx - 0.5);
  403. }
  404. else {
  405. sqrtpow = pow(y, absx / 2.0 - 0.25);
  406. r *= sqrtpow;
  407. r *= sqrtpow;
  408. }
  409. }
  410. if (Py_IS_INFINITY(r))
  411. errno = ERANGE;
  412. return r;
  413. }
  414. /*
  415. lgamma: natural log of the absolute value of the Gamma function.
  416. For large arguments, Lanczos' formula works extremely well here.
  417. */
  418. static double
  419. m_lgamma(double x)
  420. {
  421. double r;
  422. double absx;
  423. /* special cases */
  424. if (!Py_IS_FINITE(x)) {
  425. if (Py_IS_NAN(x))
  426. return x; /* lgamma(nan) = nan */
  427. else
  428. return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
  429. }
  430. /* integer arguments */
  431. if (x == floor(x) && x <= 2.0) {
  432. if (x <= 0.0) {
  433. errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
  434. return Py_HUGE_VAL; /* integers n <= 0 */
  435. }
  436. else {
  437. return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
  438. }
  439. }
  440. absx = fabs(x);
  441. /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
  442. if (absx < 1e-20)
  443. return -log(absx);
  444. /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
  445. having a second set of numerator coefficients for lanczos_sum that
  446. absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
  447. subtraction below; it's probably not worth it. */
  448. r = log(lanczos_sum(absx)) - lanczos_g;
  449. r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
  450. if (x < 0.0)
  451. /* Use reflection formula to get value for negative x. */
  452. r = logpi - log(fabs(m_sinpi(absx))) - log(absx) - r;
  453. if (Py_IS_INFINITY(r))
  454. errno = ERANGE;
  455. return r;
  456. }
  457. /*
  458. wrapper for atan2 that deals directly with special cases before
  459. delegating to the platform libm for the remaining cases. This
  460. is necessary to get consistent behaviour across platforms.
  461. Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
  462. always follow C99.
  463. */
  464. static double
  465. m_atan2(double y, double x)
  466. {
  467. if (Py_IS_NAN(x) || Py_IS_NAN(y))
  468. return Py_NAN;
  469. if (Py_IS_INFINITY(y)) {
  470. if (Py_IS_INFINITY(x)) {
  471. if (copysign(1., x) == 1.)
  472. /* atan2(+-inf, +inf) == +-pi/4 */
  473. return copysign(0.25*Py_MATH_PI, y);
  474. else
  475. /* atan2(+-inf, -inf) == +-pi*3/4 */
  476. return copysign(0.75*Py_MATH_PI, y);
  477. }
  478. /* atan2(+-inf, x) == +-pi/2 for finite x */
  479. return copysign(0.5*Py_MATH_PI, y);
  480. }
  481. if (Py_IS_INFINITY(x) || y == 0.) {
  482. if (copysign(1., x) == 1.)
  483. /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
  484. return copysign(0., y);
  485. else
  486. /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
  487. return copysign(Py_MATH_PI, y);
  488. }
  489. return atan2(y, x);
  490. }
  491. /* IEEE 754-style remainder operation: x - n*y where n*y is the nearest
  492. multiple of y to x, taking n even in the case of a tie. Assuming an IEEE 754
  493. binary floating-point format, the result is always exact. */
  494. static double
  495. m_remainder(double x, double y)
  496. {
  497. /* Deal with most common case first. */
  498. if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) {
  499. double absx, absy, c, m, r;
  500. if (y == 0.0) {
  501. return Py_NAN;
  502. }
  503. absx = fabs(x);
  504. absy = fabs(y);
  505. m = fmod(absx, absy);
  506. /*
  507. Warning: some subtlety here. What we *want* to know at this point is
  508. whether the remainder m is less than, equal to, or greater than half
  509. of absy. However, we can't do that comparison directly because we
  510. can't be sure that 0.5*absy is representable (the multiplication
  511. might incur precision loss due to underflow). So instead we compare
  512. m with the complement c = absy - m: m < 0.5*absy if and only if m <
  513. c, and so on. The catch is that absy - m might also not be
  514. representable, but it turns out that it doesn't matter:
  515. - if m > 0.5*absy then absy - m is exactly representable, by
  516. Sterbenz's lemma, so m > c
  517. - if m == 0.5*absy then again absy - m is exactly representable
  518. and m == c
  519. - if m < 0.5*absy then either (i) 0.5*absy is exactly representable,
  520. in which case 0.5*absy < absy - m, so 0.5*absy <= c and hence m <
  521. c, or (ii) absy is tiny, either subnormal or in the lowest normal
  522. binade. Then absy - m is exactly representable and again m < c.
  523. */
  524. c = absy - m;
  525. if (m < c) {
  526. r = m;
  527. }
  528. else if (m > c) {
  529. r = -c;
  530. }
  531. else {
  532. /*
  533. Here absx is exactly halfway between two multiples of absy,
  534. and we need to choose the even multiple. x now has the form
  535. absx = n * absy + m
  536. for some integer n (recalling that m = 0.5*absy at this point).
  537. If n is even we want to return m; if n is odd, we need to
  538. return -m.
  539. So
  540. 0.5 * (absx - m) = (n/2) * absy
  541. and now reducing modulo absy gives us:
  542. | m, if n is odd
  543. fmod(0.5 * (absx - m), absy) = |
  544. | 0, if n is even
  545. Now m - 2.0 * fmod(...) gives the desired result: m
  546. if n is even, -m if m is odd.
  547. Note that all steps in fmod(0.5 * (absx - m), absy)
  548. will be computed exactly, with no rounding error
  549. introduced.
  550. */
  551. assert(m == c);
  552. r = m - 2.0 * fmod(0.5 * (absx - m), absy);
  553. }
  554. return copysign(1.0, x) * r;
  555. }
  556. /* Special values. */
  557. if (Py_IS_NAN(x)) {
  558. return x;
  559. }
  560. if (Py_IS_NAN(y)) {
  561. return y;
  562. }
  563. if (Py_IS_INFINITY(x)) {
  564. return Py_NAN;
  565. }
  566. assert(Py_IS_INFINITY(y));
  567. return x;
  568. }
  569. /*
  570. Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
  571. log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
  572. special values directly, passing positive non-special values through to
  573. the system log/log10.
  574. */
  575. static double
  576. m_log(double x)
  577. {
  578. if (Py_IS_FINITE(x)) {
  579. if (x > 0.0)
  580. return log(x);
  581. errno = EDOM;
  582. if (x == 0.0)
  583. return -Py_HUGE_VAL; /* log(0) = -inf */
  584. else
  585. return Py_NAN; /* log(-ve) = nan */
  586. }
  587. else if (Py_IS_NAN(x))
  588. return x; /* log(nan) = nan */
  589. else if (x > 0.0)
  590. return x; /* log(inf) = inf */
  591. else {
  592. errno = EDOM;
  593. return Py_NAN; /* log(-inf) = nan */
  594. }
  595. }
  596. /*
  597. log2: log to base 2.
  598. Uses an algorithm that should:
  599. (a) produce exact results for powers of 2, and
  600. (b) give a monotonic log2 (for positive finite floats),
  601. assuming that the system log is monotonic.
  602. */
  603. static double
  604. m_log2(double x)
  605. {
  606. if (!Py_IS_FINITE(x)) {
  607. if (Py_IS_NAN(x))
  608. return x; /* log2(nan) = nan */
  609. else if (x > 0.0)
  610. return x; /* log2(+inf) = +inf */
  611. else {
  612. errno = EDOM;
  613. return Py_NAN; /* log2(-inf) = nan, invalid-operation */
  614. }
  615. }
  616. if (x > 0.0) {
  617. return log2(x);
  618. }
  619. else if (x == 0.0) {
  620. errno = EDOM;
  621. return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
  622. }
  623. else {
  624. errno = EDOM;
  625. return Py_NAN; /* log2(-inf) = nan, invalid-operation */
  626. }
  627. }
  628. static double
  629. m_log10(double x)
  630. {
  631. if (Py_IS_FINITE(x)) {
  632. if (x > 0.0)
  633. return log10(x);
  634. errno = EDOM;
  635. if (x == 0.0)
  636. return -Py_HUGE_VAL; /* log10(0) = -inf */
  637. else
  638. return Py_NAN; /* log10(-ve) = nan */
  639. }
  640. else if (Py_IS_NAN(x))
  641. return x; /* log10(nan) = nan */
  642. else if (x > 0.0)
  643. return x; /* log10(inf) = inf */
  644. else {
  645. errno = EDOM;
  646. return Py_NAN; /* log10(-inf) = nan */
  647. }
  648. }
  649. static PyObject *
  650. math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
  651. {
  652. PyObject *res, *x;
  653. Py_ssize_t i;
  654. if (nargs == 0) {
  655. return PyLong_FromLong(0);
  656. }
  657. res = PyNumber_Index(args[0]);
  658. if (res == NULL) {
  659. return NULL;
  660. }
  661. if (nargs == 1) {
  662. Py_SETREF(res, PyNumber_Absolute(res));
  663. return res;
  664. }
  665. PyObject *one = _PyLong_GetOne(); // borrowed ref
  666. for (i = 1; i < nargs; i++) {
  667. x = _PyNumber_Index(args[i]);
  668. if (x == NULL) {
  669. Py_DECREF(res);
  670. return NULL;
  671. }
  672. if (res == one) {
  673. /* Fast path: just check arguments.
  674. It is okay to use identity comparison here. */
  675. Py_DECREF(x);
  676. continue;
  677. }
  678. Py_SETREF(res, _PyLong_GCD(res, x));
  679. Py_DECREF(x);
  680. if (res == NULL) {
  681. return NULL;
  682. }
  683. }
  684. return res;
  685. }
  686. PyDoc_STRVAR(math_gcd_doc,
  687. "gcd($module, *integers)\n"
  688. "--\n"
  689. "\n"
  690. "Greatest Common Divisor.");
  691. static PyObject *
  692. long_lcm(PyObject *a, PyObject *b)
  693. {
  694. PyObject *g, *m, *f, *ab;
  695. if (_PyLong_IsZero((PyLongObject *)a) || _PyLong_IsZero((PyLongObject *)b)) {
  696. return PyLong_FromLong(0);
  697. }
  698. g = _PyLong_GCD(a, b);
  699. if (g == NULL) {
  700. return NULL;
  701. }
  702. f = PyNumber_FloorDivide(a, g);
  703. Py_DECREF(g);
  704. if (f == NULL) {
  705. return NULL;
  706. }
  707. m = PyNumber_Multiply(f, b);
  708. Py_DECREF(f);
  709. if (m == NULL) {
  710. return NULL;
  711. }
  712. ab = PyNumber_Absolute(m);
  713. Py_DECREF(m);
  714. return ab;
  715. }
  716. static PyObject *
  717. math_lcm(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
  718. {
  719. PyObject *res, *x;
  720. Py_ssize_t i;
  721. if (nargs == 0) {
  722. return PyLong_FromLong(1);
  723. }
  724. res = PyNumber_Index(args[0]);
  725. if (res == NULL) {
  726. return NULL;
  727. }
  728. if (nargs == 1) {
  729. Py_SETREF(res, PyNumber_Absolute(res));
  730. return res;
  731. }
  732. PyObject *zero = _PyLong_GetZero(); // borrowed ref
  733. for (i = 1; i < nargs; i++) {
  734. x = PyNumber_Index(args[i]);
  735. if (x == NULL) {
  736. Py_DECREF(res);
  737. return NULL;
  738. }
  739. if (res == zero) {
  740. /* Fast path: just check arguments.
  741. It is okay to use identity comparison here. */
  742. Py_DECREF(x);
  743. continue;
  744. }
  745. Py_SETREF(res, long_lcm(res, x));
  746. Py_DECREF(x);
  747. if (res == NULL) {
  748. return NULL;
  749. }
  750. }
  751. return res;
  752. }
  753. PyDoc_STRVAR(math_lcm_doc,
  754. "lcm($module, *integers)\n"
  755. "--\n"
  756. "\n"
  757. "Least Common Multiple.");
  758. /* Call is_error when errno != 0, and where x is the result libm
  759. * returned. is_error will usually set up an exception and return
  760. * true (1), but may return false (0) without setting up an exception.
  761. */
  762. static int
  763. is_error(double x)
  764. {
  765. int result = 1; /* presumption of guilt */
  766. assert(errno); /* non-zero errno is a precondition for calling */
  767. if (errno == EDOM)
  768. PyErr_SetString(PyExc_ValueError, "math domain error");
  769. else if (errno == ERANGE) {
  770. /* ANSI C generally requires libm functions to set ERANGE
  771. * on overflow, but also generally *allows* them to set
  772. * ERANGE on underflow too. There's no consistency about
  773. * the latter across platforms.
  774. * Alas, C99 never requires that errno be set.
  775. * Here we suppress the underflow errors (libm functions
  776. * should return a zero on underflow, and +- HUGE_VAL on
  777. * overflow, so testing the result for zero suffices to
  778. * distinguish the cases).
  779. *
  780. * On some platforms (Ubuntu/ia64) it seems that errno can be
  781. * set to ERANGE for subnormal results that do *not* underflow
  782. * to zero. So to be safe, we'll ignore ERANGE whenever the
  783. * function result is less than 1.5 in absolute value.
  784. *
  785. * bpo-46018: Changed to 1.5 to ensure underflows in expm1()
  786. * are correctly detected, since the function may underflow
  787. * toward -1.0 rather than 0.0.
  788. */
  789. if (fabs(x) < 1.5)
  790. result = 0;
  791. else
  792. PyErr_SetString(PyExc_OverflowError,
  793. "math range error");
  794. }
  795. else
  796. /* Unexpected math error */
  797. PyErr_SetFromErrno(PyExc_ValueError);
  798. return result;
  799. }
  800. /*
  801. math_1 is used to wrap a libm function f that takes a double
  802. argument and returns a double.
  803. The error reporting follows these rules, which are designed to do
  804. the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
  805. platforms.
  806. - a NaN result from non-NaN inputs causes ValueError to be raised
  807. - an infinite result from finite inputs causes OverflowError to be
  808. raised if can_overflow is 1, or raises ValueError if can_overflow
  809. is 0.
  810. - if the result is finite and errno == EDOM then ValueError is
  811. raised
  812. - if the result is finite and nonzero and errno == ERANGE then
  813. OverflowError is raised
  814. The last rule is used to catch overflow on platforms which follow
  815. C89 but for which HUGE_VAL is not an infinity.
  816. For the majority of one-argument functions these rules are enough
  817. to ensure that Python's functions behave as specified in 'Annex F'
  818. of the C99 standard, with the 'invalid' and 'divide-by-zero'
  819. floating-point exceptions mapping to Python's ValueError and the
  820. 'overflow' floating-point exception mapping to OverflowError.
  821. math_1 only works for functions that don't have singularities *and*
  822. the possibility of overflow; fortunately, that covers everything we
  823. care about right now.
  824. */
  825. static PyObject *
  826. math_1(PyObject *arg, double (*func) (double), int can_overflow)
  827. {
  828. double x, r;
  829. x = PyFloat_AsDouble(arg);
  830. if (x == -1.0 && PyErr_Occurred())
  831. return NULL;
  832. errno = 0;
  833. r = (*func)(x);
  834. if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
  835. PyErr_SetString(PyExc_ValueError,
  836. "math domain error"); /* invalid arg */
  837. return NULL;
  838. }
  839. if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
  840. if (can_overflow)
  841. PyErr_SetString(PyExc_OverflowError,
  842. "math range error"); /* overflow */
  843. else
  844. PyErr_SetString(PyExc_ValueError,
  845. "math domain error"); /* singularity */
  846. return NULL;
  847. }
  848. if (Py_IS_FINITE(r) && errno && is_error(r))
  849. /* this branch unnecessary on most platforms */
  850. return NULL;
  851. return PyFloat_FromDouble(r);
  852. }
  853. /* variant of math_1, to be used when the function being wrapped is known to
  854. set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
  855. errno = ERANGE for overflow). */
  856. static PyObject *
  857. math_1a(PyObject *arg, double (*func) (double))
  858. {
  859. double x, r;
  860. x = PyFloat_AsDouble(arg);
  861. if (x == -1.0 && PyErr_Occurred())
  862. return NULL;
  863. errno = 0;
  864. r = (*func)(x);
  865. if (errno && is_error(r))
  866. return NULL;
  867. return PyFloat_FromDouble(r);
  868. }
  869. /*
  870. math_2 is used to wrap a libm function f that takes two double
  871. arguments and returns a double.
  872. The error reporting follows these rules, which are designed to do
  873. the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
  874. platforms.
  875. - a NaN result from non-NaN inputs causes ValueError to be raised
  876. - an infinite result from finite inputs causes OverflowError to be
  877. raised.
  878. - if the result is finite and errno == EDOM then ValueError is
  879. raised
  880. - if the result is finite and nonzero and errno == ERANGE then
  881. OverflowError is raised
  882. The last rule is used to catch overflow on platforms which follow
  883. C89 but for which HUGE_VAL is not an infinity.
  884. For most two-argument functions (copysign, fmod, hypot, atan2)
  885. these rules are enough to ensure that Python's functions behave as
  886. specified in 'Annex F' of the C99 standard, with the 'invalid' and
  887. 'divide-by-zero' floating-point exceptions mapping to Python's
  888. ValueError and the 'overflow' floating-point exception mapping to
  889. OverflowError.
  890. */
  891. static PyObject *
  892. math_2(PyObject *const *args, Py_ssize_t nargs,
  893. double (*func) (double, double), const char *funcname)
  894. {
  895. double x, y, r;
  896. if (!_PyArg_CheckPositional(funcname, nargs, 2, 2))
  897. return NULL;
  898. x = PyFloat_AsDouble(args[0]);
  899. if (x == -1.0 && PyErr_Occurred()) {
  900. return NULL;
  901. }
  902. y = PyFloat_AsDouble(args[1]);
  903. if (y == -1.0 && PyErr_Occurred()) {
  904. return NULL;
  905. }
  906. errno = 0;
  907. r = (*func)(x, y);
  908. if (Py_IS_NAN(r)) {
  909. if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
  910. errno = EDOM;
  911. else
  912. errno = 0;
  913. }
  914. else if (Py_IS_INFINITY(r)) {
  915. if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
  916. errno = ERANGE;
  917. else
  918. errno = 0;
  919. }
  920. if (errno && is_error(r))
  921. return NULL;
  922. else
  923. return PyFloat_FromDouble(r);
  924. }
  925. #define FUNC1(funcname, func, can_overflow, docstring) \
  926. static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
  927. return math_1(args, func, can_overflow); \
  928. }\
  929. PyDoc_STRVAR(math_##funcname##_doc, docstring);
  930. #define FUNC1A(funcname, func, docstring) \
  931. static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
  932. return math_1a(args, func); \
  933. }\
  934. PyDoc_STRVAR(math_##funcname##_doc, docstring);
  935. #define FUNC2(funcname, func, docstring) \
  936. static PyObject * math_##funcname(PyObject *self, PyObject *const *args, Py_ssize_t nargs) { \
  937. return math_2(args, nargs, func, #funcname); \
  938. }\
  939. PyDoc_STRVAR(math_##funcname##_doc, docstring);
  940. FUNC1(acos, acos, 0,
  941. "acos($module, x, /)\n--\n\n"
  942. "Return the arc cosine (measured in radians) of x.\n\n"
  943. "The result is between 0 and pi.")
  944. FUNC1(acosh, acosh, 0,
  945. "acosh($module, x, /)\n--\n\n"
  946. "Return the inverse hyperbolic cosine of x.")
  947. FUNC1(asin, asin, 0,
  948. "asin($module, x, /)\n--\n\n"
  949. "Return the arc sine (measured in radians) of x.\n\n"
  950. "The result is between -pi/2 and pi/2.")
  951. FUNC1(asinh, asinh, 0,
  952. "asinh($module, x, /)\n--\n\n"
  953. "Return the inverse hyperbolic sine of x.")
  954. FUNC1(atan, atan, 0,
  955. "atan($module, x, /)\n--\n\n"
  956. "Return the arc tangent (measured in radians) of x.\n\n"
  957. "The result is between -pi/2 and pi/2.")
  958. FUNC2(atan2, m_atan2,
  959. "atan2($module, y, x, /)\n--\n\n"
  960. "Return the arc tangent (measured in radians) of y/x.\n\n"
  961. "Unlike atan(y/x), the signs of both x and y are considered.")
  962. FUNC1(atanh, atanh, 0,
  963. "atanh($module, x, /)\n--\n\n"
  964. "Return the inverse hyperbolic tangent of x.")
  965. FUNC1(cbrt, cbrt, 0,
  966. "cbrt($module, x, /)\n--\n\n"
  967. "Return the cube root of x.")
  968. /*[clinic input]
  969. math.ceil
  970. x as number: object
  971. /
  972. Return the ceiling of x as an Integral.
  973. This is the smallest integer >= x.
  974. [clinic start generated code]*/
  975. static PyObject *
  976. math_ceil(PyObject *module, PyObject *number)
  977. /*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
  978. {
  979. if (!PyFloat_CheckExact(number)) {
  980. math_module_state *state = get_math_module_state(module);
  981. PyObject *method = _PyObject_LookupSpecial(number, state->str___ceil__);
  982. if (method != NULL) {
  983. PyObject *result = _PyObject_CallNoArgs(method);
  984. Py_DECREF(method);
  985. return result;
  986. }
  987. if (PyErr_Occurred())
  988. return NULL;
  989. }
  990. double x = PyFloat_AsDouble(number);
  991. if (x == -1.0 && PyErr_Occurred())
  992. return NULL;
  993. return PyLong_FromDouble(ceil(x));
  994. }
  995. FUNC2(copysign, copysign,
  996. "copysign($module, x, y, /)\n--\n\n"
  997. "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
  998. "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
  999. "returns -1.0.\n")
  1000. FUNC1(cos, cos, 0,
  1001. "cos($module, x, /)\n--\n\n"
  1002. "Return the cosine of x (measured in radians).")
  1003. FUNC1(cosh, cosh, 1,
  1004. "cosh($module, x, /)\n--\n\n"
  1005. "Return the hyperbolic cosine of x.")
  1006. FUNC1A(erf, erf,
  1007. "erf($module, x, /)\n--\n\n"
  1008. "Error function at x.")
  1009. FUNC1A(erfc, erfc,
  1010. "erfc($module, x, /)\n--\n\n"
  1011. "Complementary error function at x.")
  1012. FUNC1(exp, exp, 1,
  1013. "exp($module, x, /)\n--\n\n"
  1014. "Return e raised to the power of x.")
  1015. FUNC1(exp2, exp2, 1,
  1016. "exp2($module, x, /)\n--\n\n"
  1017. "Return 2 raised to the power of x.")
  1018. FUNC1(expm1, expm1, 1,
  1019. "expm1($module, x, /)\n--\n\n"
  1020. "Return exp(x)-1.\n\n"
  1021. "This function avoids the loss of precision involved in the direct "
  1022. "evaluation of exp(x)-1 for small x.")
  1023. FUNC1(fabs, fabs, 0,
  1024. "fabs($module, x, /)\n--\n\n"
  1025. "Return the absolute value of the float x.")
  1026. /*[clinic input]
  1027. math.floor
  1028. x as number: object
  1029. /
  1030. Return the floor of x as an Integral.
  1031. This is the largest integer <= x.
  1032. [clinic start generated code]*/
  1033. static PyObject *
  1034. math_floor(PyObject *module, PyObject *number)
  1035. /*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
  1036. {
  1037. double x;
  1038. if (PyFloat_CheckExact(number)) {
  1039. x = PyFloat_AS_DOUBLE(number);
  1040. }
  1041. else
  1042. {
  1043. math_module_state *state = get_math_module_state(module);
  1044. PyObject *method = _PyObject_LookupSpecial(number, state->str___floor__);
  1045. if (method != NULL) {
  1046. PyObject *result = _PyObject_CallNoArgs(method);
  1047. Py_DECREF(method);
  1048. return result;
  1049. }
  1050. if (PyErr_Occurred())
  1051. return NULL;
  1052. x = PyFloat_AsDouble(number);
  1053. if (x == -1.0 && PyErr_Occurred())
  1054. return NULL;
  1055. }
  1056. return PyLong_FromDouble(floor(x));
  1057. }
  1058. FUNC1A(gamma, m_tgamma,
  1059. "gamma($module, x, /)\n--\n\n"
  1060. "Gamma function at x.")
  1061. FUNC1A(lgamma, m_lgamma,
  1062. "lgamma($module, x, /)\n--\n\n"
  1063. "Natural logarithm of absolute value of Gamma function at x.")
  1064. FUNC1(log1p, m_log1p, 0,
  1065. "log1p($module, x, /)\n--\n\n"
  1066. "Return the natural logarithm of 1+x (base e).\n\n"
  1067. "The result is computed in a way which is accurate for x near zero.")
  1068. FUNC2(remainder, m_remainder,
  1069. "remainder($module, x, y, /)\n--\n\n"
  1070. "Difference between x and the closest integer multiple of y.\n\n"
  1071. "Return x - n*y where n*y is the closest integer multiple of y.\n"
  1072. "In the case where x is exactly halfway between two multiples of\n"
  1073. "y, the nearest even value of n is used. The result is always exact.")
  1074. FUNC1(sin, sin, 0,
  1075. "sin($module, x, /)\n--\n\n"
  1076. "Return the sine of x (measured in radians).")
  1077. FUNC1(sinh, sinh, 1,
  1078. "sinh($module, x, /)\n--\n\n"
  1079. "Return the hyperbolic sine of x.")
  1080. FUNC1(sqrt, sqrt, 0,
  1081. "sqrt($module, x, /)\n--\n\n"
  1082. "Return the square root of x.")
  1083. FUNC1(tan, tan, 0,
  1084. "tan($module, x, /)\n--\n\n"
  1085. "Return the tangent of x (measured in radians).")
  1086. FUNC1(tanh, tanh, 0,
  1087. "tanh($module, x, /)\n--\n\n"
  1088. "Return the hyperbolic tangent of x.")
  1089. /* Precision summation function as msum() by Raymond Hettinger in
  1090. <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
  1091. enhanced with the exact partials sum and roundoff from Mark
  1092. Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
  1093. See those links for more details, proofs and other references.
  1094. Note 1: IEEE 754 floating-point semantics with a rounding mode of
  1095. roundTiesToEven are assumed.
  1096. Note 2: No provision is made for intermediate overflow handling;
  1097. therefore, fsum([1e+308, -1e+308, 1e+308]) returns 1e+308 while
  1098. fsum([1e+308, 1e+308, -1e+308]) raises an OverflowError due to the
  1099. overflow of the first partial sum.
  1100. Note 3: The algorithm has two potential sources of fragility. First, C
  1101. permits arithmetic operations on `double`s to be performed in an
  1102. intermediate format whose range and precision may be greater than those of
  1103. `double` (see for example C99 §5.2.4.2.2, paragraph 8). This can happen for
  1104. example on machines using the now largely historical x87 FPUs. In this case,
  1105. `fsum` can produce incorrect results. If `FLT_EVAL_METHOD` is `0` or `1`, or
  1106. `FLT_EVAL_METHOD` is `2` and `long double` is identical to `double`, then we
  1107. should be safe from this source of errors. Second, an aggressively
  1108. optimizing compiler can re-associate operations so that (for example) the
  1109. statement `yr = hi - x;` is treated as `yr = (x + y) - x` and then
  1110. re-associated as `yr = y + (x - x)`, giving `y = yr` and `lo = 0.0`. That
  1111. re-association would be in violation of the C standard, and should not occur
  1112. except possibly in the presence of unsafe optimizations (e.g., -ffast-math,
  1113. -fassociative-math). Such optimizations should be avoided for this module.
  1114. Note 4: The signature of math.fsum() differs from builtins.sum()
  1115. because the start argument doesn't make sense in the context of
  1116. accurate summation. Since the partials table is collapsed before
  1117. returning a result, sum(seq2, start=sum(seq1)) may not equal the
  1118. accurate result returned by sum(itertools.chain(seq1, seq2)).
  1119. */
  1120. #define NUM_PARTIALS 32 /* initial partials array size, on stack */
  1121. /* Extend the partials array p[] by doubling its size. */
  1122. static int /* non-zero on error */
  1123. _fsum_realloc(double **p_ptr, Py_ssize_t n,
  1124. double *ps, Py_ssize_t *m_ptr)
  1125. {
  1126. void *v = NULL;
  1127. Py_ssize_t m = *m_ptr;
  1128. m += m; /* double */
  1129. if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
  1130. double *p = *p_ptr;
  1131. if (p == ps) {
  1132. v = PyMem_Malloc(sizeof(double) * m);
  1133. if (v != NULL)
  1134. memcpy(v, ps, sizeof(double) * n);
  1135. }
  1136. else
  1137. v = PyMem_Realloc(p, sizeof(double) * m);
  1138. }
  1139. if (v == NULL) { /* size overflow or no memory */
  1140. PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
  1141. return 1;
  1142. }
  1143. *p_ptr = (double*) v;
  1144. *m_ptr = m;
  1145. return 0;
  1146. }
  1147. /* Full precision summation of a sequence of floats.
  1148. def msum(iterable):
  1149. partials = [] # sorted, non-overlapping partial sums
  1150. for x in iterable:
  1151. i = 0
  1152. for y in partials:
  1153. if abs(x) < abs(y):
  1154. x, y = y, x
  1155. hi = x + y
  1156. lo = y - (hi - x)
  1157. if lo:
  1158. partials[i] = lo
  1159. i += 1
  1160. x = hi
  1161. partials[i:] = [x]
  1162. return sum_exact(partials)
  1163. Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
  1164. are exactly equal to x+y. The inner loop applies hi/lo summation to each
  1165. partial so that the list of partial sums remains exact.
  1166. Sum_exact() adds the partial sums exactly and correctly rounds the final
  1167. result (using the round-half-to-even rule). The items in partials remain
  1168. non-zero, non-special, non-overlapping and strictly increasing in
  1169. magnitude, but possibly not all having the same sign.
  1170. Depends on IEEE 754 arithmetic guarantees and half-even rounding.
  1171. */
  1172. /*[clinic input]
  1173. math.fsum
  1174. seq: object
  1175. /
  1176. Return an accurate floating point sum of values in the iterable seq.
  1177. Assumes IEEE-754 floating point arithmetic.
  1178. [clinic start generated code]*/
  1179. static PyObject *
  1180. math_fsum(PyObject *module, PyObject *seq)
  1181. /*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
  1182. {
  1183. PyObject *item, *iter, *sum = NULL;
  1184. Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
  1185. double x, y, t, ps[NUM_PARTIALS], *p = ps;
  1186. double xsave, special_sum = 0.0, inf_sum = 0.0;
  1187. double hi, yr, lo = 0.0;
  1188. iter = PyObject_GetIter(seq);
  1189. if (iter == NULL)
  1190. return NULL;
  1191. for(;;) { /* for x in iterable */
  1192. assert(0 <= n && n <= m);
  1193. assert((m == NUM_PARTIALS && p == ps) ||
  1194. (m > NUM_PARTIALS && p != NULL));
  1195. item = PyIter_Next(iter);
  1196. if (item == NULL) {
  1197. if (PyErr_Occurred())
  1198. goto _fsum_error;
  1199. break;
  1200. }
  1201. ASSIGN_DOUBLE(x, item, error_with_item);
  1202. Py_DECREF(item);
  1203. xsave = x;
  1204. for (i = j = 0; j < n; j++) { /* for y in partials */
  1205. y = p[j];
  1206. if (fabs(x) < fabs(y)) {
  1207. t = x; x = y; y = t;
  1208. }
  1209. hi = x + y;
  1210. yr = hi - x;
  1211. lo = y - yr;
  1212. if (lo != 0.0)
  1213. p[i++] = lo;
  1214. x = hi;
  1215. }
  1216. n = i; /* ps[i:] = [x] */
  1217. if (x != 0.0) {
  1218. if (! Py_IS_FINITE(x)) {
  1219. /* a nonfinite x could arise either as
  1220. a result of intermediate overflow, or
  1221. as a result of a nan or inf in the
  1222. summands */
  1223. if (Py_IS_FINITE(xsave)) {
  1224. PyErr_SetString(PyExc_OverflowError,
  1225. "intermediate overflow in fsum");
  1226. goto _fsum_error;
  1227. }
  1228. if (Py_IS_INFINITY(xsave))
  1229. inf_sum += xsave;
  1230. special_sum += xsave;
  1231. /* reset partials */
  1232. n = 0;
  1233. }
  1234. else if (n >= m && _fsum_realloc(&p, n, ps, &m))
  1235. goto _fsum_error;
  1236. else
  1237. p[n++] = x;
  1238. }
  1239. }
  1240. if (special_sum != 0.0) {
  1241. if (Py_IS_NAN(inf_sum))
  1242. PyErr_SetString(PyExc_ValueError,
  1243. "-inf + inf in fsum");
  1244. else
  1245. sum = PyFloat_FromDouble(special_sum);
  1246. goto _fsum_error;
  1247. }
  1248. hi = 0.0;
  1249. if (n > 0) {
  1250. hi = p[--n];
  1251. /* sum_exact(ps, hi) from the top, stop when the sum becomes
  1252. inexact. */
  1253. while (n > 0) {
  1254. x = hi;
  1255. y = p[--n];
  1256. assert(fabs(y) < fabs(x));
  1257. hi = x + y;
  1258. yr = hi - x;
  1259. lo = y - yr;
  1260. if (lo != 0.0)
  1261. break;
  1262. }
  1263. /* Make half-even rounding work across multiple partials.
  1264. Needed so that sum([1e-16, 1, 1e16]) will round-up the last
  1265. digit to two instead of down to zero (the 1e-16 makes the 1
  1266. slightly closer to two). With a potential 1 ULP rounding
  1267. error fixed-up, math.fsum() can guarantee commutativity. */
  1268. if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
  1269. (lo > 0.0 && p[n-1] > 0.0))) {
  1270. y = lo * 2.0;
  1271. x = hi + y;
  1272. yr = x - hi;
  1273. if (y == yr)
  1274. hi = x;
  1275. }
  1276. }
  1277. sum = PyFloat_FromDouble(hi);
  1278. _fsum_error:
  1279. Py_DECREF(iter);
  1280. if (p != ps)
  1281. PyMem_Free(p);
  1282. return sum;
  1283. error_with_item:
  1284. Py_DECREF(item);
  1285. goto _fsum_error;
  1286. }
  1287. #undef NUM_PARTIALS
  1288. static unsigned long
  1289. count_set_bits(unsigned long n)
  1290. {
  1291. unsigned long count = 0;
  1292. while (n != 0) {
  1293. ++count;
  1294. n &= n - 1; /* clear least significant bit */
  1295. }
  1296. return count;
  1297. }
  1298. /* Integer square root
  1299. Given a nonnegative integer `n`, we want to compute the largest integer
  1300. `a` for which `a * a <= n`, or equivalently the integer part of the exact
  1301. square root of `n`.
  1302. We use an adaptive-precision pure-integer version of Newton's iteration. Given
  1303. a positive integer `n`, the algorithm produces at each iteration an integer
  1304. approximation `a` to the square root of `n >> s` for some even integer `s`,
  1305. with `s` decreasing as the iterations progress. On the final iteration, `s` is
  1306. zero and we have an approximation to the square root of `n` itself.
  1307. At every step, the approximation `a` is strictly within 1.0 of the true square
  1308. root, so we have
  1309. (a - 1)**2 < (n >> s) < (a + 1)**2
  1310. After the final iteration, a check-and-correct step is needed to determine
  1311. whether `a` or `a - 1` gives the desired integer square root of `n`.
  1312. The algorithm is remarkable in its simplicity. There's no need for a
  1313. per-iteration check-and-correct step, and termination is straightforward: the
  1314. number of iterations is known in advance (it's exactly `floor(log2(log2(n)))`
  1315. for `n > 1`). The only tricky part of the correctness proof is in establishing
  1316. that the bound `(a - 1)**2 < (n >> s) < (a + 1)**2` is maintained from one
  1317. iteration to the next. A sketch of the proof of this is given below.
  1318. In addition to the proof sketch, a formal, computer-verified proof
  1319. of correctness (using Lean) of an equivalent recursive algorithm can be found
  1320. here:
  1321. https://github.com/mdickinson/snippets/blob/master/proofs/isqrt/src/isqrt.lean
  1322. Here's Python code equivalent to the C implementation below:
  1323. def isqrt(n):
  1324. """
  1325. Return the integer part of the square root of the input.
  1326. """
  1327. n = operator.index(n)
  1328. if n < 0:
  1329. raise ValueError("isqrt() argument must be nonnegative")
  1330. if n == 0:
  1331. return 0
  1332. c = (n.bit_length() - 1) // 2
  1333. a = 1
  1334. d = 0
  1335. for s in reversed(range(c.bit_length())):
  1336. # Loop invariant: (a-1)**2 < (n >> 2*(c - d)) < (a+1)**2
  1337. e = d
  1338. d = c >> s
  1339. a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
  1340. return a - (a*a > n)
  1341. Sketch of proof of correctness
  1342. ------------------------------
  1343. The delicate part of the correctness proof is showing that the loop invariant
  1344. is preserved from one iteration to the next. That is, just before the line
  1345. a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
  1346. is executed in the above code, we know that
  1347. (1) (a - 1)**2 < (n >> 2*(c - e)) < (a + 1)**2.
  1348. (since `e` is always the value of `d` from the previous iteration). We must
  1349. prove that after that line is executed, we have
  1350. (a - 1)**2 < (n >> 2*(c - d)) < (a + 1)**2
  1351. To facilitate the proof, we make some changes of notation. Write `m` for
  1352. `n >> 2*(c-d)`, and write `b` for the new value of `a`, so
  1353. b = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
  1354. or equivalently:
  1355. (2) b = (a << d - e - 1) + (m >> d - e + 1) // a
  1356. Then we can rewrite (1) as:
  1357. (3) (a - 1)**2 < (m >> 2*(d - e)) < (a + 1)**2
  1358. and we must show that (b - 1)**2 < m < (b + 1)**2.
  1359. From this point on, we switch to mathematical notation, so `/` means exact
  1360. division rather than integer division and `^` is used for exponentiation. We
  1361. use the `√` symbol for the exact square root. In (3), we can remove the
  1362. implicit floor operation to give:
  1363. (4) (a - 1)^2 < m / 4^(d - e) < (a + 1)^2
  1364. Taking square roots throughout (4), scaling by `2^(d-e)`, and rearranging gives
  1365. (5) 0 <= | 2^(d-e)a - √m | < 2^(d-e)
  1366. Squaring and dividing through by `2^(d-e+1) a` gives
  1367. (6) 0 <= 2^(d-e-1) a + m / (2^(d-e+1) a) - √m < 2^(d-e-1) / a
  1368. We'll show below that `2^(d-e-1) <= a`. Given that, we can replace the
  1369. right-hand side of (6) with `1`, and now replacing the central
  1370. term `m / (2^(d-e+1) a)` with its floor in (6) gives
  1371. (7) -1 < 2^(d-e-1) a + m // 2^(d-e+1) a - √m < 1
  1372. Or equivalently, from (2):
  1373. (7) -1 < b - √m < 1
  1374. and rearranging gives that `(b-1)^2 < m < (b+1)^2`, which is what we needed
  1375. to prove.
  1376. We're not quite done: we still have to prove the inequality `2^(d - e - 1) <=
  1377. a` that was used to get line (7) above. From the definition of `c`, we have
  1378. `4^c <= n`, which implies
  1379. (8) 4^d <= m
  1380. also, since `e == d >> 1`, `d` is at most `2e + 1`, from which it follows
  1381. that `2d - 2e - 1 <= d` and hence that
  1382. (9) 4^(2d - 2e - 1) <= m
  1383. Dividing both sides by `4^(d - e)` gives
  1384. (10) 4^(d - e - 1) <= m / 4^(d - e)
  1385. But we know from (4) that `m / 4^(d-e) < (a + 1)^2`, hence
  1386. (11) 4^(d - e - 1) < (a + 1)^2
  1387. Now taking square roots of both sides and observing that both `2^(d-e-1)` and
  1388. `a` are integers gives `2^(d - e - 1) <= a`, which is what we needed. This
  1389. completes the proof sketch.
  1390. */
  1391. /*
  1392. The _approximate_isqrt_tab table provides approximate square roots for
  1393. 16-bit integers. For any n in the range 2**14 <= n < 2**16, the value
  1394. a = _approximate_isqrt_tab[(n >> 8) - 64]
  1395. is an approximate square root of n, satisfying (a - 1)**2 < n < (a + 1)**2.
  1396. The table was computed in Python using the expression:
  1397. [min(round(sqrt(256*n + 128)), 255) for n in range(64, 256)]
  1398. */
  1399. static const uint8_t _approximate_isqrt_tab[192] = {
  1400. 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139,
  1401. 140, 141, 142, 143, 144, 144, 145, 146, 147, 148, 149, 150,
  1402. 151, 151, 152, 153, 154, 155, 156, 156, 157, 158, 159, 160,
  1403. 160, 161, 162, 163, 164, 164, 165, 166, 167, 167, 168, 169,
  1404. 170, 170, 171, 172, 173, 173, 174, 175, 176, 176, 177, 178,
  1405. 179, 179, 180, 181, 181, 182, 183, 183, 184, 185, 186, 186,
  1406. 187, 188, 188, 189, 190, 190, 191, 192, 192, 193, 194, 194,
  1407. 195, 196, 196, 197, 198, 198, 199, 200, 200, 201, 201, 202,
  1408. 203, 203, 204, 205, 205, 206, 206, 207, 208, 208, 209, 210,
  1409. 210, 211, 211, 212, 213, 213, 214, 214, 215, 216, 216, 217,
  1410. 217, 218, 219, 219, 220, 220, 221, 221, 222, 223, 223, 224,
  1411. 224, 225, 225, 226, 227, 227, 228, 228, 229, 229, 230, 230,
  1412. 231, 232, 232, 233, 233, 234, 234, 235, 235, 236, 237, 237,
  1413. 238, 238, 239, 239, 240, 240, 241, 241, 242, 242, 243, 243,
  1414. 244, 244, 245, 246, 246, 247, 247, 248, 248, 249, 249, 250,
  1415. 250, 251, 251, 252, 252, 253, 253, 254, 254, 255, 255, 255,
  1416. };
  1417. /* Approximate square root of a large 64-bit integer.
  1418. Given `n` satisfying `2**62 <= n < 2**64`, return `a`
  1419. satisfying `(a - 1)**2 < n < (a + 1)**2`. */
  1420. static inline uint32_t
  1421. _approximate_isqrt(uint64_t n)
  1422. {
  1423. uint32_t u = _approximate_isqrt_tab[(n >> 56) - 64];
  1424. u = (u << 7) + (uint32_t)(n >> 41) / u;
  1425. return (u << 15) + (uint32_t)((n >> 17) / u);
  1426. }
  1427. /*[clinic input]
  1428. math.isqrt
  1429. n: object
  1430. /
  1431. Return the integer part of the square root of the input.
  1432. [clinic start generated code]*/
  1433. static PyObject *
  1434. math_isqrt(PyObject *module, PyObject *n)
  1435. /*[clinic end generated code: output=35a6f7f980beab26 input=5b6e7ae4fa6c43d6]*/
  1436. {
  1437. int a_too_large, c_bit_length;
  1438. size_t c, d;
  1439. uint64_t m;
  1440. uint32_t u;
  1441. PyObject *a = NULL, *b;
  1442. n = _PyNumber_Index(n);
  1443. if (n == NULL) {
  1444. return NULL;
  1445. }
  1446. if (_PyLong_IsNegative((PyLongObject *)n)) {
  1447. PyErr_SetString(
  1448. PyExc_ValueError,
  1449. "isqrt() argument must be nonnegative");
  1450. goto error;
  1451. }
  1452. if (_PyLong_IsZero((PyLongObject *)n)) {
  1453. Py_DECREF(n);
  1454. return PyLong_FromLong(0);
  1455. }
  1456. /* c = (n.bit_length() - 1) // 2 */
  1457. c = _PyLong_NumBits(n);
  1458. if (c == (size_t)(-1)) {
  1459. goto error;
  1460. }
  1461. c = (c - 1U) / 2U;
  1462. /* Fast path: if c <= 31 then n < 2**64 and we can compute directly with a
  1463. fast, almost branch-free algorithm. */
  1464. if (c <= 31U) {
  1465. int shift = 31 - (int)c;
  1466. m = (uint64_t)PyLong_AsUnsignedLongLong(n);
  1467. Py_DECREF(n);
  1468. if (m == (uint64_t)(-1) && PyErr_Occurred()) {
  1469. return NULL;
  1470. }
  1471. u = _approximate_isqrt(m << 2*shift) >> shift;
  1472. u -= (uint64_t)u * u > m;
  1473. return PyLong_FromUnsignedLong(u);
  1474. }
  1475. /* Slow path: n >= 2**64. We perform the first five iterations in C integer
  1476. arithmetic, then switch to using Python long integers. */
  1477. /* From n >= 2**64 it follows that c.bit_length() >= 6. */
  1478. c_bit_length = 6;
  1479. while ((c >> c_bit_length) > 0U) {
  1480. ++c_bit_length;
  1481. }
  1482. /* Initialise d and a. */
  1483. d = c >> (c_bit_length - 5);
  1484. b = _PyLong_Rshift(n, 2U*c - 62U);
  1485. if (b == NULL) {
  1486. goto error;
  1487. }
  1488. m = (uint64_t)PyLong_AsUnsignedLongLong(b);
  1489. Py_DECREF(b);
  1490. if (m == (uint64_t)(-1) && PyErr_Occurred()) {
  1491. goto error;
  1492. }
  1493. u = _approximate_isqrt(m) >> (31U - d);
  1494. a = PyLong_FromUnsignedLong(u);
  1495. if (a == NULL) {
  1496. goto error;
  1497. }
  1498. for (int s = c_bit_length - 6; s >= 0; --s) {
  1499. PyObject *q;
  1500. size_t e = d;
  1501. d = c >> s;
  1502. /* q = (n >> 2*c - e - d + 1) // a */
  1503. q = _PyLong_Rshift(n, 2U*c - d - e + 1U);
  1504. if (q == NULL) {
  1505. goto error;
  1506. }
  1507. Py_SETREF(q, PyNumber_FloorDivide(q, a));
  1508. if (q == NULL) {
  1509. goto error;
  1510. }
  1511. /* a = (a << d - 1 - e) + q */
  1512. Py_SETREF(a, _PyLong_Lshift(a, d - 1U - e));
  1513. if (a == NULL) {
  1514. Py_DECREF(q);
  1515. goto error;
  1516. }
  1517. Py_SETREF(a, PyNumber_Add(a, q));
  1518. Py_DECREF(q);
  1519. if (a == NULL) {
  1520. goto error;
  1521. }
  1522. }
  1523. /* The correct result is either a or a - 1. Figure out which, and
  1524. decrement a if necessary. */
  1525. /* a_too_large = n < a * a */
  1526. b = PyNumber_Multiply(a, a);
  1527. if (b == NULL) {
  1528. goto error;
  1529. }
  1530. a_too_large = PyObject_RichCompareBool(n, b, Py_LT);
  1531. Py_DECREF(b);
  1532. if (a_too_large == -1) {
  1533. goto error;
  1534. }
  1535. if (a_too_large) {
  1536. Py_SETREF(a, PyNumber_Subtract(a, _PyLong_GetOne()));
  1537. }
  1538. Py_DECREF(n);
  1539. return a;
  1540. error:
  1541. Py_XDECREF(a);
  1542. Py_DECREF(n);
  1543. return NULL;
  1544. }
  1545. /* Divide-and-conquer factorial algorithm
  1546. *
  1547. * Based on the formula and pseudo-code provided at:
  1548. * http://www.luschny.de/math/factorial/binarysplitfact.html
  1549. *
  1550. * Faster algorithms exist, but they're more complicated and depend on
  1551. * a fast prime factorization algorithm.
  1552. *
  1553. * Notes on the algorithm
  1554. * ----------------------
  1555. *
  1556. * factorial(n) is written in the form 2**k * m, with m odd. k and m are
  1557. * computed separately, and then combined using a left shift.
  1558. *
  1559. * The function factorial_odd_part computes the odd part m (i.e., the greatest
  1560. * odd divisor) of factorial(n), using the formula:
  1561. *
  1562. * factorial_odd_part(n) =
  1563. *
  1564. * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
  1565. *
  1566. * Example: factorial_odd_part(20) =
  1567. *
  1568. * (1) *
  1569. * (1) *
  1570. * (1 * 3 * 5) *
  1571. * (1 * 3 * 5 * 7 * 9) *
  1572. * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
  1573. *
  1574. * Here i goes from large to small: the first term corresponds to i=4 (any
  1575. * larger i gives an empty product), and the last term corresponds to i=0.
  1576. * Each term can be computed from the last by multiplying by the extra odd
  1577. * numbers required: e.g., to get from the penultimate term to the last one,
  1578. * we multiply by (11 * 13 * 15 * 17 * 19).
  1579. *
  1580. * To see a hint of why this formula works, here are the same numbers as above
  1581. * but with the even parts (i.e., the appropriate powers of 2) included. For
  1582. * each subterm in the product for i, we multiply that subterm by 2**i:
  1583. *
  1584. * factorial(20) =
  1585. *
  1586. * (16) *
  1587. * (8) *
  1588. * (4 * 12 * 20) *
  1589. * (2 * 6 * 10 * 14 * 18) *
  1590. * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
  1591. *
  1592. * The factorial_partial_product function computes the product of all odd j in
  1593. * range(start, stop) for given start and stop. It's used to compute the
  1594. * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
  1595. * operates recursively, repeatedly splitting the range into two roughly equal
  1596. * pieces until the subranges are small enough to be computed using only C
  1597. * integer arithmetic.
  1598. *
  1599. * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
  1600. * the factorial) is computed independently in the main math_factorial
  1601. * function. By standard results, its value is:
  1602. *
  1603. * two_valuation = n//2 + n//4 + n//8 + ....
  1604. *
  1605. * It can be shown (e.g., by complete induction on n) that two_valuation is
  1606. * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
  1607. * '1'-bits in the binary expansion of n.
  1608. */
  1609. /* factorial_partial_product: Compute product(range(start, stop, 2)) using
  1610. * divide and conquer. Assumes start and stop are odd and stop > start.
  1611. * max_bits must be >= bit_length(stop - 2). */
  1612. static PyObject *
  1613. factorial_partial_product(unsigned long start, unsigned long stop,
  1614. unsigned long max_bits)
  1615. {
  1616. unsigned long midpoint, num_operands;
  1617. PyObject *left = NULL, *right = NULL, *result = NULL;
  1618. /* If the return value will fit an unsigned long, then we can
  1619. * multiply in a tight, fast loop where each multiply is O(1).
  1620. * Compute an upper bound on the number of bits required to store
  1621. * the answer.
  1622. *
  1623. * Storing some integer z requires floor(lg(z))+1 bits, which is
  1624. * conveniently the value returned by bit_length(z). The
  1625. * product x*y will require at most
  1626. * bit_length(x) + bit_length(y) bits to store, based
  1627. * on the idea that lg product = lg x + lg y.
  1628. *
  1629. * We know that stop - 2 is the largest number to be multiplied. From
  1630. * there, we have: bit_length(answer) <= num_operands *
  1631. * bit_length(stop - 2)
  1632. */
  1633. num_operands = (stop - start) / 2;
  1634. /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
  1635. * unlikely case of an overflow in num_operands * max_bits. */
  1636. if (num_operands <= 8 * SIZEOF_LONG &&
  1637. num_operands * max_bits <= 8 * SIZEOF_LONG) {
  1638. unsigned long j, total;
  1639. for (total = start, j = start + 2; j < stop; j += 2)
  1640. total *= j;
  1641. return PyLong_FromUnsignedLong(total);
  1642. }
  1643. /* find midpoint of range(start, stop), rounded up to next odd number. */
  1644. midpoint = (start + num_operands) | 1;
  1645. left = factorial_partial_product(start, midpoint,
  1646. _Py_bit_length(midpoint - 2));
  1647. if (left == NULL)
  1648. goto error;
  1649. right = factorial_partial_product(midpoint, stop, max_bits);
  1650. if (right == NULL)
  1651. goto error;
  1652. result = PyNumber_Multiply(left, right);
  1653. error:
  1654. Py_XDECREF(left);
  1655. Py_XDECREF(right);
  1656. return result;
  1657. }
  1658. /* factorial_odd_part: compute the odd part of factorial(n). */
  1659. static PyObject *
  1660. factorial_odd_part(unsigned long n)
  1661. {
  1662. long i;
  1663. unsigned long v, lower, upper;
  1664. PyObject *partial, *tmp, *inner, *outer;
  1665. inner = PyLong_FromLong(1);
  1666. if (inner == NULL)
  1667. return NULL;
  1668. outer = Py_NewRef(inner);
  1669. upper = 3;
  1670. for (i = _Py_bit_length(n) - 2; i >= 0; i--) {
  1671. v = n >> i;
  1672. if (v <= 2)
  1673. continue;
  1674. lower = upper;
  1675. /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
  1676. upper = (v + 1) | 1;
  1677. /* Here inner is the product of all odd integers j in the range (0,
  1678. n/2**(i+1)]. The factorial_partial_product call below gives the
  1679. product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
  1680. partial = factorial_partial_product(lower, upper, _Py_bit_length(upper-2));
  1681. /* inner *= partial */
  1682. if (partial == NULL)
  1683. goto error;
  1684. tmp = PyNumber_Multiply(inner, partial);
  1685. Py_DECREF(partial);
  1686. if (tmp == NULL)
  1687. goto error;
  1688. Py_SETREF(inner, tmp);
  1689. /* Now inner is the product of all odd integers j in the range (0,
  1690. n/2**i], giving the inner product in the formula above. */
  1691. /* outer *= inner; */
  1692. tmp = PyNumber_Multiply(outer, inner);
  1693. if (tmp == NULL)
  1694. goto error;
  1695. Py_SETREF(outer, tmp);
  1696. }
  1697. Py_DECREF(inner);
  1698. return outer;
  1699. error:
  1700. Py_DECREF(outer);
  1701. Py_DECREF(inner);
  1702. return NULL;
  1703. }
  1704. /* Lookup table for small factorial values */
  1705. static const unsigned long SmallFactorials[] = {
  1706. 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
  1707. 362880, 3628800, 39916800, 479001600,
  1708. #if SIZEOF_LONG >= 8
  1709. 6227020800, 87178291200, 1307674368000,
  1710. 20922789888000, 355687428096000, 6402373705728000,
  1711. 121645100408832000, 2432902008176640000
  1712. #endif
  1713. };
  1714. /*[clinic input]
  1715. math.factorial
  1716. n as arg: object
  1717. /
  1718. Find n!.
  1719. Raise a ValueError if x is negative or non-integral.
  1720. [clinic start generated code]*/
  1721. static PyObject *
  1722. math_factorial(PyObject *module, PyObject *arg)
  1723. /*[clinic end generated code: output=6686f26fae00e9ca input=713fb771677e8c31]*/
  1724. {
  1725. long x, two_valuation;
  1726. int overflow;
  1727. PyObject *result, *odd_part;
  1728. x = PyLong_AsLongAndOverflow(arg, &overflow);
  1729. if (x == -1 && PyErr_Occurred()) {
  1730. return NULL;
  1731. }
  1732. else if (overflow == 1) {
  1733. PyErr_Format(PyExc_OverflowError,
  1734. "factorial() argument should not exceed %ld",
  1735. LONG_MAX);
  1736. return NULL;
  1737. }
  1738. else if (overflow == -1 || x < 0) {
  1739. PyErr_SetString(PyExc_ValueError,
  1740. "factorial() not defined for negative values");
  1741. return NULL;
  1742. }
  1743. /* use lookup table if x is small */
  1744. if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
  1745. return PyLong_FromUnsignedLong(SmallFactorials[x]);
  1746. /* else express in the form odd_part * 2**two_valuation, and compute as
  1747. odd_part << two_valuation. */
  1748. odd_part = factorial_odd_part(x);
  1749. if (odd_part == NULL)
  1750. return NULL;
  1751. two_valuation = x - count_set_bits(x);
  1752. result = _PyLong_Lshift(odd_part, two_valuation);
  1753. Py_DECREF(odd_part);
  1754. return result;
  1755. }
  1756. /*[clinic input]
  1757. math.trunc
  1758. x: object
  1759. /
  1760. Truncates the Real x to the nearest Integral toward 0.
  1761. Uses the __trunc__ magic method.
  1762. [clinic start generated code]*/
  1763. static PyObject *
  1764. math_trunc(PyObject *module, PyObject *x)
  1765. /*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
  1766. {
  1767. PyObject *trunc, *result;
  1768. if (PyFloat_CheckExact(x)) {
  1769. return PyFloat_Type.tp_as_number->nb_int(x);
  1770. }
  1771. if (!_PyType_IsReady(Py_TYPE(x))) {
  1772. if (PyType_Ready(Py_TYPE(x)) < 0)
  1773. return NULL;
  1774. }
  1775. math_module_state *state = get_math_module_state(module);
  1776. trunc = _PyObject_LookupSpecial(x, state->str___trunc__);
  1777. if (trunc == NULL) {
  1778. if (!PyErr_Occurred())
  1779. PyErr_Format(PyExc_TypeError,
  1780. "type %.100s doesn't define __trunc__ method",
  1781. Py_TYPE(x)->tp_name);
  1782. return NULL;
  1783. }
  1784. result = _PyObject_CallNoArgs(trunc);
  1785. Py_DECREF(trunc);
  1786. return result;
  1787. }
  1788. /*[clinic input]
  1789. math.frexp
  1790. x: double
  1791. /
  1792. Return the mantissa and exponent of x, as pair (m, e).
  1793. m is a float and e is an int, such that x = m * 2.**e.
  1794. If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
  1795. [clinic start generated code]*/
  1796. static PyObject *
  1797. math_frexp_impl(PyObject *module, double x)
  1798. /*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
  1799. {
  1800. int i;
  1801. /* deal with special cases directly, to sidestep platform
  1802. differences */
  1803. if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
  1804. i = 0;
  1805. }
  1806. else {
  1807. x = frexp(x, &i);
  1808. }
  1809. return Py_BuildValue("(di)", x, i);
  1810. }
  1811. /*[clinic input]
  1812. math.ldexp
  1813. x: double
  1814. i: object
  1815. /
  1816. Return x * (2**i).
  1817. This is essentially the inverse of frexp().
  1818. [clinic start generated code]*/
  1819. static PyObject *
  1820. math_ldexp_impl(PyObject *module, double x, PyObject *i)
  1821. /*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
  1822. {
  1823. double r;
  1824. long exp;
  1825. int overflow;
  1826. if (PyLong_Check(i)) {
  1827. /* on overflow, replace exponent with either LONG_MAX
  1828. or LONG_MIN, depending on the sign. */
  1829. exp = PyLong_AsLongAndOverflow(i, &overflow);
  1830. if (exp == -1 && PyErr_Occurred())
  1831. return NULL;
  1832. if (overflow)
  1833. exp = overflow < 0 ? LONG_MIN : LONG_MAX;
  1834. }
  1835. else {
  1836. PyErr_SetString(PyExc_TypeError,
  1837. "Expected an int as second argument to ldexp.");
  1838. return NULL;
  1839. }
  1840. if (x == 0. || !Py_IS_FINITE(x)) {
  1841. /* NaNs, zeros and infinities are returned unchanged */
  1842. r = x;
  1843. errno = 0;
  1844. } else if (exp > INT_MAX) {
  1845. /* overflow */
  1846. r = copysign(Py_HUGE_VAL, x);
  1847. errno = ERANGE;
  1848. } else if (exp < INT_MIN) {
  1849. /* underflow to +-0 */
  1850. r = copysign(0., x);
  1851. errno = 0;
  1852. } else {
  1853. errno = 0;
  1854. r = ldexp(x, (int)exp);
  1855. if (Py_IS_INFINITY(r))
  1856. errno = ERANGE;
  1857. }
  1858. if (errno && is_error(r))
  1859. return NULL;
  1860. return PyFloat_FromDouble(r);
  1861. }
  1862. /*[clinic input]
  1863. math.modf
  1864. x: double
  1865. /
  1866. Return the fractional and integer parts of x.
  1867. Both results carry the sign of x and are floats.
  1868. [clinic start generated code]*/
  1869. static PyObject *
  1870. math_modf_impl(PyObject *module, double x)
  1871. /*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
  1872. {
  1873. double y;
  1874. /* some platforms don't do the right thing for NaNs and
  1875. infinities, so we take care of special cases directly. */
  1876. if (!Py_IS_FINITE(x)) {
  1877. if (Py_IS_INFINITY(x))
  1878. return Py_BuildValue("(dd)", copysign(0., x), x);
  1879. else if (Py_IS_NAN(x))
  1880. return Py_BuildValue("(dd)", x, x);
  1881. }
  1882. errno = 0;
  1883. x = modf(x, &y);
  1884. return Py_BuildValue("(dd)", x, y);
  1885. }
  1886. /* A decent logarithm is easy to compute even for huge ints, but libm can't
  1887. do that by itself -- loghelper can. func is log or log10, and name is
  1888. "log" or "log10". Note that overflow of the result isn't possible: an int
  1889. can contain no more than INT_MAX * SHIFT bits, so has value certainly less
  1890. than 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
  1891. small enough to fit in an IEEE single. log and log10 are even smaller.
  1892. However, intermediate overflow is possible for an int if the number of bits
  1893. in that int is larger than PY_SSIZE_T_MAX. */
  1894. static PyObject*
  1895. loghelper(PyObject* arg, double (*func)(double))
  1896. {
  1897. /* If it is int, do it ourselves. */
  1898. if (PyLong_Check(arg)) {
  1899. double x, result;
  1900. Py_ssize_t e;
  1901. /* Negative or zero inputs give a ValueError. */
  1902. if (!_PyLong_IsPositive((PyLongObject *)arg)) {
  1903. PyErr_SetString(PyExc_ValueError,
  1904. "math domain error");
  1905. return NULL;
  1906. }
  1907. x = PyLong_AsDouble(arg);
  1908. if (x == -1.0 && PyErr_Occurred()) {
  1909. if (!PyErr_ExceptionMatches(PyExc_OverflowError))
  1910. return NULL;
  1911. /* Here the conversion to double overflowed, but it's possible
  1912. to compute the log anyway. Clear the exception and continue. */
  1913. PyErr_Clear();
  1914. x = _PyLong_Frexp((PyLongObject *)arg, &e);
  1915. if (x == -1.0 && PyErr_Occurred())
  1916. return NULL;
  1917. /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
  1918. result = func(x) + func(2.0) * e;
  1919. }
  1920. else
  1921. /* Successfully converted x to a double. */
  1922. result = func(x);
  1923. return PyFloat_FromDouble(result);
  1924. }
  1925. /* Else let libm handle it by itself. */
  1926. return math_1(arg, func, 0);
  1927. }
  1928. /* AC: cannot convert yet, see gh-102839 and gh-89381, waiting
  1929. for support of multiple signatures */
  1930. static PyObject *
  1931. math_log(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
  1932. {
  1933. PyObject *num, *den;
  1934. PyObject *ans;
  1935. if (!_PyArg_CheckPositional("log", nargs, 1, 2))
  1936. return NULL;
  1937. num = loghelper(args[0], m_log);
  1938. if (num == NULL || nargs == 1)
  1939. return num;
  1940. den = loghelper(args[1], m_log);
  1941. if (den == NULL) {
  1942. Py_DECREF(num);
  1943. return NULL;
  1944. }
  1945. ans = PyNumber_TrueDivide(num, den);
  1946. Py_DECREF(num);
  1947. Py_DECREF(den);
  1948. return ans;
  1949. }
  1950. PyDoc_STRVAR(math_log_doc,
  1951. "log(x, [base=math.e])\n\
  1952. Return the logarithm of x to the given base.\n\n\
  1953. If the base is not specified, returns the natural logarithm (base e) of x.");
  1954. /*[clinic input]
  1955. math.log2
  1956. x: object
  1957. /
  1958. Return the base 2 logarithm of x.
  1959. [clinic start generated code]*/
  1960. static PyObject *
  1961. math_log2(PyObject *module, PyObject *x)
  1962. /*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
  1963. {
  1964. return loghelper(x, m_log2);
  1965. }
  1966. /*[clinic input]
  1967. math.log10
  1968. x: object
  1969. /
  1970. Return the base 10 logarithm of x.
  1971. [clinic start generated code]*/
  1972. static PyObject *
  1973. math_log10(PyObject *module, PyObject *x)
  1974. /*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
  1975. {
  1976. return loghelper(x, m_log10);
  1977. }
  1978. /*[clinic input]
  1979. math.fmod
  1980. x: double
  1981. y: double
  1982. /
  1983. Return fmod(x, y), according to platform C.
  1984. x % y may differ.
  1985. [clinic start generated code]*/
  1986. static PyObject *
  1987. math_fmod_impl(PyObject *module, double x, double y)
  1988. /*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
  1989. {
  1990. double r;
  1991. /* fmod(x, +/-Inf) returns x for finite x. */
  1992. if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
  1993. return PyFloat_FromDouble(x);
  1994. errno = 0;
  1995. r = fmod(x, y);
  1996. if (Py_IS_NAN(r)) {
  1997. if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
  1998. errno = EDOM;
  1999. else
  2000. errno = 0;
  2001. }
  2002. if (errno && is_error(r))
  2003. return NULL;
  2004. else
  2005. return PyFloat_FromDouble(r);
  2006. }
  2007. /*
  2008. Given a *vec* of values, compute the vector norm:
  2009. sqrt(sum(x ** 2 for x in vec))
  2010. The *max* variable should be equal to the largest fabs(x).
  2011. The *n* variable is the length of *vec*.
  2012. If n==0, then *max* should be 0.0.
  2013. If an infinity is present in the vec, *max* should be INF.
  2014. The *found_nan* variable indicates whether some member of
  2015. the *vec* is a NaN.
  2016. To avoid overflow/underflow and to achieve high accuracy giving results
  2017. that are almost always correctly rounded, four techniques are used:
  2018. * lossless scaling using a power-of-two scaling factor
  2019. * accurate squaring using Veltkamp-Dekker splitting [1]
  2020. or an equivalent with an fma() call
  2021. * compensated summation using a variant of the Neumaier algorithm [2]
  2022. * differential correction of the square root [3]
  2023. The usual presentation of the Neumaier summation algorithm has an
  2024. expensive branch depending on which operand has the larger
  2025. magnitude. We avoid this cost by arranging the calculation so that
  2026. fabs(csum) is always as large as fabs(x).
  2027. To establish the invariant, *csum* is initialized to 1.0 which is
  2028. always larger than x**2 after scaling or after division by *max*.
  2029. After the loop is finished, the initial 1.0 is subtracted out for a
  2030. net zero effect on the final sum. Since *csum* will be greater than
  2031. 1.0, the subtraction of 1.0 will not cause fractional digits to be
  2032. dropped from *csum*.
  2033. To get the full benefit from compensated summation, the largest
  2034. addend should be in the range: 0.5 <= |x| <= 1.0. Accordingly,
  2035. scaling or division by *max* should not be skipped even if not
  2036. otherwise needed to prevent overflow or loss of precision.
  2037. The assertion that hi*hi <= 1.0 is a bit subtle. Each vector element
  2038. gets scaled to a magnitude below 1.0. The Veltkamp-Dekker splitting
  2039. algorithm gives a *hi* value that is correctly rounded to half
  2040. precision. When a value at or below 1.0 is correctly rounded, it
  2041. never goes above 1.0. And when values at or below 1.0 are squared,
  2042. they remain at or below 1.0, thus preserving the summation invariant.
  2043. Another interesting assertion is that csum+lo*lo == csum. In the loop,
  2044. each scaled vector element has a magnitude less than 1.0. After the
  2045. Veltkamp split, *lo* has a maximum value of 2**-27. So the maximum
  2046. value of *lo* squared is 2**-54. The value of ulp(1.0)/2.0 is 2**-53.
  2047. Given that csum >= 1.0, we have:
  2048. lo**2 <= 2**-54 < 2**-53 == 1/2*ulp(1.0) <= ulp(csum)/2
  2049. Since lo**2 is less than 1/2 ulp(csum), we have csum+lo*lo == csum.
  2050. To minimize loss of information during the accumulation of fractional
  2051. values, each term has a separate accumulator. This also breaks up
  2052. sequential dependencies in the inner loop so the CPU can maximize
  2053. floating point throughput. [4] On an Apple M1 Max, hypot(*vec)
  2054. takes only 3.33 µsec when len(vec) == 1000.
  2055. The square root differential correction is needed because a
  2056. correctly rounded square root of a correctly rounded sum of
  2057. squares can still be off by as much as one ulp.
  2058. The differential correction starts with a value *x* that is
  2059. the difference between the square of *h*, the possibly inaccurately
  2060. rounded square root, and the accurately computed sum of squares.
  2061. The correction is the first order term of the Maclaurin series
  2062. expansion of sqrt(h**2 + x) == h + x/(2*h) + O(x**2). [5]
  2063. Essentially, this differential correction is equivalent to one
  2064. refinement step in Newton's divide-and-average square root
  2065. algorithm, effectively doubling the number of accurate bits.
  2066. This technique is used in Dekker's SQRT2 algorithm and again in
  2067. Borges' ALGORITHM 4 and 5.
  2068. The hypot() function is faithfully rounded (less than 1 ulp error)
  2069. and usually correctly rounded (within 1/2 ulp). The squaring
  2070. step is exact. The Neumaier summation computes as if in doubled
  2071. precision (106 bits) and has the advantage that its input squares
  2072. are non-negative so that the condition number of the sum is one.
  2073. The square root with a differential correction is likewise computed
  2074. as if in doubled precision.
  2075. For n <= 1000, prior to the final addition that rounds the overall
  2076. result, the internal accuracy of "h" together with its correction of
  2077. "x / (2.0 * h)" is at least 100 bits. [6] Also, hypot() was tested
  2078. against a Decimal implementation with prec=300. After 100 million
  2079. trials, no incorrectly rounded examples were found. In addition,
  2080. perfect commutativity (all permutations are exactly equal) was
  2081. verified for 1 billion random inputs with n=5. [7]
  2082. References:
  2083. 1. Veltkamp-Dekker splitting: http://csclub.uwaterloo.ca/~pbarfuss/dekker1971.pdf
  2084. 2. Compensated summation: http://www.ti3.tu-harburg.de/paper/rump/Ru08b.pdf
  2085. 3. Square root differential correction: https://arxiv.org/pdf/1904.09481.pdf
  2086. 4. Data dependency graph: https://bugs.python.org/file49439/hypot.png
  2087. 5. https://www.wolframalpha.com/input/?i=Maclaurin+series+sqrt%28h**2+%2B+x%29+at+x%3D0
  2088. 6. Analysis of internal accuracy: https://bugs.python.org/file49484/best_frac.py
  2089. 7. Commutativity test: https://bugs.python.org/file49448/test_hypot_commutativity.py
  2090. */
  2091. static inline double
  2092. vector_norm(Py_ssize_t n, double *vec, double max, int found_nan)
  2093. {
  2094. double x, h, scale, csum = 1.0, frac1 = 0.0, frac2 = 0.0;
  2095. DoubleLength pr, sm;
  2096. int max_e;
  2097. Py_ssize_t i;
  2098. if (Py_IS_INFINITY(max)) {
  2099. return max;
  2100. }
  2101. if (found_nan) {
  2102. return Py_NAN;
  2103. }
  2104. if (max == 0.0 || n <= 1) {
  2105. return max;
  2106. }
  2107. frexp(max, &max_e);
  2108. if (max_e < -1023) {
  2109. /* When max_e < -1023, ldexp(1.0, -max_e) would overflow. */
  2110. for (i=0 ; i < n ; i++) {
  2111. vec[i] /= DBL_MIN; // convert subnormals to normals
  2112. }
  2113. return DBL_MIN * vector_norm(n, vec, max / DBL_MIN, found_nan);
  2114. }
  2115. scale = ldexp(1.0, -max_e);
  2116. assert(max * scale >= 0.5);
  2117. assert(max * scale < 1.0);
  2118. for (i=0 ; i < n ; i++) {
  2119. x = vec[i];
  2120. assert(Py_IS_FINITE(x) && fabs(x) <= max);
  2121. x *= scale; // lossless scaling
  2122. assert(fabs(x) < 1.0);
  2123. pr = dl_mul(x, x); // lossless squaring
  2124. assert(pr.hi <= 1.0);
  2125. sm = dl_fast_sum(csum, pr.hi); // lossless addition
  2126. csum = sm.hi;
  2127. frac1 += pr.lo; // lossy addition
  2128. frac2 += sm.lo; // lossy addition
  2129. }
  2130. h = sqrt(csum - 1.0 + (frac1 + frac2));
  2131. pr = dl_mul(-h, h);
  2132. sm = dl_fast_sum(csum, pr.hi);
  2133. csum = sm.hi;
  2134. frac1 += pr.lo;
  2135. frac2 += sm.lo;
  2136. x = csum - 1.0 + (frac1 + frac2);
  2137. h += x / (2.0 * h); // differential correction
  2138. return h / scale;
  2139. }
  2140. #define NUM_STACK_ELEMS 16
  2141. /*[clinic input]
  2142. math.dist
  2143. p: object
  2144. q: object
  2145. /
  2146. Return the Euclidean distance between two points p and q.
  2147. The points should be specified as sequences (or iterables) of
  2148. coordinates. Both inputs must have the same dimension.
  2149. Roughly equivalent to:
  2150. sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
  2151. [clinic start generated code]*/
  2152. static PyObject *
  2153. math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
  2154. /*[clinic end generated code: output=56bd9538d06bbcfe input=74e85e1b6092e68e]*/
  2155. {
  2156. PyObject *item;
  2157. double max = 0.0;
  2158. double x, px, qx, result;
  2159. Py_ssize_t i, m, n;
  2160. int found_nan = 0, p_allocated = 0, q_allocated = 0;
  2161. double diffs_on_stack[NUM_STACK_ELEMS];
  2162. double *diffs = diffs_on_stack;
  2163. if (!PyTuple_Check(p)) {
  2164. p = PySequence_Tuple(p);
  2165. if (p == NULL) {
  2166. return NULL;
  2167. }
  2168. p_allocated = 1;
  2169. }
  2170. if (!PyTuple_Check(q)) {
  2171. q = PySequence_Tuple(q);
  2172. if (q == NULL) {
  2173. if (p_allocated) {
  2174. Py_DECREF(p);
  2175. }
  2176. return NULL;
  2177. }
  2178. q_allocated = 1;
  2179. }
  2180. m = PyTuple_GET_SIZE(p);
  2181. n = PyTuple_GET_SIZE(q);
  2182. if (m != n) {
  2183. PyErr_SetString(PyExc_ValueError,
  2184. "both points must have the same number of dimensions");
  2185. goto error_exit;
  2186. }
  2187. if (n > NUM_STACK_ELEMS) {
  2188. diffs = (double *) PyObject_Malloc(n * sizeof(double));
  2189. if (diffs == NULL) {
  2190. PyErr_NoMemory();
  2191. goto error_exit;
  2192. }
  2193. }
  2194. for (i=0 ; i<n ; i++) {
  2195. item = PyTuple_GET_ITEM(p, i);
  2196. ASSIGN_DOUBLE(px, item, error_exit);
  2197. item = PyTuple_GET_ITEM(q, i);
  2198. ASSIGN_DOUBLE(qx, item, error_exit);
  2199. x = fabs(px - qx);
  2200. diffs[i] = x;
  2201. found_nan |= Py_IS_NAN(x);
  2202. if (x > max) {
  2203. max = x;
  2204. }
  2205. }
  2206. result = vector_norm(n, diffs, max, found_nan);
  2207. if (diffs != diffs_on_stack) {
  2208. PyObject_Free(diffs);
  2209. }
  2210. if (p_allocated) {
  2211. Py_DECREF(p);
  2212. }
  2213. if (q_allocated) {
  2214. Py_DECREF(q);
  2215. }
  2216. return PyFloat_FromDouble(result);
  2217. error_exit:
  2218. if (diffs != diffs_on_stack) {
  2219. PyObject_Free(diffs);
  2220. }
  2221. if (p_allocated) {
  2222. Py_DECREF(p);
  2223. }
  2224. if (q_allocated) {
  2225. Py_DECREF(q);
  2226. }
  2227. return NULL;
  2228. }
  2229. /* AC: cannot convert yet, waiting for *args support */
  2230. static PyObject *
  2231. math_hypot(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
  2232. {
  2233. Py_ssize_t i;
  2234. PyObject *item;
  2235. double max = 0.0;
  2236. double x, result;
  2237. int found_nan = 0;
  2238. double coord_on_stack[NUM_STACK_ELEMS];
  2239. double *coordinates = coord_on_stack;
  2240. if (nargs > NUM_STACK_ELEMS) {
  2241. coordinates = (double *) PyObject_Malloc(nargs * sizeof(double));
  2242. if (coordinates == NULL) {
  2243. return PyErr_NoMemory();
  2244. }
  2245. }
  2246. for (i = 0; i < nargs; i++) {
  2247. item = args[i];
  2248. ASSIGN_DOUBLE(x, item, error_exit);
  2249. x = fabs(x);
  2250. coordinates[i] = x;
  2251. found_nan |= Py_IS_NAN(x);
  2252. if (x > max) {
  2253. max = x;
  2254. }
  2255. }
  2256. result = vector_norm(nargs, coordinates, max, found_nan);
  2257. if (coordinates != coord_on_stack) {
  2258. PyObject_Free(coordinates);
  2259. }
  2260. return PyFloat_FromDouble(result);
  2261. error_exit:
  2262. if (coordinates != coord_on_stack) {
  2263. PyObject_Free(coordinates);
  2264. }
  2265. return NULL;
  2266. }
  2267. #undef NUM_STACK_ELEMS
  2268. PyDoc_STRVAR(math_hypot_doc,
  2269. "hypot(*coordinates) -> value\n\n\
  2270. Multidimensional Euclidean distance from the origin to a point.\n\
  2271. \n\
  2272. Roughly equivalent to:\n\
  2273. sqrt(sum(x**2 for x in coordinates))\n\
  2274. \n\
  2275. For a two dimensional point (x, y), gives the hypotenuse\n\
  2276. using the Pythagorean theorem: sqrt(x*x + y*y).\n\
  2277. \n\
  2278. For example, the hypotenuse of a 3/4/5 right triangle is:\n\
  2279. \n\
  2280. >>> hypot(3.0, 4.0)\n\
  2281. 5.0\n\
  2282. ");
  2283. /** sumprod() ***************************************************************/
  2284. /* Forward declaration */
  2285. static inline int _check_long_mult_overflow(long a, long b);
  2286. static inline bool
  2287. long_add_would_overflow(long a, long b)
  2288. {
  2289. return (a > 0) ? (b > LONG_MAX - a) : (b < LONG_MIN - a);
  2290. }
  2291. /*[clinic input]
  2292. math.sumprod
  2293. p: object
  2294. q: object
  2295. /
  2296. Return the sum of products of values from two iterables p and q.
  2297. Roughly equivalent to:
  2298. sum(itertools.starmap(operator.mul, zip(p, q, strict=True)))
  2299. For float and mixed int/float inputs, the intermediate products
  2300. and sums are computed with extended precision.
  2301. [clinic start generated code]*/
  2302. static PyObject *
  2303. math_sumprod_impl(PyObject *module, PyObject *p, PyObject *q)
  2304. /*[clinic end generated code: output=6722dbfe60664554 input=82be54fe26f87e30]*/
  2305. {
  2306. PyObject *p_i = NULL, *q_i = NULL, *term_i = NULL, *new_total = NULL;
  2307. PyObject *p_it, *q_it, *total;
  2308. iternextfunc p_next, q_next;
  2309. bool p_stopped = false, q_stopped = false;
  2310. bool int_path_enabled = true, int_total_in_use = false;
  2311. bool flt_path_enabled = true, flt_total_in_use = false;
  2312. long int_total = 0;
  2313. TripleLength flt_total = tl_zero;
  2314. p_it = PyObject_GetIter(p);
  2315. if (p_it == NULL) {
  2316. return NULL;
  2317. }
  2318. q_it = PyObject_GetIter(q);
  2319. if (q_it == NULL) {
  2320. Py_DECREF(p_it);
  2321. return NULL;
  2322. }
  2323. total = PyLong_FromLong(0);
  2324. if (total == NULL) {
  2325. Py_DECREF(p_it);
  2326. Py_DECREF(q_it);
  2327. return NULL;
  2328. }
  2329. p_next = *Py_TYPE(p_it)->tp_iternext;
  2330. q_next = *Py_TYPE(q_it)->tp_iternext;
  2331. while (1) {
  2332. bool finished;
  2333. assert (p_i == NULL);
  2334. assert (q_i == NULL);
  2335. assert (term_i == NULL);
  2336. assert (new_total == NULL);
  2337. assert (p_it != NULL);
  2338. assert (q_it != NULL);
  2339. assert (total != NULL);
  2340. p_i = p_next(p_it);
  2341. if (p_i == NULL) {
  2342. if (PyErr_Occurred()) {
  2343. if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
  2344. goto err_exit;
  2345. }
  2346. PyErr_Clear();
  2347. }
  2348. p_stopped = true;
  2349. }
  2350. q_i = q_next(q_it);
  2351. if (q_i == NULL) {
  2352. if (PyErr_Occurred()) {
  2353. if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
  2354. goto err_exit;
  2355. }
  2356. PyErr_Clear();
  2357. }
  2358. q_stopped = true;
  2359. }
  2360. if (p_stopped != q_stopped) {
  2361. PyErr_Format(PyExc_ValueError, "Inputs are not the same length");
  2362. goto err_exit;
  2363. }
  2364. finished = p_stopped & q_stopped;
  2365. if (int_path_enabled) {
  2366. if (!finished && PyLong_CheckExact(p_i) & PyLong_CheckExact(q_i)) {
  2367. int overflow;
  2368. long int_p, int_q, int_prod;
  2369. int_p = PyLong_AsLongAndOverflow(p_i, &overflow);
  2370. if (overflow) {
  2371. goto finalize_int_path;
  2372. }
  2373. int_q = PyLong_AsLongAndOverflow(q_i, &overflow);
  2374. if (overflow) {
  2375. goto finalize_int_path;
  2376. }
  2377. if (_check_long_mult_overflow(int_p, int_q)) {
  2378. goto finalize_int_path;
  2379. }
  2380. int_prod = int_p * int_q;
  2381. if (long_add_would_overflow(int_total, int_prod)) {
  2382. goto finalize_int_path;
  2383. }
  2384. int_total += int_prod;
  2385. int_total_in_use = true;
  2386. Py_CLEAR(p_i);
  2387. Py_CLEAR(q_i);
  2388. continue;
  2389. }
  2390. finalize_int_path:
  2391. // We're finished, overflowed, or have a non-int
  2392. int_path_enabled = false;
  2393. if (int_total_in_use) {
  2394. term_i = PyLong_FromLong(int_total);
  2395. if (term_i == NULL) {
  2396. goto err_exit;
  2397. }
  2398. new_total = PyNumber_Add(total, term_i);
  2399. if (new_total == NULL) {
  2400. goto err_exit;
  2401. }
  2402. Py_SETREF(total, new_total);
  2403. new_total = NULL;
  2404. Py_CLEAR(term_i);
  2405. int_total = 0; // An ounce of prevention, ...
  2406. int_total_in_use = false;
  2407. }
  2408. }
  2409. if (flt_path_enabled) {
  2410. if (!finished) {
  2411. double flt_p, flt_q;
  2412. bool p_type_float = PyFloat_CheckExact(p_i);
  2413. bool q_type_float = PyFloat_CheckExact(q_i);
  2414. if (p_type_float && q_type_float) {
  2415. flt_p = PyFloat_AS_DOUBLE(p_i);
  2416. flt_q = PyFloat_AS_DOUBLE(q_i);
  2417. } else if (p_type_float && (PyLong_CheckExact(q_i) || PyBool_Check(q_i))) {
  2418. /* We care about float/int pairs and int/float pairs because
  2419. they arise naturally in several use cases such as price
  2420. times quantity, measurements with integer weights, or
  2421. data selected by a vector of bools. */
  2422. flt_p = PyFloat_AS_DOUBLE(p_i);
  2423. flt_q = PyLong_AsDouble(q_i);
  2424. if (flt_q == -1.0 && PyErr_Occurred()) {
  2425. PyErr_Clear();
  2426. goto finalize_flt_path;
  2427. }
  2428. } else if (q_type_float && (PyLong_CheckExact(p_i) || PyBool_Check(p_i))) {
  2429. flt_q = PyFloat_AS_DOUBLE(q_i);
  2430. flt_p = PyLong_AsDouble(p_i);
  2431. if (flt_p == -1.0 && PyErr_Occurred()) {
  2432. PyErr_Clear();
  2433. goto finalize_flt_path;
  2434. }
  2435. } else {
  2436. goto finalize_flt_path;
  2437. }
  2438. TripleLength new_flt_total = tl_fma(flt_p, flt_q, flt_total);
  2439. if (isfinite(new_flt_total.hi)) {
  2440. flt_total = new_flt_total;
  2441. flt_total_in_use = true;
  2442. Py_CLEAR(p_i);
  2443. Py_CLEAR(q_i);
  2444. continue;
  2445. }
  2446. }
  2447. finalize_flt_path:
  2448. // We're finished, overflowed, have a non-float, or got a non-finite value
  2449. flt_path_enabled = false;
  2450. if (flt_total_in_use) {
  2451. term_i = PyFloat_FromDouble(tl_to_d(flt_total));
  2452. if (term_i == NULL) {
  2453. goto err_exit;
  2454. }
  2455. new_total = PyNumber_Add(total, term_i);
  2456. if (new_total == NULL) {
  2457. goto err_exit;
  2458. }
  2459. Py_SETREF(total, new_total);
  2460. new_total = NULL;
  2461. Py_CLEAR(term_i);
  2462. flt_total = tl_zero;
  2463. flt_total_in_use = false;
  2464. }
  2465. }
  2466. assert(!int_total_in_use);
  2467. assert(!flt_total_in_use);
  2468. if (finished) {
  2469. goto normal_exit;
  2470. }
  2471. term_i = PyNumber_Multiply(p_i, q_i);
  2472. if (term_i == NULL) {
  2473. goto err_exit;
  2474. }
  2475. new_total = PyNumber_Add(total, term_i);
  2476. if (new_total == NULL) {
  2477. goto err_exit;
  2478. }
  2479. Py_SETREF(total, new_total);
  2480. new_total = NULL;
  2481. Py_CLEAR(p_i);
  2482. Py_CLEAR(q_i);
  2483. Py_CLEAR(term_i);
  2484. }
  2485. normal_exit:
  2486. Py_DECREF(p_it);
  2487. Py_DECREF(q_it);
  2488. return total;
  2489. err_exit:
  2490. Py_DECREF(p_it);
  2491. Py_DECREF(q_it);
  2492. Py_DECREF(total);
  2493. Py_XDECREF(p_i);
  2494. Py_XDECREF(q_i);
  2495. Py_XDECREF(term_i);
  2496. Py_XDECREF(new_total);
  2497. return NULL;
  2498. }
  2499. /* pow can't use math_2, but needs its own wrapper: the problem is
  2500. that an infinite result can arise either as a result of overflow
  2501. (in which case OverflowError should be raised) or as a result of
  2502. e.g. 0.**-5. (for which ValueError needs to be raised.)
  2503. */
  2504. /*[clinic input]
  2505. math.pow
  2506. x: double
  2507. y: double
  2508. /
  2509. Return x**y (x to the power of y).
  2510. [clinic start generated code]*/
  2511. static PyObject *
  2512. math_pow_impl(PyObject *module, double x, double y)
  2513. /*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
  2514. {
  2515. double r;
  2516. int odd_y;
  2517. /* deal directly with IEEE specials, to cope with problems on various
  2518. platforms whose semantics don't exactly match C99 */
  2519. r = 0.; /* silence compiler warning */
  2520. if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
  2521. errno = 0;
  2522. if (Py_IS_NAN(x))
  2523. r = y == 0. ? 1. : x; /* NaN**0 = 1 */
  2524. else if (Py_IS_NAN(y))
  2525. r = x == 1. ? 1. : y; /* 1**NaN = 1 */
  2526. else if (Py_IS_INFINITY(x)) {
  2527. odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
  2528. if (y > 0.)
  2529. r = odd_y ? x : fabs(x);
  2530. else if (y == 0.)
  2531. r = 1.;
  2532. else /* y < 0. */
  2533. r = odd_y ? copysign(0., x) : 0.;
  2534. }
  2535. else if (Py_IS_INFINITY(y)) {
  2536. if (fabs(x) == 1.0)
  2537. r = 1.;
  2538. else if (y > 0. && fabs(x) > 1.0)
  2539. r = y;
  2540. else if (y < 0. && fabs(x) < 1.0) {
  2541. r = -y; /* result is +inf */
  2542. }
  2543. else
  2544. r = 0.;
  2545. }
  2546. }
  2547. else {
  2548. /* let libm handle finite**finite */
  2549. errno = 0;
  2550. r = pow(x, y);
  2551. /* a NaN result should arise only from (-ve)**(finite
  2552. non-integer); in this case we want to raise ValueError. */
  2553. if (!Py_IS_FINITE(r)) {
  2554. if (Py_IS_NAN(r)) {
  2555. errno = EDOM;
  2556. }
  2557. /*
  2558. an infinite result here arises either from:
  2559. (A) (+/-0.)**negative (-> divide-by-zero)
  2560. (B) overflow of x**y with x and y finite
  2561. */
  2562. else if (Py_IS_INFINITY(r)) {
  2563. if (x == 0.)
  2564. errno = EDOM;
  2565. else
  2566. errno = ERANGE;
  2567. }
  2568. }
  2569. }
  2570. if (errno && is_error(r))
  2571. return NULL;
  2572. else
  2573. return PyFloat_FromDouble(r);
  2574. }
  2575. static const double degToRad = Py_MATH_PI / 180.0;
  2576. static const double radToDeg = 180.0 / Py_MATH_PI;
  2577. /*[clinic input]
  2578. math.degrees
  2579. x: double
  2580. /
  2581. Convert angle x from radians to degrees.
  2582. [clinic start generated code]*/
  2583. static PyObject *
  2584. math_degrees_impl(PyObject *module, double x)
  2585. /*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
  2586. {
  2587. return PyFloat_FromDouble(x * radToDeg);
  2588. }
  2589. /*[clinic input]
  2590. math.radians
  2591. x: double
  2592. /
  2593. Convert angle x from degrees to radians.
  2594. [clinic start generated code]*/
  2595. static PyObject *
  2596. math_radians_impl(PyObject *module, double x)
  2597. /*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
  2598. {
  2599. return PyFloat_FromDouble(x * degToRad);
  2600. }
  2601. /*[clinic input]
  2602. math.isfinite
  2603. x: double
  2604. /
  2605. Return True if x is neither an infinity nor a NaN, and False otherwise.
  2606. [clinic start generated code]*/
  2607. static PyObject *
  2608. math_isfinite_impl(PyObject *module, double x)
  2609. /*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
  2610. {
  2611. return PyBool_FromLong((long)Py_IS_FINITE(x));
  2612. }
  2613. /*[clinic input]
  2614. math.isnan
  2615. x: double
  2616. /
  2617. Return True if x is a NaN (not a number), and False otherwise.
  2618. [clinic start generated code]*/
  2619. static PyObject *
  2620. math_isnan_impl(PyObject *module, double x)
  2621. /*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
  2622. {
  2623. return PyBool_FromLong((long)Py_IS_NAN(x));
  2624. }
  2625. /*[clinic input]
  2626. math.isinf
  2627. x: double
  2628. /
  2629. Return True if x is a positive or negative infinity, and False otherwise.
  2630. [clinic start generated code]*/
  2631. static PyObject *
  2632. math_isinf_impl(PyObject *module, double x)
  2633. /*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
  2634. {
  2635. return PyBool_FromLong((long)Py_IS_INFINITY(x));
  2636. }
  2637. /*[clinic input]
  2638. math.isclose -> bool
  2639. a: double
  2640. b: double
  2641. *
  2642. rel_tol: double = 1e-09
  2643. maximum difference for being considered "close", relative to the
  2644. magnitude of the input values
  2645. abs_tol: double = 0.0
  2646. maximum difference for being considered "close", regardless of the
  2647. magnitude of the input values
  2648. Determine whether two floating point numbers are close in value.
  2649. Return True if a is close in value to b, and False otherwise.
  2650. For the values to be considered close, the difference between them
  2651. must be smaller than at least one of the tolerances.
  2652. -inf, inf and NaN behave similarly to the IEEE 754 Standard. That
  2653. is, NaN is not close to anything, even itself. inf and -inf are
  2654. only close to themselves.
  2655. [clinic start generated code]*/
  2656. static int
  2657. math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
  2658. double abs_tol)
  2659. /*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
  2660. {
  2661. double diff = 0.0;
  2662. /* sanity check on the inputs */
  2663. if (rel_tol < 0.0 || abs_tol < 0.0 ) {
  2664. PyErr_SetString(PyExc_ValueError,
  2665. "tolerances must be non-negative");
  2666. return -1;
  2667. }
  2668. if ( a == b ) {
  2669. /* short circuit exact equality -- needed to catch two infinities of
  2670. the same sign. And perhaps speeds things up a bit sometimes.
  2671. */
  2672. return 1;
  2673. }
  2674. /* This catches the case of two infinities of opposite sign, or
  2675. one infinity and one finite number. Two infinities of opposite
  2676. sign would otherwise have an infinite relative tolerance.
  2677. Two infinities of the same sign are caught by the equality check
  2678. above.
  2679. */
  2680. if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
  2681. return 0;
  2682. }
  2683. /* now do the regular computation
  2684. this is essentially the "weak" test from the Boost library
  2685. */
  2686. diff = fabs(b - a);
  2687. return (((diff <= fabs(rel_tol * b)) ||
  2688. (diff <= fabs(rel_tol * a))) ||
  2689. (diff <= abs_tol));
  2690. }
  2691. static inline int
  2692. _check_long_mult_overflow(long a, long b) {
  2693. /* From Python2's int_mul code:
  2694. Integer overflow checking for * is painful: Python tried a couple ways, but
  2695. they didn't work on all platforms, or failed in endcases (a product of
  2696. -sys.maxint-1 has been a particular pain).
  2697. Here's another way:
  2698. The native long product x*y is either exactly right or *way* off, being
  2699. just the last n bits of the true product, where n is the number of bits
  2700. in a long (the delivered product is the true product plus i*2**n for
  2701. some integer i).
  2702. The native double product (double)x * (double)y is subject to three
  2703. rounding errors: on a sizeof(long)==8 box, each cast to double can lose
  2704. info, and even on a sizeof(long)==4 box, the multiplication can lose info.
  2705. But, unlike the native long product, it's not in *range* trouble: even
  2706. if sizeof(long)==32 (256-bit longs), the product easily fits in the
  2707. dynamic range of a double. So the leading 50 (or so) bits of the double
  2708. product are correct.
  2709. We check these two ways against each other, and declare victory if they're
  2710. approximately the same. Else, because the native long product is the only
  2711. one that can lose catastrophic amounts of information, it's the native long
  2712. product that must have overflowed.
  2713. */
  2714. long longprod = (long)((unsigned long)a * b);
  2715. double doubleprod = (double)a * (double)b;
  2716. double doubled_longprod = (double)longprod;
  2717. if (doubled_longprod == doubleprod) {
  2718. return 0;
  2719. }
  2720. const double diff = doubled_longprod - doubleprod;
  2721. const double absdiff = diff >= 0.0 ? diff : -diff;
  2722. const double absprod = doubleprod >= 0.0 ? doubleprod : -doubleprod;
  2723. if (32.0 * absdiff <= absprod) {
  2724. return 0;
  2725. }
  2726. return 1;
  2727. }
  2728. /*[clinic input]
  2729. math.prod
  2730. iterable: object
  2731. /
  2732. *
  2733. start: object(c_default="NULL") = 1
  2734. Calculate the product of all the elements in the input iterable.
  2735. The default start value for the product is 1.
  2736. When the iterable is empty, return the start value. This function is
  2737. intended specifically for use with numeric values and may reject
  2738. non-numeric types.
  2739. [clinic start generated code]*/
  2740. static PyObject *
  2741. math_prod_impl(PyObject *module, PyObject *iterable, PyObject *start)
  2742. /*[clinic end generated code: output=36153bedac74a198 input=4c5ab0682782ed54]*/
  2743. {
  2744. PyObject *result = start;
  2745. PyObject *temp, *item, *iter;
  2746. iter = PyObject_GetIter(iterable);
  2747. if (iter == NULL) {
  2748. return NULL;
  2749. }
  2750. if (result == NULL) {
  2751. result = _PyLong_GetOne();
  2752. }
  2753. Py_INCREF(result);
  2754. #ifndef SLOW_PROD
  2755. /* Fast paths for integers keeping temporary products in C.
  2756. * Assumes all inputs are the same type.
  2757. * If the assumption fails, default to use PyObjects instead.
  2758. */
  2759. if (PyLong_CheckExact(result)) {
  2760. int overflow;
  2761. long i_result = PyLong_AsLongAndOverflow(result, &overflow);
  2762. /* If this already overflowed, don't even enter the loop. */
  2763. if (overflow == 0) {
  2764. Py_SETREF(result, NULL);
  2765. }
  2766. /* Loop over all the items in the iterable until we finish, we overflow
  2767. * or we found a non integer element */
  2768. while (result == NULL) {
  2769. item = PyIter_Next(iter);
  2770. if (item == NULL) {
  2771. Py_DECREF(iter);
  2772. if (PyErr_Occurred()) {
  2773. return NULL;
  2774. }
  2775. return PyLong_FromLong(i_result);
  2776. }
  2777. if (PyLong_CheckExact(item)) {
  2778. long b = PyLong_AsLongAndOverflow(item, &overflow);
  2779. if (overflow == 0 && !_check_long_mult_overflow(i_result, b)) {
  2780. long x = i_result * b;
  2781. i_result = x;
  2782. Py_DECREF(item);
  2783. continue;
  2784. }
  2785. }
  2786. /* Either overflowed or is not an int.
  2787. * Restore real objects and process normally */
  2788. result = PyLong_FromLong(i_result);
  2789. if (result == NULL) {
  2790. Py_DECREF(item);
  2791. Py_DECREF(iter);
  2792. return NULL;
  2793. }
  2794. temp = PyNumber_Multiply(result, item);
  2795. Py_DECREF(result);
  2796. Py_DECREF(item);
  2797. result = temp;
  2798. if (result == NULL) {
  2799. Py_DECREF(iter);
  2800. return NULL;
  2801. }
  2802. }
  2803. }
  2804. /* Fast paths for floats keeping temporary products in C.
  2805. * Assumes all inputs are the same type.
  2806. * If the assumption fails, default to use PyObjects instead.
  2807. */
  2808. if (PyFloat_CheckExact(result)) {
  2809. double f_result = PyFloat_AS_DOUBLE(result);
  2810. Py_SETREF(result, NULL);
  2811. while(result == NULL) {
  2812. item = PyIter_Next(iter);
  2813. if (item == NULL) {
  2814. Py_DECREF(iter);
  2815. if (PyErr_Occurred()) {
  2816. return NULL;
  2817. }
  2818. return PyFloat_FromDouble(f_result);
  2819. }
  2820. if (PyFloat_CheckExact(item)) {
  2821. f_result *= PyFloat_AS_DOUBLE(item);
  2822. Py_DECREF(item);
  2823. continue;
  2824. }
  2825. if (PyLong_CheckExact(item)) {
  2826. long value;
  2827. int overflow;
  2828. value = PyLong_AsLongAndOverflow(item, &overflow);
  2829. if (!overflow) {
  2830. f_result *= (double)value;
  2831. Py_DECREF(item);
  2832. continue;
  2833. }
  2834. }
  2835. result = PyFloat_FromDouble(f_result);
  2836. if (result == NULL) {
  2837. Py_DECREF(item);
  2838. Py_DECREF(iter);
  2839. return NULL;
  2840. }
  2841. temp = PyNumber_Multiply(result, item);
  2842. Py_DECREF(result);
  2843. Py_DECREF(item);
  2844. result = temp;
  2845. if (result == NULL) {
  2846. Py_DECREF(iter);
  2847. return NULL;
  2848. }
  2849. }
  2850. }
  2851. #endif
  2852. /* Consume rest of the iterable (if any) that could not be handled
  2853. * by specialized functions above.*/
  2854. for(;;) {
  2855. item = PyIter_Next(iter);
  2856. if (item == NULL) {
  2857. /* error, or end-of-sequence */
  2858. if (PyErr_Occurred()) {
  2859. Py_SETREF(result, NULL);
  2860. }
  2861. break;
  2862. }
  2863. temp = PyNumber_Multiply(result, item);
  2864. Py_DECREF(result);
  2865. Py_DECREF(item);
  2866. result = temp;
  2867. if (result == NULL)
  2868. break;
  2869. }
  2870. Py_DECREF(iter);
  2871. return result;
  2872. }
  2873. /* least significant 64 bits of the odd part of factorial(n), for n in range(128).
  2874. Python code to generate the values:
  2875. import math
  2876. for n in range(128):
  2877. fac = math.factorial(n)
  2878. fac_odd_part = fac // (fac & -fac)
  2879. reduced_fac_odd_part = fac_odd_part % (2**64)
  2880. print(f"{reduced_fac_odd_part:#018x}u")
  2881. */
  2882. static const uint64_t reduced_factorial_odd_part[] = {
  2883. 0x0000000000000001u, 0x0000000000000001u, 0x0000000000000001u, 0x0000000000000003u,
  2884. 0x0000000000000003u, 0x000000000000000fu, 0x000000000000002du, 0x000000000000013bu,
  2885. 0x000000000000013bu, 0x0000000000000b13u, 0x000000000000375fu, 0x0000000000026115u,
  2886. 0x000000000007233fu, 0x00000000005cca33u, 0x0000000002898765u, 0x00000000260eeeebu,
  2887. 0x00000000260eeeebu, 0x0000000286fddd9bu, 0x00000016beecca73u, 0x000001b02b930689u,
  2888. 0x00000870d9df20adu, 0x0000b141df4dae31u, 0x00079dd498567c1bu, 0x00af2e19afc5266du,
  2889. 0x020d8a4d0f4f7347u, 0x335281867ec241efu, 0x9b3093d46fdd5923u, 0x5e1f9767cc5866b1u,
  2890. 0x92dd23d6966aced7u, 0xa30d0f4f0a196e5bu, 0x8dc3e5a1977d7755u, 0x2ab8ce915831734bu,
  2891. 0x2ab8ce915831734bu, 0x81d2a0bc5e5fdcabu, 0x9efcac82445da75bu, 0xbc8b95cf58cde171u,
  2892. 0xa0e8444a1f3cecf9u, 0x4191deb683ce3ffdu, 0xddd3878bc84ebfc7u, 0xcb39a64b83ff3751u,
  2893. 0xf8203f7993fc1495u, 0xbd2a2a78b35f4bddu, 0x84757be6b6d13921u, 0x3fbbcfc0b524988bu,
  2894. 0xbd11ed47c8928df9u, 0x3c26b59e41c2f4c5u, 0x677a5137e883fdb3u, 0xff74e943b03b93ddu,
  2895. 0xfe5ebbcb10b2bb97u, 0xb021f1de3235e7e7u, 0x33509eb2e743a58fu, 0x390f9da41279fb7du,
  2896. 0xe5cb0154f031c559u, 0x93074695ba4ddb6du, 0x81c471caa636247fu, 0xe1347289b5a1d749u,
  2897. 0x286f21c3f76ce2ffu, 0x00be84a2173e8ac7u, 0x1595065ca215b88bu, 0xf95877595b018809u,
  2898. 0x9c2efe3c5516f887u, 0x373294604679382bu, 0xaf1ff7a888adcd35u, 0x18ddf279a2c5800bu,
  2899. 0x18ddf279a2c5800bu, 0x505a90e2542582cbu, 0x5bacad2cd8d5dc2bu, 0xfe3152bcbff89f41u,
  2900. 0xe1467e88bf829351u, 0xb8001adb9e31b4d5u, 0x2803ac06a0cbb91fu, 0x1904b5d698805799u,
  2901. 0xe12a648b5c831461u, 0x3516abbd6160cfa9u, 0xac46d25f12fe036du, 0x78bfa1da906b00efu,
  2902. 0xf6390338b7f111bdu, 0x0f25f80f538255d9u, 0x4ec8ca55b8db140fu, 0x4ff670740b9b30a1u,
  2903. 0x8fd032443a07f325u, 0x80dfe7965c83eeb5u, 0xa3dc1714d1213afdu, 0x205b7bbfcdc62007u,
  2904. 0xa78126bbe140a093u, 0x9de1dc61ca7550cfu, 0x84f0046d01b492c5u, 0x2d91810b945de0f3u,
  2905. 0xf5408b7f6008aa71u, 0x43707f4863034149u, 0xdac65fb9679279d5u, 0xc48406e7d1114eb7u,
  2906. 0xa7dc9ed3c88e1271u, 0xfb25b2efdb9cb30du, 0x1bebda0951c4df63u, 0x5c85e975580ee5bdu,
  2907. 0x1591bc60082cb137u, 0x2c38606318ef25d7u, 0x76ca72f7c5c63e27u, 0xf04a75d17baa0915u,
  2908. 0x77458175139ae30du, 0x0e6c1330bc1b9421u, 0xdf87d2b5797e8293u, 0xefa5c703e1e68925u,
  2909. 0x2b6b1b3278b4f6e1u, 0xceee27b382394249u, 0xd74e3829f5dab91du, 0xfdb17989c26b5f1fu,
  2910. 0xc1b7d18781530845u, 0x7b4436b2105a8561u, 0x7ba7c0418372a7d7u, 0x9dbc5c67feb6c639u,
  2911. 0x502686d7f6ff6b8fu, 0x6101855406be7a1fu, 0x9956afb5806930e7u, 0xe1f0ee88af40f7c5u,
  2912. 0x984b057bda5c1151u, 0x9a49819acc13ea05u, 0x8ef0dead0896ef27u, 0x71f7826efe292b21u,
  2913. 0xad80a480e46986efu, 0x01cdc0ebf5e0c6f7u, 0x6e06f839968f68dbu, 0xdd5943ab56e76139u,
  2914. 0xcdcf31bf8604c5e7u, 0x7e2b4a847054a1cbu, 0x0ca75697a4d3d0f5u, 0x4703f53ac514a98bu,
  2915. };
  2916. /* inverses of reduced_factorial_odd_part values modulo 2**64.
  2917. Python code to generate the values:
  2918. import math
  2919. for n in range(128):
  2920. fac = math.factorial(n)
  2921. fac_odd_part = fac // (fac & -fac)
  2922. inverted_fac_odd_part = pow(fac_odd_part, -1, 2**64)
  2923. print(f"{inverted_fac_odd_part:#018x}u")
  2924. */
  2925. static const uint64_t inverted_factorial_odd_part[] = {
  2926. 0x0000000000000001u, 0x0000000000000001u, 0x0000000000000001u, 0xaaaaaaaaaaaaaaabu,
  2927. 0xaaaaaaaaaaaaaaabu, 0xeeeeeeeeeeeeeeefu, 0x4fa4fa4fa4fa4fa5u, 0x2ff2ff2ff2ff2ff3u,
  2928. 0x2ff2ff2ff2ff2ff3u, 0x938cc70553e3771bu, 0xb71c27cddd93e49fu, 0xb38e3229fcdee63du,
  2929. 0xe684bb63544a4cbfu, 0xc2f684917ca340fbu, 0xf747c9cba417526du, 0xbb26eb51d7bd49c3u,
  2930. 0xbb26eb51d7bd49c3u, 0xb0a7efb985294093u, 0xbe4b8c69f259eabbu, 0x6854d17ed6dc4fb9u,
  2931. 0xe1aa904c915f4325u, 0x3b8206df131cead1u, 0x79c6009fea76fe13u, 0xd8c5d381633cd365u,
  2932. 0x4841f12b21144677u, 0x4a91ff68200b0d0fu, 0x8f9513a58c4f9e8bu, 0x2b3e690621a42251u,
  2933. 0x4f520f00e03c04e7u, 0x2edf84ee600211d3u, 0xadcaa2764aaacdfdu, 0x161f4f9033f4fe63u,
  2934. 0x161f4f9033f4fe63u, 0xbada2932ea4d3e03u, 0xcec189f3efaa30d3u, 0xf7475bb68330bf91u,
  2935. 0x37eb7bf7d5b01549u, 0x46b35660a4e91555u, 0xa567c12d81f151f7u, 0x4c724007bb2071b1u,
  2936. 0x0f4a0cce58a016bdu, 0xfa21068e66106475u, 0x244ab72b5a318ae1u, 0x366ce67e080d0f23u,
  2937. 0xd666fdae5dd2a449u, 0xd740ddd0acc06a0du, 0xb050bbbb28e6f97bu, 0x70b003fe890a5c75u,
  2938. 0xd03aabff83037427u, 0x13ec4ca72c783bd7u, 0x90282c06afdbd96fu, 0x4414ddb9db4a95d5u,
  2939. 0xa2c68735ae6832e9u, 0xbf72d71455676665u, 0xa8469fab6b759b7fu, 0xc1e55b56e606caf9u,
  2940. 0x40455630fc4a1cffu, 0x0120a7b0046d16f7u, 0xa7c3553b08faef23u, 0x9f0bfd1b08d48639u,
  2941. 0xa433ffce9a304d37u, 0xa22ad1d53915c683u, 0xcb6cbc723ba5dd1du, 0x547fb1b8ab9d0ba3u,
  2942. 0x547fb1b8ab9d0ba3u, 0x8f15a826498852e3u, 0x32e1a03f38880283u, 0x3de4cce63283f0c1u,
  2943. 0x5dfe6667e4da95b1u, 0xfda6eeeef479e47du, 0xf14de991cc7882dfu, 0xe68db79247630ca9u,
  2944. 0xa7d6db8207ee8fa1u, 0x255e1f0fcf034499u, 0xc9a8990e43dd7e65u, 0x3279b6f289702e0fu,
  2945. 0xe7b5905d9b71b195u, 0x03025ba41ff0da69u, 0xb7df3d6d3be55aefu, 0xf89b212ebff2b361u,
  2946. 0xfe856d095996f0adu, 0xd6e533e9fdf20f9du, 0xf8c0e84a63da3255u, 0xa677876cd91b4db7u,
  2947. 0x07ed4f97780d7d9bu, 0x90a8705f258db62fu, 0xa41bbb2be31b1c0du, 0x6ec28690b038383bu,
  2948. 0xdb860c3bb2edd691u, 0x0838286838a980f9u, 0x558417a74b36f77du, 0x71779afc3646ef07u,
  2949. 0x743cda377ccb6e91u, 0x7fdf9f3fe89153c5u, 0xdc97d25df49b9a4bu, 0x76321a778eb37d95u,
  2950. 0x7cbb5e27da3bd487u, 0x9cff4ade1a009de7u, 0x70eb166d05c15197u, 0xdcf0460b71d5fe3du,
  2951. 0x5ac1ee5260b6a3c5u, 0xc922dedfdd78efe1u, 0xe5d381dc3b8eeb9bu, 0xd57e5347bafc6aadu,
  2952. 0x86939040983acd21u, 0x395b9d69740a4ff9u, 0x1467299c8e43d135u, 0x5fe440fcad975cdfu,
  2953. 0xcaa9a39794a6ca8du, 0xf61dbd640868dea1u, 0xac09d98d74843be7u, 0x2b103b9e1a6b4809u,
  2954. 0x2ab92d16960f536fu, 0x6653323d5e3681dfu, 0xefd48c1c0624e2d7u, 0xa496fefe04816f0du,
  2955. 0x1754a7b07bbdd7b1u, 0x23353c829a3852cdu, 0xbf831261abd59097u, 0x57a8e656df0618e1u,
  2956. 0x16e9206c3100680fu, 0xadad4c6ee921dac7u, 0x635f2b3860265353u, 0xdd6d0059f44b3d09u,
  2957. 0xac4dd6b894447dd7u, 0x42ea183eeaa87be3u, 0x15612d1550ee5b5du, 0x226fa19d656cb623u,
  2958. };
  2959. /* exponent of the largest power of 2 dividing factorial(n), for n in range(68)
  2960. Python code to generate the values:
  2961. import math
  2962. for n in range(128):
  2963. fac = math.factorial(n)
  2964. fac_trailing_zeros = (fac & -fac).bit_length() - 1
  2965. print(fac_trailing_zeros)
  2966. */
  2967. static const uint8_t factorial_trailing_zeros[] = {
  2968. 0, 0, 1, 1, 3, 3, 4, 4, 7, 7, 8, 8, 10, 10, 11, 11, // 0-15
  2969. 15, 15, 16, 16, 18, 18, 19, 19, 22, 22, 23, 23, 25, 25, 26, 26, // 16-31
  2970. 31, 31, 32, 32, 34, 34, 35, 35, 38, 38, 39, 39, 41, 41, 42, 42, // 32-47
  2971. 46, 46, 47, 47, 49, 49, 50, 50, 53, 53, 54, 54, 56, 56, 57, 57, // 48-63
  2972. 63, 63, 64, 64, 66, 66, 67, 67, 70, 70, 71, 71, 73, 73, 74, 74, // 64-79
  2973. 78, 78, 79, 79, 81, 81, 82, 82, 85, 85, 86, 86, 88, 88, 89, 89, // 80-95
  2974. 94, 94, 95, 95, 97, 97, 98, 98, 101, 101, 102, 102, 104, 104, 105, 105, // 96-111
  2975. 109, 109, 110, 110, 112, 112, 113, 113, 116, 116, 117, 117, 119, 119, 120, 120, // 112-127
  2976. };
  2977. /* Number of permutations and combinations.
  2978. * P(n, k) = n! / (n-k)!
  2979. * C(n, k) = P(n, k) / k!
  2980. */
  2981. /* Calculate C(n, k) for n in the 63-bit range. */
  2982. static PyObject *
  2983. perm_comb_small(unsigned long long n, unsigned long long k, int iscomb)
  2984. {
  2985. if (k == 0) {
  2986. return PyLong_FromLong(1);
  2987. }
  2988. /* For small enough n and k the result fits in the 64-bit range and can
  2989. * be calculated without allocating intermediate PyLong objects. */
  2990. if (iscomb) {
  2991. /* Maps k to the maximal n so that 2*k-1 <= n <= 127 and C(n, k)
  2992. * fits into a uint64_t. Exclude k = 1, because the second fast
  2993. * path is faster for this case.*/
  2994. static const unsigned char fast_comb_limits1[] = {
  2995. 0, 0, 127, 127, 127, 127, 127, 127, // 0-7
  2996. 127, 127, 127, 127, 127, 127, 127, 127, // 8-15
  2997. 116, 105, 97, 91, 86, 82, 78, 76, // 16-23
  2998. 74, 72, 71, 70, 69, 68, 68, 67, // 24-31
  2999. 67, 67, 67, // 32-34
  3000. };
  3001. if (k < Py_ARRAY_LENGTH(fast_comb_limits1) && n <= fast_comb_limits1[k]) {
  3002. /*
  3003. comb(n, k) fits into a uint64_t. We compute it as
  3004. comb_odd_part << shift
  3005. where 2**shift is the largest power of two dividing comb(n, k)
  3006. and comb_odd_part is comb(n, k) >> shift. comb_odd_part can be
  3007. calculated efficiently via arithmetic modulo 2**64, using three
  3008. lookups and two uint64_t multiplications.
  3009. */
  3010. uint64_t comb_odd_part = reduced_factorial_odd_part[n]
  3011. * inverted_factorial_odd_part[k]
  3012. * inverted_factorial_odd_part[n - k];
  3013. int shift = factorial_trailing_zeros[n]
  3014. - factorial_trailing_zeros[k]
  3015. - factorial_trailing_zeros[n - k];
  3016. return PyLong_FromUnsignedLongLong(comb_odd_part << shift);
  3017. }
  3018. /* Maps k to the maximal n so that 2*k-1 <= n <= 127 and C(n, k)*k
  3019. * fits into a long long (which is at least 64 bit). Only contains
  3020. * items larger than in fast_comb_limits1. */
  3021. static const unsigned long long fast_comb_limits2[] = {
  3022. 0, ULLONG_MAX, 4294967296ULL, 3329022, 102570, 13467, 3612, 1449, // 0-7
  3023. 746, 453, 308, 227, 178, 147, // 8-13
  3024. };
  3025. if (k < Py_ARRAY_LENGTH(fast_comb_limits2) && n <= fast_comb_limits2[k]) {
  3026. /* C(n, k) = C(n, k-1) * (n-k+1) / k */
  3027. unsigned long long result = n;
  3028. for (unsigned long long i = 1; i < k;) {
  3029. result *= --n;
  3030. result /= ++i;
  3031. }
  3032. return PyLong_FromUnsignedLongLong(result);
  3033. }
  3034. }
  3035. else {
  3036. /* Maps k to the maximal n so that k <= n and P(n, k)
  3037. * fits into a long long (which is at least 64 bit). */
  3038. static const unsigned long long fast_perm_limits[] = {
  3039. 0, ULLONG_MAX, 4294967296ULL, 2642246, 65537, 7133, 1627, 568, // 0-7
  3040. 259, 142, 88, 61, 45, 36, 30, 26, // 8-15
  3041. 24, 22, 21, 20, 20, // 16-20
  3042. };
  3043. if (k < Py_ARRAY_LENGTH(fast_perm_limits) && n <= fast_perm_limits[k]) {
  3044. if (n <= 127) {
  3045. /* P(n, k) fits into a uint64_t. */
  3046. uint64_t perm_odd_part = reduced_factorial_odd_part[n]
  3047. * inverted_factorial_odd_part[n - k];
  3048. int shift = factorial_trailing_zeros[n]
  3049. - factorial_trailing_zeros[n - k];
  3050. return PyLong_FromUnsignedLongLong(perm_odd_part << shift);
  3051. }
  3052. /* P(n, k) = P(n, k-1) * (n-k+1) */
  3053. unsigned long long result = n;
  3054. for (unsigned long long i = 1; i < k;) {
  3055. result *= --n;
  3056. ++i;
  3057. }
  3058. return PyLong_FromUnsignedLongLong(result);
  3059. }
  3060. }
  3061. /* For larger n use recursive formulas:
  3062. *
  3063. * P(n, k) = P(n, j) * P(n-j, k-j)
  3064. * C(n, k) = C(n, j) * C(n-j, k-j) // C(k, j)
  3065. */
  3066. unsigned long long j = k / 2;
  3067. PyObject *a, *b;
  3068. a = perm_comb_small(n, j, iscomb);
  3069. if (a == NULL) {
  3070. return NULL;
  3071. }
  3072. b = perm_comb_small(n - j, k - j, iscomb);
  3073. if (b == NULL) {
  3074. goto error;
  3075. }
  3076. Py_SETREF(a, PyNumber_Multiply(a, b));
  3077. Py_DECREF(b);
  3078. if (iscomb && a != NULL) {
  3079. b = perm_comb_small(k, j, 1);
  3080. if (b == NULL) {
  3081. goto error;
  3082. }
  3083. Py_SETREF(a, PyNumber_FloorDivide(a, b));
  3084. Py_DECREF(b);
  3085. }
  3086. return a;
  3087. error:
  3088. Py_DECREF(a);
  3089. return NULL;
  3090. }
  3091. /* Calculate P(n, k) or C(n, k) using recursive formulas.
  3092. * It is more efficient than sequential multiplication thanks to
  3093. * Karatsuba multiplication.
  3094. */
  3095. static PyObject *
  3096. perm_comb(PyObject *n, unsigned long long k, int iscomb)
  3097. {
  3098. if (k == 0) {
  3099. return PyLong_FromLong(1);
  3100. }
  3101. if (k == 1) {
  3102. return Py_NewRef(n);
  3103. }
  3104. /* P(n, k) = P(n, j) * P(n-j, k-j) */
  3105. /* C(n, k) = C(n, j) * C(n-j, k-j) // C(k, j) */
  3106. unsigned long long j = k / 2;
  3107. PyObject *a, *b;
  3108. a = perm_comb(n, j, iscomb);
  3109. if (a == NULL) {
  3110. return NULL;
  3111. }
  3112. PyObject *t = PyLong_FromUnsignedLongLong(j);
  3113. if (t == NULL) {
  3114. goto error;
  3115. }
  3116. n = PyNumber_Subtract(n, t);
  3117. Py_DECREF(t);
  3118. if (n == NULL) {
  3119. goto error;
  3120. }
  3121. b = perm_comb(n, k - j, iscomb);
  3122. Py_DECREF(n);
  3123. if (b == NULL) {
  3124. goto error;
  3125. }
  3126. Py_SETREF(a, PyNumber_Multiply(a, b));
  3127. Py_DECREF(b);
  3128. if (iscomb && a != NULL) {
  3129. b = perm_comb_small(k, j, 1);
  3130. if (b == NULL) {
  3131. goto error;
  3132. }
  3133. Py_SETREF(a, PyNumber_FloorDivide(a, b));
  3134. Py_DECREF(b);
  3135. }
  3136. return a;
  3137. error:
  3138. Py_DECREF(a);
  3139. return NULL;
  3140. }
  3141. /*[clinic input]
  3142. math.perm
  3143. n: object
  3144. k: object = None
  3145. /
  3146. Number of ways to choose k items from n items without repetition and with order.
  3147. Evaluates to n! / (n - k)! when k <= n and evaluates
  3148. to zero when k > n.
  3149. If k is not specified or is None, then k defaults to n
  3150. and the function returns n!.
  3151. Raises TypeError if either of the arguments are not integers.
  3152. Raises ValueError if either of the arguments are negative.
  3153. [clinic start generated code]*/
  3154. static PyObject *
  3155. math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
  3156. /*[clinic end generated code: output=e021a25469653e23 input=5311c5a00f359b53]*/
  3157. {
  3158. PyObject *result = NULL;
  3159. int overflow, cmp;
  3160. long long ki, ni;
  3161. if (k == Py_None) {
  3162. return math_factorial(module, n);
  3163. }
  3164. n = PyNumber_Index(n);
  3165. if (n == NULL) {
  3166. return NULL;
  3167. }
  3168. k = PyNumber_Index(k);
  3169. if (k == NULL) {
  3170. Py_DECREF(n);
  3171. return NULL;
  3172. }
  3173. assert(PyLong_CheckExact(n) && PyLong_CheckExact(k));
  3174. if (_PyLong_IsNegative((PyLongObject *)n)) {
  3175. PyErr_SetString(PyExc_ValueError,
  3176. "n must be a non-negative integer");
  3177. goto error;
  3178. }
  3179. if (_PyLong_IsNegative((PyLongObject *)k)) {
  3180. PyErr_SetString(PyExc_ValueError,
  3181. "k must be a non-negative integer");
  3182. goto error;
  3183. }
  3184. cmp = PyObject_RichCompareBool(n, k, Py_LT);
  3185. if (cmp != 0) {
  3186. if (cmp > 0) {
  3187. result = PyLong_FromLong(0);
  3188. goto done;
  3189. }
  3190. goto error;
  3191. }
  3192. ki = PyLong_AsLongLongAndOverflow(k, &overflow);
  3193. assert(overflow >= 0 && !PyErr_Occurred());
  3194. if (overflow > 0) {
  3195. PyErr_Format(PyExc_OverflowError,
  3196. "k must not exceed %lld",
  3197. LLONG_MAX);
  3198. goto error;
  3199. }
  3200. assert(ki >= 0);
  3201. ni = PyLong_AsLongLongAndOverflow(n, &overflow);
  3202. assert(overflow >= 0 && !PyErr_Occurred());
  3203. if (!overflow && ki > 1) {
  3204. assert(ni >= 0);
  3205. result = perm_comb_small((unsigned long long)ni,
  3206. (unsigned long long)ki, 0);
  3207. }
  3208. else {
  3209. result = perm_comb(n, (unsigned long long)ki, 0);
  3210. }
  3211. done:
  3212. Py_DECREF(n);
  3213. Py_DECREF(k);
  3214. return result;
  3215. error:
  3216. Py_DECREF(n);
  3217. Py_DECREF(k);
  3218. return NULL;
  3219. }
  3220. /*[clinic input]
  3221. math.comb
  3222. n: object
  3223. k: object
  3224. /
  3225. Number of ways to choose k items from n items without repetition and without order.
  3226. Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
  3227. to zero when k > n.
  3228. Also called the binomial coefficient because it is equivalent
  3229. to the coefficient of k-th term in polynomial expansion of the
  3230. expression (1 + x)**n.
  3231. Raises TypeError if either of the arguments are not integers.
  3232. Raises ValueError if either of the arguments are negative.
  3233. [clinic start generated code]*/
  3234. static PyObject *
  3235. math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
  3236. /*[clinic end generated code: output=bd2cec8d854f3493 input=9a05315af2518709]*/
  3237. {
  3238. PyObject *result = NULL, *temp;
  3239. int overflow, cmp;
  3240. long long ki, ni;
  3241. n = PyNumber_Index(n);
  3242. if (n == NULL) {
  3243. return NULL;
  3244. }
  3245. k = PyNumber_Index(k);
  3246. if (k == NULL) {
  3247. Py_DECREF(n);
  3248. return NULL;
  3249. }
  3250. assert(PyLong_CheckExact(n) && PyLong_CheckExact(k));
  3251. if (_PyLong_IsNegative((PyLongObject *)n)) {
  3252. PyErr_SetString(PyExc_ValueError,
  3253. "n must be a non-negative integer");
  3254. goto error;
  3255. }
  3256. if (_PyLong_IsNegative((PyLongObject *)k)) {
  3257. PyErr_SetString(PyExc_ValueError,
  3258. "k must be a non-negative integer");
  3259. goto error;
  3260. }
  3261. ni = PyLong_AsLongLongAndOverflow(n, &overflow);
  3262. assert(overflow >= 0 && !PyErr_Occurred());
  3263. if (!overflow) {
  3264. assert(ni >= 0);
  3265. ki = PyLong_AsLongLongAndOverflow(k, &overflow);
  3266. assert(overflow >= 0 && !PyErr_Occurred());
  3267. if (overflow || ki > ni) {
  3268. result = PyLong_FromLong(0);
  3269. goto done;
  3270. }
  3271. assert(ki >= 0);
  3272. ki = Py_MIN(ki, ni - ki);
  3273. if (ki > 1) {
  3274. result = perm_comb_small((unsigned long long)ni,
  3275. (unsigned long long)ki, 1);
  3276. goto done;
  3277. }
  3278. /* For k == 1 just return the original n in perm_comb(). */
  3279. }
  3280. else {
  3281. /* k = min(k, n - k) */
  3282. temp = PyNumber_Subtract(n, k);
  3283. if (temp == NULL) {
  3284. goto error;
  3285. }
  3286. assert(PyLong_Check(temp));
  3287. if (_PyLong_IsNegative((PyLongObject *)temp)) {
  3288. Py_DECREF(temp);
  3289. result = PyLong_FromLong(0);
  3290. goto done;
  3291. }
  3292. cmp = PyObject_RichCompareBool(temp, k, Py_LT);
  3293. if (cmp > 0) {
  3294. Py_SETREF(k, temp);
  3295. }
  3296. else {
  3297. Py_DECREF(temp);
  3298. if (cmp < 0) {
  3299. goto error;
  3300. }
  3301. }
  3302. ki = PyLong_AsLongLongAndOverflow(k, &overflow);
  3303. assert(overflow >= 0 && !PyErr_Occurred());
  3304. if (overflow) {
  3305. PyErr_Format(PyExc_OverflowError,
  3306. "min(n - k, k) must not exceed %lld",
  3307. LLONG_MAX);
  3308. goto error;
  3309. }
  3310. assert(ki >= 0);
  3311. }
  3312. result = perm_comb(n, (unsigned long long)ki, 1);
  3313. done:
  3314. Py_DECREF(n);
  3315. Py_DECREF(k);
  3316. return result;
  3317. error:
  3318. Py_DECREF(n);
  3319. Py_DECREF(k);
  3320. return NULL;
  3321. }
  3322. /*[clinic input]
  3323. math.nextafter
  3324. x: double
  3325. y: double
  3326. /
  3327. *
  3328. steps: object = None
  3329. Return the floating-point value the given number of steps after x towards y.
  3330. If steps is not specified or is None, it defaults to 1.
  3331. Raises a TypeError, if x or y is not a double, or if steps is not an integer.
  3332. Raises ValueError if steps is negative.
  3333. [clinic start generated code]*/
  3334. static PyObject *
  3335. math_nextafter_impl(PyObject *module, double x, double y, PyObject *steps)
  3336. /*[clinic end generated code: output=cc6511f02afc099e input=7f2a5842112af2b4]*/
  3337. {
  3338. #if defined(_AIX)
  3339. if (x == y) {
  3340. /* On AIX 7.1, libm nextafter(-0.0, +0.0) returns -0.0.
  3341. Bug fixed in bos.adt.libm 7.2.2.0 by APAR IV95512. */
  3342. return PyFloat_FromDouble(y);
  3343. }
  3344. if (Py_IS_NAN(x)) {
  3345. return PyFloat_FromDouble(x);
  3346. }
  3347. if (Py_IS_NAN(y)) {
  3348. return PyFloat_FromDouble(y);
  3349. }
  3350. #endif
  3351. if (steps == Py_None) {
  3352. // fast path: we default to one step.
  3353. return PyFloat_FromDouble(nextafter(x, y));
  3354. }
  3355. steps = PyNumber_Index(steps);
  3356. if (steps == NULL) {
  3357. return NULL;
  3358. }
  3359. assert(PyLong_CheckExact(steps));
  3360. if (_PyLong_IsNegative((PyLongObject *)steps)) {
  3361. PyErr_SetString(PyExc_ValueError,
  3362. "steps must be a non-negative integer");
  3363. Py_DECREF(steps);
  3364. return NULL;
  3365. }
  3366. unsigned long long usteps_ull = PyLong_AsUnsignedLongLong(steps);
  3367. // Conveniently, uint64_t and double have the same number of bits
  3368. // on all the platforms we care about.
  3369. // So if an overflow occurs, we can just use UINT64_MAX.
  3370. Py_DECREF(steps);
  3371. if (usteps_ull >= UINT64_MAX) {
  3372. // This branch includes the case where an error occurred, since
  3373. // (unsigned long long)(-1) = ULLONG_MAX >= UINT64_MAX. Note that
  3374. // usteps_ull can be strictly larger than UINT64_MAX on a machine
  3375. // where unsigned long long has width > 64 bits.
  3376. if (PyErr_Occurred()) {
  3377. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  3378. PyErr_Clear();
  3379. }
  3380. else {
  3381. return NULL;
  3382. }
  3383. }
  3384. usteps_ull = UINT64_MAX;
  3385. }
  3386. assert(usteps_ull <= UINT64_MAX);
  3387. uint64_t usteps = (uint64_t)usteps_ull;
  3388. if (usteps == 0) {
  3389. return PyFloat_FromDouble(x);
  3390. }
  3391. if (Py_IS_NAN(x)) {
  3392. return PyFloat_FromDouble(x);
  3393. }
  3394. if (Py_IS_NAN(y)) {
  3395. return PyFloat_FromDouble(y);
  3396. }
  3397. // We assume that double and uint64_t have the same endianness.
  3398. // This is not guaranteed by the C-standard, but it is true for
  3399. // all platforms we care about. (The most likely form of violation
  3400. // would be a "mixed-endian" double.)
  3401. union pun {double f; uint64_t i;};
  3402. union pun ux = {x}, uy = {y};
  3403. if (ux.i == uy.i) {
  3404. return PyFloat_FromDouble(x);
  3405. }
  3406. const uint64_t sign_bit = 1ULL<<63;
  3407. uint64_t ax = ux.i & ~sign_bit;
  3408. uint64_t ay = uy.i & ~sign_bit;
  3409. // opposite signs
  3410. if (((ux.i ^ uy.i) & sign_bit)) {
  3411. // NOTE: ax + ay can never overflow, because their most significant bit
  3412. // ain't set.
  3413. if (ax + ay <= usteps) {
  3414. return PyFloat_FromDouble(uy.f);
  3415. // This comparison has to use <, because <= would get +0.0 vs -0.0
  3416. // wrong.
  3417. } else if (ax < usteps) {
  3418. union pun result = {.i = (uy.i & sign_bit) | (usteps - ax)};
  3419. return PyFloat_FromDouble(result.f);
  3420. } else {
  3421. ux.i -= usteps;
  3422. return PyFloat_FromDouble(ux.f);
  3423. }
  3424. // same sign
  3425. } else if (ax > ay) {
  3426. if (ax - ay >= usteps) {
  3427. ux.i -= usteps;
  3428. return PyFloat_FromDouble(ux.f);
  3429. } else {
  3430. return PyFloat_FromDouble(uy.f);
  3431. }
  3432. } else {
  3433. if (ay - ax >= usteps) {
  3434. ux.i += usteps;
  3435. return PyFloat_FromDouble(ux.f);
  3436. } else {
  3437. return PyFloat_FromDouble(uy.f);
  3438. }
  3439. }
  3440. }
  3441. /*[clinic input]
  3442. math.ulp -> double
  3443. x: double
  3444. /
  3445. Return the value of the least significant bit of the float x.
  3446. [clinic start generated code]*/
  3447. static double
  3448. math_ulp_impl(PyObject *module, double x)
  3449. /*[clinic end generated code: output=f5207867a9384dd4 input=31f9bfbbe373fcaa]*/
  3450. {
  3451. if (Py_IS_NAN(x)) {
  3452. return x;
  3453. }
  3454. x = fabs(x);
  3455. if (Py_IS_INFINITY(x)) {
  3456. return x;
  3457. }
  3458. double inf = Py_INFINITY;
  3459. double x2 = nextafter(x, inf);
  3460. if (Py_IS_INFINITY(x2)) {
  3461. /* special case: x is the largest positive representable float */
  3462. x2 = nextafter(x, -inf);
  3463. return x - x2;
  3464. }
  3465. return x2 - x;
  3466. }
  3467. static int
  3468. math_exec(PyObject *module)
  3469. {
  3470. math_module_state *state = get_math_module_state(module);
  3471. state->str___ceil__ = PyUnicode_InternFromString("__ceil__");
  3472. if (state->str___ceil__ == NULL) {
  3473. return -1;
  3474. }
  3475. state->str___floor__ = PyUnicode_InternFromString("__floor__");
  3476. if (state->str___floor__ == NULL) {
  3477. return -1;
  3478. }
  3479. state->str___trunc__ = PyUnicode_InternFromString("__trunc__");
  3480. if (state->str___trunc__ == NULL) {
  3481. return -1;
  3482. }
  3483. if (_PyModule_Add(module, "pi", PyFloat_FromDouble(Py_MATH_PI)) < 0) {
  3484. return -1;
  3485. }
  3486. if (_PyModule_Add(module, "e", PyFloat_FromDouble(Py_MATH_E)) < 0) {
  3487. return -1;
  3488. }
  3489. // 2pi
  3490. if (_PyModule_Add(module, "tau", PyFloat_FromDouble(Py_MATH_TAU)) < 0) {
  3491. return -1;
  3492. }
  3493. if (_PyModule_Add(module, "inf", PyFloat_FromDouble(Py_INFINITY)) < 0) {
  3494. return -1;
  3495. }
  3496. if (_PyModule_Add(module, "nan", PyFloat_FromDouble(fabs(Py_NAN))) < 0) {
  3497. return -1;
  3498. }
  3499. return 0;
  3500. }
  3501. static int
  3502. math_clear(PyObject *module)
  3503. {
  3504. math_module_state *state = get_math_module_state(module);
  3505. Py_CLEAR(state->str___ceil__);
  3506. Py_CLEAR(state->str___floor__);
  3507. Py_CLEAR(state->str___trunc__);
  3508. return 0;
  3509. }
  3510. static void
  3511. math_free(void *module)
  3512. {
  3513. math_clear((PyObject *)module);
  3514. }
  3515. static PyMethodDef math_methods[] = {
  3516. {"acos", math_acos, METH_O, math_acos_doc},
  3517. {"acosh", math_acosh, METH_O, math_acosh_doc},
  3518. {"asin", math_asin, METH_O, math_asin_doc},
  3519. {"asinh", math_asinh, METH_O, math_asinh_doc},
  3520. {"atan", math_atan, METH_O, math_atan_doc},
  3521. {"atan2", _PyCFunction_CAST(math_atan2), METH_FASTCALL, math_atan2_doc},
  3522. {"atanh", math_atanh, METH_O, math_atanh_doc},
  3523. {"cbrt", math_cbrt, METH_O, math_cbrt_doc},
  3524. MATH_CEIL_METHODDEF
  3525. {"copysign", _PyCFunction_CAST(math_copysign), METH_FASTCALL, math_copysign_doc},
  3526. {"cos", math_cos, METH_O, math_cos_doc},
  3527. {"cosh", math_cosh, METH_O, math_cosh_doc},
  3528. MATH_DEGREES_METHODDEF
  3529. MATH_DIST_METHODDEF
  3530. {"erf", math_erf, METH_O, math_erf_doc},
  3531. {"erfc", math_erfc, METH_O, math_erfc_doc},
  3532. {"exp", math_exp, METH_O, math_exp_doc},
  3533. {"exp2", math_exp2, METH_O, math_exp2_doc},
  3534. {"expm1", math_expm1, METH_O, math_expm1_doc},
  3535. {"fabs", math_fabs, METH_O, math_fabs_doc},
  3536. MATH_FACTORIAL_METHODDEF
  3537. MATH_FLOOR_METHODDEF
  3538. MATH_FMOD_METHODDEF
  3539. MATH_FREXP_METHODDEF
  3540. MATH_FSUM_METHODDEF
  3541. {"gamma", math_gamma, METH_O, math_gamma_doc},
  3542. {"gcd", _PyCFunction_CAST(math_gcd), METH_FASTCALL, math_gcd_doc},
  3543. {"hypot", _PyCFunction_CAST(math_hypot), METH_FASTCALL, math_hypot_doc},
  3544. MATH_ISCLOSE_METHODDEF
  3545. MATH_ISFINITE_METHODDEF
  3546. MATH_ISINF_METHODDEF
  3547. MATH_ISNAN_METHODDEF
  3548. MATH_ISQRT_METHODDEF
  3549. {"lcm", _PyCFunction_CAST(math_lcm), METH_FASTCALL, math_lcm_doc},
  3550. MATH_LDEXP_METHODDEF
  3551. {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
  3552. {"log", _PyCFunction_CAST(math_log), METH_FASTCALL, math_log_doc},
  3553. {"log1p", math_log1p, METH_O, math_log1p_doc},
  3554. MATH_LOG10_METHODDEF
  3555. MATH_LOG2_METHODDEF
  3556. MATH_MODF_METHODDEF
  3557. MATH_POW_METHODDEF
  3558. MATH_RADIANS_METHODDEF
  3559. {"remainder", _PyCFunction_CAST(math_remainder), METH_FASTCALL, math_remainder_doc},
  3560. {"sin", math_sin, METH_O, math_sin_doc},
  3561. {"sinh", math_sinh, METH_O, math_sinh_doc},
  3562. {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
  3563. {"tan", math_tan, METH_O, math_tan_doc},
  3564. {"tanh", math_tanh, METH_O, math_tanh_doc},
  3565. MATH_SUMPROD_METHODDEF
  3566. MATH_TRUNC_METHODDEF
  3567. MATH_PROD_METHODDEF
  3568. MATH_PERM_METHODDEF
  3569. MATH_COMB_METHODDEF
  3570. MATH_NEXTAFTER_METHODDEF
  3571. MATH_ULP_METHODDEF
  3572. {NULL, NULL} /* sentinel */
  3573. };
  3574. static PyModuleDef_Slot math_slots[] = {
  3575. {Py_mod_exec, math_exec},
  3576. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  3577. {0, NULL}
  3578. };
  3579. PyDoc_STRVAR(module_doc,
  3580. "This module provides access to the mathematical functions\n"
  3581. "defined by the C standard.");
  3582. static struct PyModuleDef mathmodule = {
  3583. PyModuleDef_HEAD_INIT,
  3584. .m_name = "math",
  3585. .m_doc = module_doc,
  3586. .m_size = sizeof(math_module_state),
  3587. .m_methods = math_methods,
  3588. .m_slots = math_slots,
  3589. .m_clear = math_clear,
  3590. .m_free = math_free,
  3591. };
  3592. PyMODINIT_FUNC
  3593. PyInit_math(void)
  3594. {
  3595. return PyModuleDef_Init(&mathmodule);
  3596. }