numbers.py 136 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596
  1. from __future__ import annotations
  2. import numbers
  3. import decimal
  4. import fractions
  5. import math
  6. import re as regex
  7. import sys
  8. from functools import lru_cache
  9. from .containers import Tuple
  10. from .sympify import (SympifyError, _sympy_converter, sympify, _convert_numpy_types,
  11. _sympify, _is_numpy_instance)
  12. from .singleton import S, Singleton
  13. from .basic import Basic
  14. from .expr import Expr, AtomicExpr
  15. from .evalf import pure_complex
  16. from .cache import cacheit, clear_cache
  17. from .decorators import _sympifyit
  18. from .logic import fuzzy_not
  19. from .kind import NumberKind
  20. from sympy.external.gmpy import SYMPY_INTS, HAS_GMPY, gmpy
  21. from sympy.multipledispatch import dispatch
  22. import mpmath
  23. import mpmath.libmp as mlib
  24. from mpmath.libmp import bitcount, round_nearest as rnd
  25. from mpmath.libmp.backend import MPZ
  26. from mpmath.libmp import mpf_pow, mpf_pi, mpf_e, phi_fixed
  27. from mpmath.ctx_mp import mpnumeric
  28. from mpmath.libmp.libmpf import (
  29. finf as _mpf_inf, fninf as _mpf_ninf,
  30. fnan as _mpf_nan, fzero, _normalize as mpf_normalize,
  31. prec_to_dps, dps_to_prec)
  32. from sympy.utilities.misc import as_int, debug, filldedent
  33. from .parameters import global_parameters
  34. _LOG2 = math.log(2)
  35. def comp(z1, z2, tol=None):
  36. r"""Return a bool indicating whether the error between z1 and z2
  37. is $\le$ ``tol``.
  38. Examples
  39. ========
  40. If ``tol`` is ``None`` then ``True`` will be returned if
  41. :math:`|z1 - z2|\times 10^p \le 5` where $p$ is minimum value of the
  42. decimal precision of each value.
  43. >>> from sympy import comp, pi
  44. >>> pi4 = pi.n(4); pi4
  45. 3.142
  46. >>> comp(_, 3.142)
  47. True
  48. >>> comp(pi4, 3.141)
  49. False
  50. >>> comp(pi4, 3.143)
  51. False
  52. A comparison of strings will be made
  53. if ``z1`` is a Number and ``z2`` is a string or ``tol`` is ''.
  54. >>> comp(pi4, 3.1415)
  55. True
  56. >>> comp(pi4, 3.1415, '')
  57. False
  58. When ``tol`` is provided and $z2$ is non-zero and
  59. :math:`|z1| > 1` the error is normalized by :math:`|z1|`:
  60. >>> abs(pi4 - 3.14)/pi4
  61. 0.000509791731426756
  62. >>> comp(pi4, 3.14, .001) # difference less than 0.1%
  63. True
  64. >>> comp(pi4, 3.14, .0005) # difference less than 0.1%
  65. False
  66. When :math:`|z1| \le 1` the absolute error is used:
  67. >>> 1/pi4
  68. 0.3183
  69. >>> abs(1/pi4 - 0.3183)/(1/pi4)
  70. 3.07371499106316e-5
  71. >>> abs(1/pi4 - 0.3183)
  72. 9.78393554684764e-6
  73. >>> comp(1/pi4, 0.3183, 1e-5)
  74. True
  75. To see if the absolute error between ``z1`` and ``z2`` is less
  76. than or equal to ``tol``, call this as ``comp(z1 - z2, 0, tol)``
  77. or ``comp(z1 - z2, tol=tol)``:
  78. >>> abs(pi4 - 3.14)
  79. 0.00160156249999988
  80. >>> comp(pi4 - 3.14, 0, .002)
  81. True
  82. >>> comp(pi4 - 3.14, 0, .001)
  83. False
  84. """
  85. if isinstance(z2, str):
  86. if not pure_complex(z1, or_real=True):
  87. raise ValueError('when z2 is a str z1 must be a Number')
  88. return str(z1) == z2
  89. if not z1:
  90. z1, z2 = z2, z1
  91. if not z1:
  92. return True
  93. if not tol:
  94. a, b = z1, z2
  95. if tol == '':
  96. return str(a) == str(b)
  97. if tol is None:
  98. a, b = sympify(a), sympify(b)
  99. if not all(i.is_number for i in (a, b)):
  100. raise ValueError('expecting 2 numbers')
  101. fa = a.atoms(Float)
  102. fb = b.atoms(Float)
  103. if not fa and not fb:
  104. # no floats -- compare exactly
  105. return a == b
  106. # get a to be pure_complex
  107. for _ in range(2):
  108. ca = pure_complex(a, or_real=True)
  109. if not ca:
  110. if fa:
  111. a = a.n(prec_to_dps(min([i._prec for i in fa])))
  112. ca = pure_complex(a, or_real=True)
  113. break
  114. else:
  115. fa, fb = fb, fa
  116. a, b = b, a
  117. cb = pure_complex(b)
  118. if not cb and fb:
  119. b = b.n(prec_to_dps(min([i._prec for i in fb])))
  120. cb = pure_complex(b, or_real=True)
  121. if ca and cb and (ca[1] or cb[1]):
  122. return all(comp(i, j) for i, j in zip(ca, cb))
  123. tol = 10**prec_to_dps(min(a._prec, getattr(b, '_prec', a._prec)))
  124. return int(abs(a - b)*tol) <= 5
  125. diff = abs(z1 - z2)
  126. az1 = abs(z1)
  127. if z2 and az1 > 1:
  128. return diff/az1 <= tol
  129. else:
  130. return diff <= tol
  131. def mpf_norm(mpf, prec):
  132. """Return the mpf tuple normalized appropriately for the indicated
  133. precision after doing a check to see if zero should be returned or
  134. not when the mantissa is 0. ``mpf_normlize`` always assumes that this
  135. is zero, but it may not be since the mantissa for mpf's values "+inf",
  136. "-inf" and "nan" have a mantissa of zero, too.
  137. Note: this is not intended to validate a given mpf tuple, so sending
  138. mpf tuples that were not created by mpmath may produce bad results. This
  139. is only a wrapper to ``mpf_normalize`` which provides the check for non-
  140. zero mpfs that have a 0 for the mantissa.
  141. """
  142. sign, man, expt, bc = mpf
  143. if not man:
  144. # hack for mpf_normalize which does not do this;
  145. # it assumes that if man is zero the result is 0
  146. # (see issue 6639)
  147. if not bc:
  148. return fzero
  149. else:
  150. # don't change anything; this should already
  151. # be a well formed mpf tuple
  152. return mpf
  153. # Necessary if mpmath is using the gmpy backend
  154. from mpmath.libmp.backend import MPZ
  155. rv = mpf_normalize(sign, MPZ(man), expt, bc, prec, rnd)
  156. return rv
  157. # TODO: we should use the warnings module
  158. _errdict = {"divide": False}
  159. def seterr(divide=False):
  160. """
  161. Should SymPy raise an exception on 0/0 or return a nan?
  162. divide == True .... raise an exception
  163. divide == False ... return nan
  164. """
  165. if _errdict["divide"] != divide:
  166. clear_cache()
  167. _errdict["divide"] = divide
  168. def _as_integer_ratio(p):
  169. neg_pow, man, expt, _ = getattr(p, '_mpf_', mpmath.mpf(p)._mpf_)
  170. p = [1, -1][neg_pow % 2]*man
  171. if expt < 0:
  172. q = 2**-expt
  173. else:
  174. q = 1
  175. p *= 2**expt
  176. return int(p), int(q)
  177. def _decimal_to_Rational_prec(dec):
  178. """Convert an ordinary decimal instance to a Rational."""
  179. if not dec.is_finite():
  180. raise TypeError("dec must be finite, got %s." % dec)
  181. s, d, e = dec.as_tuple()
  182. prec = len(d)
  183. if e >= 0: # it's an integer
  184. rv = Integer(int(dec))
  185. else:
  186. s = (-1)**s
  187. d = sum([di*10**i for i, di in enumerate(reversed(d))])
  188. rv = Rational(s*d, 10**-e)
  189. return rv, prec
  190. _floatpat = regex.compile(r"[-+]?((\d*\.\d+)|(\d+\.?))")
  191. def _literal_float(f):
  192. """Return True if n starts like a floating point number."""
  193. return bool(_floatpat.match(f))
  194. # (a,b) -> gcd(a,b)
  195. # TODO caching with decorator, but not to degrade performance
  196. @lru_cache(1024)
  197. def igcd(*args):
  198. """Computes nonnegative integer greatest common divisor.
  199. Explanation
  200. ===========
  201. The algorithm is based on the well known Euclid's algorithm [1]_. To
  202. improve speed, ``igcd()`` has its own caching mechanism.
  203. Examples
  204. ========
  205. >>> from sympy import igcd
  206. >>> igcd(2, 4)
  207. 2
  208. >>> igcd(5, 10, 15)
  209. 5
  210. References
  211. ==========
  212. .. [1] https://en.wikipedia.org/wiki/Euclidean_algorithm
  213. """
  214. if len(args) < 2:
  215. raise TypeError(
  216. 'igcd() takes at least 2 arguments (%s given)' % len(args))
  217. args_temp = [abs(as_int(i)) for i in args]
  218. if 1 in args_temp:
  219. return 1
  220. a = args_temp.pop()
  221. if HAS_GMPY: # Using gmpy if present to speed up.
  222. for b in args_temp:
  223. a = gmpy.gcd(a, b) if b else a
  224. return as_int(a)
  225. for b in args_temp:
  226. a = math.gcd(a, b)
  227. return a
  228. igcd2 = math.gcd
  229. def igcd_lehmer(a, b):
  230. r"""Computes greatest common divisor of two integers.
  231. Explanation
  232. ===========
  233. Euclid's algorithm for the computation of the greatest
  234. common divisor ``gcd(a, b)`` of two (positive) integers
  235. $a$ and $b$ is based on the division identity
  236. $$ a = q \times b + r$$,
  237. where the quotient $q$ and the remainder $r$ are integers
  238. and $0 \le r < b$. Then each common divisor of $a$ and $b$
  239. divides $r$, and it follows that ``gcd(a, b) == gcd(b, r)``.
  240. The algorithm works by constructing the sequence
  241. r0, r1, r2, ..., where r0 = a, r1 = b, and each rn
  242. is the remainder from the division of the two preceding
  243. elements.
  244. In Python, ``q = a // b`` and ``r = a % b`` are obtained by the
  245. floor division and the remainder operations, respectively.
  246. These are the most expensive arithmetic operations, especially
  247. for large a and b.
  248. Lehmer's algorithm [1]_ is based on the observation that the quotients
  249. ``qn = r(n-1) // rn`` are in general small integers even
  250. when a and b are very large. Hence the quotients can be
  251. usually determined from a relatively small number of most
  252. significant bits.
  253. The efficiency of the algorithm is further enhanced by not
  254. computing each long remainder in Euclid's sequence. The remainders
  255. are linear combinations of a and b with integer coefficients
  256. derived from the quotients. The coefficients can be computed
  257. as far as the quotients can be determined from the chosen
  258. most significant parts of a and b. Only then a new pair of
  259. consecutive remainders is computed and the algorithm starts
  260. anew with this pair.
  261. References
  262. ==========
  263. .. [1] https://en.wikipedia.org/wiki/Lehmer%27s_GCD_algorithm
  264. """
  265. a, b = abs(as_int(a)), abs(as_int(b))
  266. if a < b:
  267. a, b = b, a
  268. # The algorithm works by using one or two digit division
  269. # whenever possible. The outer loop will replace the
  270. # pair (a, b) with a pair of shorter consecutive elements
  271. # of the Euclidean gcd sequence until a and b
  272. # fit into two Python (long) int digits.
  273. nbits = 2*sys.int_info.bits_per_digit
  274. while a.bit_length() > nbits and b != 0:
  275. # Quotients are mostly small integers that can
  276. # be determined from most significant bits.
  277. n = a.bit_length() - nbits
  278. x, y = int(a >> n), int(b >> n) # most significant bits
  279. # Elements of the Euclidean gcd sequence are linear
  280. # combinations of a and b with integer coefficients.
  281. # Compute the coefficients of consecutive pairs
  282. # a' = A*a + B*b, b' = C*a + D*b
  283. # using small integer arithmetic as far as possible.
  284. A, B, C, D = 1, 0, 0, 1 # initial values
  285. while True:
  286. # The coefficients alternate in sign while looping.
  287. # The inner loop combines two steps to keep track
  288. # of the signs.
  289. # At this point we have
  290. # A > 0, B <= 0, C <= 0, D > 0,
  291. # x' = x + B <= x < x" = x + A,
  292. # y' = y + C <= y < y" = y + D,
  293. # and
  294. # x'*N <= a' < x"*N, y'*N <= b' < y"*N,
  295. # where N = 2**n.
  296. # Now, if y' > 0, and x"//y' and x'//y" agree,
  297. # then their common value is equal to q = a'//b'.
  298. # In addition,
  299. # x'%y" = x' - q*y" < x" - q*y' = x"%y',
  300. # and
  301. # (x'%y")*N < a'%b' < (x"%y')*N.
  302. # On the other hand, we also have x//y == q,
  303. # and therefore
  304. # x'%y" = x + B - q*(y + D) = x%y + B',
  305. # x"%y' = x + A - q*(y + C) = x%y + A',
  306. # where
  307. # B' = B - q*D < 0, A' = A - q*C > 0.
  308. if y + C <= 0:
  309. break
  310. q = (x + A) // (y + C)
  311. # Now x'//y" <= q, and equality holds if
  312. # x' - q*y" = (x - q*y) + (B - q*D) >= 0.
  313. # This is a minor optimization to avoid division.
  314. x_qy, B_qD = x - q*y, B - q*D
  315. if x_qy + B_qD < 0:
  316. break
  317. # Next step in the Euclidean sequence.
  318. x, y = y, x_qy
  319. A, B, C, D = C, D, A - q*C, B_qD
  320. # At this point the signs of the coefficients
  321. # change and their roles are interchanged.
  322. # A <= 0, B > 0, C > 0, D < 0,
  323. # x' = x + A <= x < x" = x + B,
  324. # y' = y + D < y < y" = y + C.
  325. if y + D <= 0:
  326. break
  327. q = (x + B) // (y + D)
  328. x_qy, A_qC = x - q*y, A - q*C
  329. if x_qy + A_qC < 0:
  330. break
  331. x, y = y, x_qy
  332. A, B, C, D = C, D, A_qC, B - q*D
  333. # Now the conditions on top of the loop
  334. # are again satisfied.
  335. # A > 0, B < 0, C < 0, D > 0.
  336. if B == 0:
  337. # This can only happen when y == 0 in the beginning
  338. # and the inner loop does nothing.
  339. # Long division is forced.
  340. a, b = b, a % b
  341. continue
  342. # Compute new long arguments using the coefficients.
  343. a, b = A*a + B*b, C*a + D*b
  344. # Small divisors. Finish with the standard algorithm.
  345. while b:
  346. a, b = b, a % b
  347. return a
  348. def ilcm(*args):
  349. """Computes integer least common multiple.
  350. Examples
  351. ========
  352. >>> from sympy import ilcm
  353. >>> ilcm(5, 10)
  354. 10
  355. >>> ilcm(7, 3)
  356. 21
  357. >>> ilcm(5, 10, 15)
  358. 30
  359. """
  360. if len(args) < 2:
  361. raise TypeError(
  362. 'ilcm() takes at least 2 arguments (%s given)' % len(args))
  363. if 0 in args:
  364. return 0
  365. a = args[0]
  366. for b in args[1:]:
  367. a = a // igcd(a, b) * b # since gcd(a,b) | a
  368. return a
  369. def igcdex(a, b):
  370. """Returns x, y, g such that g = x*a + y*b = gcd(a, b).
  371. Examples
  372. ========
  373. >>> from sympy.core.numbers import igcdex
  374. >>> igcdex(2, 3)
  375. (-1, 1, 1)
  376. >>> igcdex(10, 12)
  377. (-1, 1, 2)
  378. >>> x, y, g = igcdex(100, 2004)
  379. >>> x, y, g
  380. (-20, 1, 4)
  381. >>> x*100 + y*2004
  382. 4
  383. """
  384. if (not a) and (not b):
  385. return (0, 1, 0)
  386. if not a:
  387. return (0, b//abs(b), abs(b))
  388. if not b:
  389. return (a//abs(a), 0, abs(a))
  390. if a < 0:
  391. a, x_sign = -a, -1
  392. else:
  393. x_sign = 1
  394. if b < 0:
  395. b, y_sign = -b, -1
  396. else:
  397. y_sign = 1
  398. x, y, r, s = 1, 0, 0, 1
  399. while b:
  400. (c, q) = (a % b, a // b)
  401. (a, b, r, s, x, y) = (b, c, x - q*r, y - q*s, r, s)
  402. return (x*x_sign, y*y_sign, a)
  403. def mod_inverse(a, m):
  404. r"""
  405. Return the number $c$ such that, $a \times c = 1 \pmod{m}$
  406. where $c$ has the same sign as $m$. If no such value exists,
  407. a ValueError is raised.
  408. Examples
  409. ========
  410. >>> from sympy import mod_inverse, S
  411. Suppose we wish to find multiplicative inverse $x$ of
  412. 3 modulo 11. This is the same as finding $x$ such
  413. that $3x = 1 \pmod{11}$. One value of x that satisfies
  414. this congruence is 4. Because $3 \times 4 = 12$ and $12 = 1 \pmod{11}$.
  415. This is the value returned by ``mod_inverse``:
  416. >>> mod_inverse(3, 11)
  417. 4
  418. >>> mod_inverse(-3, 11)
  419. 7
  420. When there is a common factor between the numerators of
  421. `a` and `m` the inverse does not exist:
  422. >>> mod_inverse(2, 4)
  423. Traceback (most recent call last):
  424. ...
  425. ValueError: inverse of 2 mod 4 does not exist
  426. >>> mod_inverse(S(2)/7, S(5)/2)
  427. 7/2
  428. References
  429. ==========
  430. .. [1] https://en.wikipedia.org/wiki/Modular_multiplicative_inverse
  431. .. [2] https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
  432. """
  433. c = None
  434. try:
  435. a, m = as_int(a), as_int(m)
  436. if m != 1 and m != -1:
  437. x, _, g = igcdex(a, m)
  438. if g == 1:
  439. c = x % m
  440. except ValueError:
  441. a, m = sympify(a), sympify(m)
  442. if not (a.is_number and m.is_number):
  443. raise TypeError(filldedent('''
  444. Expected numbers for arguments; symbolic `mod_inverse`
  445. is not implemented
  446. but symbolic expressions can be handled with the
  447. similar function,
  448. sympy.polys.polytools.invert'''))
  449. big = (m > 1)
  450. if big not in (S.true, S.false):
  451. raise ValueError('m > 1 did not evaluate; try to simplify %s' % m)
  452. elif big:
  453. c = 1/a
  454. if c is None:
  455. raise ValueError('inverse of %s (mod %s) does not exist' % (a, m))
  456. return c
  457. class Number(AtomicExpr):
  458. """Represents atomic numbers in SymPy.
  459. Explanation
  460. ===========
  461. Floating point numbers are represented by the Float class.
  462. Rational numbers (of any size) are represented by the Rational class.
  463. Integer numbers (of any size) are represented by the Integer class.
  464. Float and Rational are subclasses of Number; Integer is a subclass
  465. of Rational.
  466. For example, ``2/3`` is represented as ``Rational(2, 3)`` which is
  467. a different object from the floating point number obtained with
  468. Python division ``2/3``. Even for numbers that are exactly
  469. represented in binary, there is a difference between how two forms,
  470. such as ``Rational(1, 2)`` and ``Float(0.5)``, are used in SymPy.
  471. The rational form is to be preferred in symbolic computations.
  472. Other kinds of numbers, such as algebraic numbers ``sqrt(2)`` or
  473. complex numbers ``3 + 4*I``, are not instances of Number class as
  474. they are not atomic.
  475. See Also
  476. ========
  477. Float, Integer, Rational
  478. """
  479. is_commutative = True
  480. is_number = True
  481. is_Number = True
  482. __slots__ = ()
  483. # Used to make max(x._prec, y._prec) return x._prec when only x is a float
  484. _prec = -1
  485. kind = NumberKind
  486. def __new__(cls, *obj):
  487. if len(obj) == 1:
  488. obj = obj[0]
  489. if isinstance(obj, Number):
  490. return obj
  491. if isinstance(obj, SYMPY_INTS):
  492. return Integer(obj)
  493. if isinstance(obj, tuple) and len(obj) == 2:
  494. return Rational(*obj)
  495. if isinstance(obj, (float, mpmath.mpf, decimal.Decimal)):
  496. return Float(obj)
  497. if isinstance(obj, str):
  498. _obj = obj.lower() # float('INF') == float('inf')
  499. if _obj == 'nan':
  500. return S.NaN
  501. elif _obj == 'inf':
  502. return S.Infinity
  503. elif _obj == '+inf':
  504. return S.Infinity
  505. elif _obj == '-inf':
  506. return S.NegativeInfinity
  507. val = sympify(obj)
  508. if isinstance(val, Number):
  509. return val
  510. else:
  511. raise ValueError('String "%s" does not denote a Number' % obj)
  512. msg = "expected str|int|long|float|Decimal|Number object but got %r"
  513. raise TypeError(msg % type(obj).__name__)
  514. def could_extract_minus_sign(self):
  515. return bool(self.is_extended_negative)
  516. def invert(self, other, *gens, **args):
  517. from sympy.polys.polytools import invert
  518. if getattr(other, 'is_number', True):
  519. return mod_inverse(self, other)
  520. return invert(self, other, *gens, **args)
  521. def __divmod__(self, other):
  522. from sympy.functions.elementary.complexes import sign
  523. try:
  524. other = Number(other)
  525. if self.is_infinite or S.NaN in (self, other):
  526. return (S.NaN, S.NaN)
  527. except TypeError:
  528. return NotImplemented
  529. if not other:
  530. raise ZeroDivisionError('modulo by zero')
  531. if self.is_Integer and other.is_Integer:
  532. return Tuple(*divmod(self.p, other.p))
  533. elif isinstance(other, Float):
  534. rat = self/Rational(other)
  535. else:
  536. rat = self/other
  537. if other.is_finite:
  538. w = int(rat) if rat >= 0 else int(rat) - 1
  539. r = self - other*w
  540. else:
  541. w = 0 if not self or (sign(self) == sign(other)) else -1
  542. r = other if w else self
  543. return Tuple(w, r)
  544. def __rdivmod__(self, other):
  545. try:
  546. other = Number(other)
  547. except TypeError:
  548. return NotImplemented
  549. return divmod(other, self)
  550. def _as_mpf_val(self, prec):
  551. """Evaluation of mpf tuple accurate to at least prec bits."""
  552. raise NotImplementedError('%s needs ._as_mpf_val() method' %
  553. (self.__class__.__name__))
  554. def _eval_evalf(self, prec):
  555. return Float._new(self._as_mpf_val(prec), prec)
  556. def _as_mpf_op(self, prec):
  557. prec = max(prec, self._prec)
  558. return self._as_mpf_val(prec), prec
  559. def __float__(self):
  560. return mlib.to_float(self._as_mpf_val(53))
  561. def floor(self):
  562. raise NotImplementedError('%s needs .floor() method' %
  563. (self.__class__.__name__))
  564. def ceiling(self):
  565. raise NotImplementedError('%s needs .ceiling() method' %
  566. (self.__class__.__name__))
  567. def __floor__(self):
  568. return self.floor()
  569. def __ceil__(self):
  570. return self.ceiling()
  571. def _eval_conjugate(self):
  572. return self
  573. def _eval_order(self, *symbols):
  574. from sympy.series.order import Order
  575. # Order(5, x, y) -> Order(1,x,y)
  576. return Order(S.One, *symbols)
  577. def _eval_subs(self, old, new):
  578. if old == -self:
  579. return -new
  580. return self # there is no other possibility
  581. @classmethod
  582. def class_key(cls):
  583. return 1, 0, 'Number'
  584. @cacheit
  585. def sort_key(self, order=None):
  586. return self.class_key(), (0, ()), (), self
  587. @_sympifyit('other', NotImplemented)
  588. def __add__(self, other):
  589. if isinstance(other, Number) and global_parameters.evaluate:
  590. if other is S.NaN:
  591. return S.NaN
  592. elif other is S.Infinity:
  593. return S.Infinity
  594. elif other is S.NegativeInfinity:
  595. return S.NegativeInfinity
  596. return AtomicExpr.__add__(self, other)
  597. @_sympifyit('other', NotImplemented)
  598. def __sub__(self, other):
  599. if isinstance(other, Number) and global_parameters.evaluate:
  600. if other is S.NaN:
  601. return S.NaN
  602. elif other is S.Infinity:
  603. return S.NegativeInfinity
  604. elif other is S.NegativeInfinity:
  605. return S.Infinity
  606. return AtomicExpr.__sub__(self, other)
  607. @_sympifyit('other', NotImplemented)
  608. def __mul__(self, other):
  609. if isinstance(other, Number) and global_parameters.evaluate:
  610. if other is S.NaN:
  611. return S.NaN
  612. elif other is S.Infinity:
  613. if self.is_zero:
  614. return S.NaN
  615. elif self.is_positive:
  616. return S.Infinity
  617. else:
  618. return S.NegativeInfinity
  619. elif other is S.NegativeInfinity:
  620. if self.is_zero:
  621. return S.NaN
  622. elif self.is_positive:
  623. return S.NegativeInfinity
  624. else:
  625. return S.Infinity
  626. elif isinstance(other, Tuple):
  627. return NotImplemented
  628. return AtomicExpr.__mul__(self, other)
  629. @_sympifyit('other', NotImplemented)
  630. def __truediv__(self, other):
  631. if isinstance(other, Number) and global_parameters.evaluate:
  632. if other is S.NaN:
  633. return S.NaN
  634. elif other in (S.Infinity, S.NegativeInfinity):
  635. return S.Zero
  636. return AtomicExpr.__truediv__(self, other)
  637. def __eq__(self, other):
  638. raise NotImplementedError('%s needs .__eq__() method' %
  639. (self.__class__.__name__))
  640. def __ne__(self, other):
  641. raise NotImplementedError('%s needs .__ne__() method' %
  642. (self.__class__.__name__))
  643. def __lt__(self, other):
  644. try:
  645. other = _sympify(other)
  646. except SympifyError:
  647. raise TypeError("Invalid comparison %s < %s" % (self, other))
  648. raise NotImplementedError('%s needs .__lt__() method' %
  649. (self.__class__.__name__))
  650. def __le__(self, other):
  651. try:
  652. other = _sympify(other)
  653. except SympifyError:
  654. raise TypeError("Invalid comparison %s <= %s" % (self, other))
  655. raise NotImplementedError('%s needs .__le__() method' %
  656. (self.__class__.__name__))
  657. def __gt__(self, other):
  658. try:
  659. other = _sympify(other)
  660. except SympifyError:
  661. raise TypeError("Invalid comparison %s > %s" % (self, other))
  662. return _sympify(other).__lt__(self)
  663. def __ge__(self, other):
  664. try:
  665. other = _sympify(other)
  666. except SympifyError:
  667. raise TypeError("Invalid comparison %s >= %s" % (self, other))
  668. return _sympify(other).__le__(self)
  669. def __hash__(self):
  670. return super().__hash__()
  671. def is_constant(self, *wrt, **flags):
  672. return True
  673. def as_coeff_mul(self, *deps, rational=True, **kwargs):
  674. # a -> c*t
  675. if self.is_Rational or not rational:
  676. return self, ()
  677. elif self.is_negative:
  678. return S.NegativeOne, (-self,)
  679. return S.One, (self,)
  680. def as_coeff_add(self, *deps):
  681. # a -> c + t
  682. if self.is_Rational:
  683. return self, ()
  684. return S.Zero, (self,)
  685. def as_coeff_Mul(self, rational=False):
  686. """Efficiently extract the coefficient of a product."""
  687. if rational and not self.is_Rational:
  688. return S.One, self
  689. return (self, S.One) if self else (S.One, self)
  690. def as_coeff_Add(self, rational=False):
  691. """Efficiently extract the coefficient of a summation."""
  692. if not rational:
  693. return self, S.Zero
  694. return S.Zero, self
  695. def gcd(self, other):
  696. """Compute GCD of `self` and `other`. """
  697. from sympy.polys.polytools import gcd
  698. return gcd(self, other)
  699. def lcm(self, other):
  700. """Compute LCM of `self` and `other`. """
  701. from sympy.polys.polytools import lcm
  702. return lcm(self, other)
  703. def cofactors(self, other):
  704. """Compute GCD and cofactors of `self` and `other`. """
  705. from sympy.polys.polytools import cofactors
  706. return cofactors(self, other)
  707. class Float(Number):
  708. """Represent a floating-point number of arbitrary precision.
  709. Examples
  710. ========
  711. >>> from sympy import Float
  712. >>> Float(3.5)
  713. 3.50000000000000
  714. >>> Float(3)
  715. 3.00000000000000
  716. Creating Floats from strings (and Python ``int`` and ``long``
  717. types) will give a minimum precision of 15 digits, but the
  718. precision will automatically increase to capture all digits
  719. entered.
  720. >>> Float(1)
  721. 1.00000000000000
  722. >>> Float(10**20)
  723. 100000000000000000000.
  724. >>> Float('1e20')
  725. 100000000000000000000.
  726. However, *floating-point* numbers (Python ``float`` types) retain
  727. only 15 digits of precision:
  728. >>> Float(1e20)
  729. 1.00000000000000e+20
  730. >>> Float(1.23456789123456789)
  731. 1.23456789123457
  732. It may be preferable to enter high-precision decimal numbers
  733. as strings:
  734. >>> Float('1.23456789123456789')
  735. 1.23456789123456789
  736. The desired number of digits can also be specified:
  737. >>> Float('1e-3', 3)
  738. 0.00100
  739. >>> Float(100, 4)
  740. 100.0
  741. Float can automatically count significant figures if a null string
  742. is sent for the precision; spaces or underscores are also allowed. (Auto-
  743. counting is only allowed for strings, ints and longs).
  744. >>> Float('123 456 789.123_456', '')
  745. 123456789.123456
  746. >>> Float('12e-3', '')
  747. 0.012
  748. >>> Float(3, '')
  749. 3.
  750. If a number is written in scientific notation, only the digits before the
  751. exponent are considered significant if a decimal appears, otherwise the
  752. "e" signifies only how to move the decimal:
  753. >>> Float('60.e2', '') # 2 digits significant
  754. 6.0e+3
  755. >>> Float('60e2', '') # 4 digits significant
  756. 6000.
  757. >>> Float('600e-2', '') # 3 digits significant
  758. 6.00
  759. Notes
  760. =====
  761. Floats are inexact by their nature unless their value is a binary-exact
  762. value.
  763. >>> approx, exact = Float(.1, 1), Float(.125, 1)
  764. For calculation purposes, evalf needs to be able to change the precision
  765. but this will not increase the accuracy of the inexact value. The
  766. following is the most accurate 5-digit approximation of a value of 0.1
  767. that had only 1 digit of precision:
  768. >>> approx.evalf(5)
  769. 0.099609
  770. By contrast, 0.125 is exact in binary (as it is in base 10) and so it
  771. can be passed to Float or evalf to obtain an arbitrary precision with
  772. matching accuracy:
  773. >>> Float(exact, 5)
  774. 0.12500
  775. >>> exact.evalf(20)
  776. 0.12500000000000000000
  777. Trying to make a high-precision Float from a float is not disallowed,
  778. but one must keep in mind that the *underlying float* (not the apparent
  779. decimal value) is being obtained with high precision. For example, 0.3
  780. does not have a finite binary representation. The closest rational is
  781. the fraction 5404319552844595/2**54. So if you try to obtain a Float of
  782. 0.3 to 20 digits of precision you will not see the same thing as 0.3
  783. followed by 19 zeros:
  784. >>> Float(0.3, 20)
  785. 0.29999999999999998890
  786. If you want a 20-digit value of the decimal 0.3 (not the floating point
  787. approximation of 0.3) you should send the 0.3 as a string. The underlying
  788. representation is still binary but a higher precision than Python's float
  789. is used:
  790. >>> Float('0.3', 20)
  791. 0.30000000000000000000
  792. Although you can increase the precision of an existing Float using Float
  793. it will not increase the accuracy -- the underlying value is not changed:
  794. >>> def show(f): # binary rep of Float
  795. ... from sympy import Mul, Pow
  796. ... s, m, e, b = f._mpf_
  797. ... v = Mul(int(m), Pow(2, int(e), evaluate=False), evaluate=False)
  798. ... print('%s at prec=%s' % (v, f._prec))
  799. ...
  800. >>> t = Float('0.3', 3)
  801. >>> show(t)
  802. 4915/2**14 at prec=13
  803. >>> show(Float(t, 20)) # higher prec, not higher accuracy
  804. 4915/2**14 at prec=70
  805. >>> show(Float(t, 2)) # lower prec
  806. 307/2**10 at prec=10
  807. The same thing happens when evalf is used on a Float:
  808. >>> show(t.evalf(20))
  809. 4915/2**14 at prec=70
  810. >>> show(t.evalf(2))
  811. 307/2**10 at prec=10
  812. Finally, Floats can be instantiated with an mpf tuple (n, c, p) to
  813. produce the number (-1)**n*c*2**p:
  814. >>> n, c, p = 1, 5, 0
  815. >>> (-1)**n*c*2**p
  816. -5
  817. >>> Float((1, 5, 0))
  818. -5.00000000000000
  819. An actual mpf tuple also contains the number of bits in c as the last
  820. element of the tuple:
  821. >>> _._mpf_
  822. (1, 5, 0, 3)
  823. This is not needed for instantiation and is not the same thing as the
  824. precision. The mpf tuple and the precision are two separate quantities
  825. that Float tracks.
  826. In SymPy, a Float is a number that can be computed with arbitrary
  827. precision. Although floating point 'inf' and 'nan' are not such
  828. numbers, Float can create these numbers:
  829. >>> Float('-inf')
  830. -oo
  831. >>> _.is_Float
  832. False
  833. Zero in Float only has a single value. Values are not separate for
  834. positive and negative zeroes.
  835. """
  836. __slots__ = ('_mpf_', '_prec')
  837. _mpf_: tuple[int, int, int, int]
  838. # A Float represents many real numbers,
  839. # both rational and irrational.
  840. is_rational = None
  841. is_irrational = None
  842. is_number = True
  843. is_real = True
  844. is_extended_real = True
  845. is_Float = True
  846. def __new__(cls, num, dps=None, precision=None):
  847. if dps is not None and precision is not None:
  848. raise ValueError('Both decimal and binary precision supplied. '
  849. 'Supply only one. ')
  850. if isinstance(num, str):
  851. # Float accepts spaces as digit separators
  852. num = num.replace(' ', '').lower()
  853. if num.startswith('.') and len(num) > 1:
  854. num = '0' + num
  855. elif num.startswith('-.') and len(num) > 2:
  856. num = '-0.' + num[2:]
  857. elif num in ('inf', '+inf'):
  858. return S.Infinity
  859. elif num == '-inf':
  860. return S.NegativeInfinity
  861. elif isinstance(num, float) and num == 0:
  862. num = '0'
  863. elif isinstance(num, float) and num == float('inf'):
  864. return S.Infinity
  865. elif isinstance(num, float) and num == float('-inf'):
  866. return S.NegativeInfinity
  867. elif isinstance(num, float) and math.isnan(num):
  868. return S.NaN
  869. elif isinstance(num, (SYMPY_INTS, Integer)):
  870. num = str(num)
  871. elif num is S.Infinity:
  872. return num
  873. elif num is S.NegativeInfinity:
  874. return num
  875. elif num is S.NaN:
  876. return num
  877. elif _is_numpy_instance(num): # support for numpy datatypes
  878. num = _convert_numpy_types(num)
  879. elif isinstance(num, mpmath.mpf):
  880. if precision is None:
  881. if dps is None:
  882. precision = num.context.prec
  883. num = num._mpf_
  884. if dps is None and precision is None:
  885. dps = 15
  886. if isinstance(num, Float):
  887. return num
  888. if isinstance(num, str) and _literal_float(num):
  889. try:
  890. Num = decimal.Decimal(num)
  891. except decimal.InvalidOperation:
  892. pass
  893. else:
  894. isint = '.' not in num
  895. num, dps = _decimal_to_Rational_prec(Num)
  896. if num.is_Integer and isint:
  897. dps = max(dps, len(str(num).lstrip('-')))
  898. dps = max(15, dps)
  899. precision = dps_to_prec(dps)
  900. elif precision == '' and dps is None or precision is None and dps == '':
  901. if not isinstance(num, str):
  902. raise ValueError('The null string can only be used when '
  903. 'the number to Float is passed as a string or an integer.')
  904. ok = None
  905. if _literal_float(num):
  906. try:
  907. Num = decimal.Decimal(num)
  908. except decimal.InvalidOperation:
  909. pass
  910. else:
  911. isint = '.' not in num
  912. num, dps = _decimal_to_Rational_prec(Num)
  913. if num.is_Integer and isint:
  914. dps = max(dps, len(str(num).lstrip('-')))
  915. precision = dps_to_prec(dps)
  916. ok = True
  917. if ok is None:
  918. raise ValueError('string-float not recognized: %s' % num)
  919. # decimal precision(dps) is set and maybe binary precision(precision)
  920. # as well.From here on binary precision is used to compute the Float.
  921. # Hence, if supplied use binary precision else translate from decimal
  922. # precision.
  923. if precision is None or precision == '':
  924. precision = dps_to_prec(dps)
  925. precision = int(precision)
  926. if isinstance(num, float):
  927. _mpf_ = mlib.from_float(num, precision, rnd)
  928. elif isinstance(num, str):
  929. _mpf_ = mlib.from_str(num, precision, rnd)
  930. elif isinstance(num, decimal.Decimal):
  931. if num.is_finite():
  932. _mpf_ = mlib.from_str(str(num), precision, rnd)
  933. elif num.is_nan():
  934. return S.NaN
  935. elif num.is_infinite():
  936. if num > 0:
  937. return S.Infinity
  938. return S.NegativeInfinity
  939. else:
  940. raise ValueError("unexpected decimal value %s" % str(num))
  941. elif isinstance(num, tuple) and len(num) in (3, 4):
  942. if isinstance(num[1], str):
  943. # it's a hexadecimal (coming from a pickled object)
  944. num = list(num)
  945. # If we're loading an object pickled in Python 2 into
  946. # Python 3, we may need to strip a tailing 'L' because
  947. # of a shim for int on Python 3, see issue #13470.
  948. if num[1].endswith('L'):
  949. num[1] = num[1][:-1]
  950. # Strip leading '0x' - gmpy2 only documents such inputs
  951. # with base prefix as valid when the 2nd argument (base) is 0.
  952. # When mpmath uses Sage as the backend, however, it
  953. # ends up including '0x' when preparing the picklable tuple.
  954. # See issue #19690.
  955. if num[1].startswith('0x'):
  956. num[1] = num[1][2:]
  957. # Now we can assume that it is in standard form
  958. num[1] = MPZ(num[1], 16)
  959. _mpf_ = tuple(num)
  960. else:
  961. if len(num) == 4:
  962. # handle normalization hack
  963. return Float._new(num, precision)
  964. else:
  965. if not all((
  966. num[0] in (0, 1),
  967. num[1] >= 0,
  968. all(type(i) in (int, int) for i in num)
  969. )):
  970. raise ValueError('malformed mpf: %s' % (num,))
  971. # don't compute number or else it may
  972. # over/underflow
  973. return Float._new(
  974. (num[0], num[1], num[2], bitcount(num[1])),
  975. precision)
  976. else:
  977. try:
  978. _mpf_ = num._as_mpf_val(precision)
  979. except (NotImplementedError, AttributeError):
  980. _mpf_ = mpmath.mpf(num, prec=precision)._mpf_
  981. return cls._new(_mpf_, precision, zero=False)
  982. @classmethod
  983. def _new(cls, _mpf_, _prec, zero=True):
  984. # special cases
  985. if zero and _mpf_ == fzero:
  986. return S.Zero # Float(0) -> 0.0; Float._new((0,0,0,0)) -> 0
  987. elif _mpf_ == _mpf_nan:
  988. return S.NaN
  989. elif _mpf_ == _mpf_inf:
  990. return S.Infinity
  991. elif _mpf_ == _mpf_ninf:
  992. return S.NegativeInfinity
  993. obj = Expr.__new__(cls)
  994. obj._mpf_ = mpf_norm(_mpf_, _prec)
  995. obj._prec = _prec
  996. return obj
  997. # mpz can't be pickled
  998. def __getnewargs_ex__(self):
  999. return ((mlib.to_pickable(self._mpf_),), {'precision': self._prec})
  1000. def _hashable_content(self):
  1001. return (self._mpf_, self._prec)
  1002. def floor(self):
  1003. return Integer(int(mlib.to_int(
  1004. mlib.mpf_floor(self._mpf_, self._prec))))
  1005. def ceiling(self):
  1006. return Integer(int(mlib.to_int(
  1007. mlib.mpf_ceil(self._mpf_, self._prec))))
  1008. def __floor__(self):
  1009. return self.floor()
  1010. def __ceil__(self):
  1011. return self.ceiling()
  1012. @property
  1013. def num(self):
  1014. return mpmath.mpf(self._mpf_)
  1015. def _as_mpf_val(self, prec):
  1016. rv = mpf_norm(self._mpf_, prec)
  1017. if rv != self._mpf_ and self._prec == prec:
  1018. debug(self._mpf_, rv)
  1019. return rv
  1020. def _as_mpf_op(self, prec):
  1021. return self._mpf_, max(prec, self._prec)
  1022. def _eval_is_finite(self):
  1023. if self._mpf_ in (_mpf_inf, _mpf_ninf):
  1024. return False
  1025. return True
  1026. def _eval_is_infinite(self):
  1027. if self._mpf_ in (_mpf_inf, _mpf_ninf):
  1028. return True
  1029. return False
  1030. def _eval_is_integer(self):
  1031. return self._mpf_ == fzero
  1032. def _eval_is_negative(self):
  1033. if self._mpf_ in (_mpf_ninf, _mpf_inf):
  1034. return False
  1035. return self.num < 0
  1036. def _eval_is_positive(self):
  1037. if self._mpf_ in (_mpf_ninf, _mpf_inf):
  1038. return False
  1039. return self.num > 0
  1040. def _eval_is_extended_negative(self):
  1041. if self._mpf_ == _mpf_ninf:
  1042. return True
  1043. if self._mpf_ == _mpf_inf:
  1044. return False
  1045. return self.num < 0
  1046. def _eval_is_extended_positive(self):
  1047. if self._mpf_ == _mpf_inf:
  1048. return True
  1049. if self._mpf_ == _mpf_ninf:
  1050. return False
  1051. return self.num > 0
  1052. def _eval_is_zero(self):
  1053. return self._mpf_ == fzero
  1054. def __bool__(self):
  1055. return self._mpf_ != fzero
  1056. def __neg__(self):
  1057. if not self:
  1058. return self
  1059. return Float._new(mlib.mpf_neg(self._mpf_), self._prec)
  1060. @_sympifyit('other', NotImplemented)
  1061. def __add__(self, other):
  1062. if isinstance(other, Number) and global_parameters.evaluate:
  1063. rhs, prec = other._as_mpf_op(self._prec)
  1064. return Float._new(mlib.mpf_add(self._mpf_, rhs, prec, rnd), prec)
  1065. return Number.__add__(self, other)
  1066. @_sympifyit('other', NotImplemented)
  1067. def __sub__(self, other):
  1068. if isinstance(other, Number) and global_parameters.evaluate:
  1069. rhs, prec = other._as_mpf_op(self._prec)
  1070. return Float._new(mlib.mpf_sub(self._mpf_, rhs, prec, rnd), prec)
  1071. return Number.__sub__(self, other)
  1072. @_sympifyit('other', NotImplemented)
  1073. def __mul__(self, other):
  1074. if isinstance(other, Number) and global_parameters.evaluate:
  1075. rhs, prec = other._as_mpf_op(self._prec)
  1076. return Float._new(mlib.mpf_mul(self._mpf_, rhs, prec, rnd), prec)
  1077. return Number.__mul__(self, other)
  1078. @_sympifyit('other', NotImplemented)
  1079. def __truediv__(self, other):
  1080. if isinstance(other, Number) and other != 0 and global_parameters.evaluate:
  1081. rhs, prec = other._as_mpf_op(self._prec)
  1082. return Float._new(mlib.mpf_div(self._mpf_, rhs, prec, rnd), prec)
  1083. return Number.__truediv__(self, other)
  1084. @_sympifyit('other', NotImplemented)
  1085. def __mod__(self, other):
  1086. if isinstance(other, Rational) and other.q != 1 and global_parameters.evaluate:
  1087. # calculate mod with Rationals, *then* round the result
  1088. return Float(Rational.__mod__(Rational(self), other),
  1089. precision=self._prec)
  1090. if isinstance(other, Float) and global_parameters.evaluate:
  1091. r = self/other
  1092. if r == int(r):
  1093. return Float(0, precision=max(self._prec, other._prec))
  1094. if isinstance(other, Number) and global_parameters.evaluate:
  1095. rhs, prec = other._as_mpf_op(self._prec)
  1096. return Float._new(mlib.mpf_mod(self._mpf_, rhs, prec, rnd), prec)
  1097. return Number.__mod__(self, other)
  1098. @_sympifyit('other', NotImplemented)
  1099. def __rmod__(self, other):
  1100. if isinstance(other, Float) and global_parameters.evaluate:
  1101. return other.__mod__(self)
  1102. if isinstance(other, Number) and global_parameters.evaluate:
  1103. rhs, prec = other._as_mpf_op(self._prec)
  1104. return Float._new(mlib.mpf_mod(rhs, self._mpf_, prec, rnd), prec)
  1105. return Number.__rmod__(self, other)
  1106. def _eval_power(self, expt):
  1107. """
  1108. expt is symbolic object but not equal to 0, 1
  1109. (-p)**r -> exp(r*log(-p)) -> exp(r*(log(p) + I*Pi)) ->
  1110. -> p**r*(sin(Pi*r) + cos(Pi*r)*I)
  1111. """
  1112. if equal_valued(self, 0):
  1113. if expt.is_extended_positive:
  1114. return self
  1115. if expt.is_extended_negative:
  1116. return S.ComplexInfinity
  1117. if isinstance(expt, Number):
  1118. if isinstance(expt, Integer):
  1119. prec = self._prec
  1120. return Float._new(
  1121. mlib.mpf_pow_int(self._mpf_, expt.p, prec, rnd), prec)
  1122. elif isinstance(expt, Rational) and \
  1123. expt.p == 1 and expt.q % 2 and self.is_negative:
  1124. return Pow(S.NegativeOne, expt, evaluate=False)*(
  1125. -self)._eval_power(expt)
  1126. expt, prec = expt._as_mpf_op(self._prec)
  1127. mpfself = self._mpf_
  1128. try:
  1129. y = mpf_pow(mpfself, expt, prec, rnd)
  1130. return Float._new(y, prec)
  1131. except mlib.ComplexResult:
  1132. re, im = mlib.mpc_pow(
  1133. (mpfself, fzero), (expt, fzero), prec, rnd)
  1134. return Float._new(re, prec) + \
  1135. Float._new(im, prec)*S.ImaginaryUnit
  1136. def __abs__(self):
  1137. return Float._new(mlib.mpf_abs(self._mpf_), self._prec)
  1138. def __int__(self):
  1139. if self._mpf_ == fzero:
  1140. return 0
  1141. return int(mlib.to_int(self._mpf_)) # uses round_fast = round_down
  1142. def __eq__(self, other):
  1143. from sympy.logic.boolalg import Boolean
  1144. try:
  1145. other = _sympify(other)
  1146. except SympifyError:
  1147. return NotImplemented
  1148. if isinstance(other, Boolean):
  1149. return False
  1150. if other.is_NumberSymbol:
  1151. if other.is_irrational:
  1152. return False
  1153. return other.__eq__(self)
  1154. if other.is_Float:
  1155. # comparison is exact
  1156. # so Float(.1, 3) != Float(.1, 33)
  1157. return self._mpf_ == other._mpf_
  1158. if other.is_Rational:
  1159. return other.__eq__(self)
  1160. if other.is_Number:
  1161. # numbers should compare at the same precision;
  1162. # all _as_mpf_val routines should be sure to abide
  1163. # by the request to change the prec if necessary; if
  1164. # they don't, the equality test will fail since it compares
  1165. # the mpf tuples
  1166. ompf = other._as_mpf_val(self._prec)
  1167. return bool(mlib.mpf_eq(self._mpf_, ompf))
  1168. if not self:
  1169. return not other
  1170. return False # Float != non-Number
  1171. def __ne__(self, other):
  1172. return not self == other
  1173. def _Frel(self, other, op):
  1174. try:
  1175. other = _sympify(other)
  1176. except SympifyError:
  1177. return NotImplemented
  1178. if other.is_Rational:
  1179. # test self*other.q <?> other.p without losing precision
  1180. '''
  1181. >>> f = Float(.1,2)
  1182. >>> i = 1234567890
  1183. >>> (f*i)._mpf_
  1184. (0, 471, 18, 9)
  1185. >>> mlib.mpf_mul(f._mpf_, mlib.from_int(i))
  1186. (0, 505555550955, -12, 39)
  1187. '''
  1188. smpf = mlib.mpf_mul(self._mpf_, mlib.from_int(other.q))
  1189. ompf = mlib.from_int(other.p)
  1190. return _sympify(bool(op(smpf, ompf)))
  1191. elif other.is_Float:
  1192. return _sympify(bool(
  1193. op(self._mpf_, other._mpf_)))
  1194. elif other.is_comparable and other not in (
  1195. S.Infinity, S.NegativeInfinity):
  1196. other = other.evalf(prec_to_dps(self._prec))
  1197. if other._prec > 1:
  1198. if other.is_Number:
  1199. return _sympify(bool(
  1200. op(self._mpf_, other._as_mpf_val(self._prec))))
  1201. def __gt__(self, other):
  1202. if isinstance(other, NumberSymbol):
  1203. return other.__lt__(self)
  1204. rv = self._Frel(other, mlib.mpf_gt)
  1205. if rv is None:
  1206. return Expr.__gt__(self, other)
  1207. return rv
  1208. def __ge__(self, other):
  1209. if isinstance(other, NumberSymbol):
  1210. return other.__le__(self)
  1211. rv = self._Frel(other, mlib.mpf_ge)
  1212. if rv is None:
  1213. return Expr.__ge__(self, other)
  1214. return rv
  1215. def __lt__(self, other):
  1216. if isinstance(other, NumberSymbol):
  1217. return other.__gt__(self)
  1218. rv = self._Frel(other, mlib.mpf_lt)
  1219. if rv is None:
  1220. return Expr.__lt__(self, other)
  1221. return rv
  1222. def __le__(self, other):
  1223. if isinstance(other, NumberSymbol):
  1224. return other.__ge__(self)
  1225. rv = self._Frel(other, mlib.mpf_le)
  1226. if rv is None:
  1227. return Expr.__le__(self, other)
  1228. return rv
  1229. def __hash__(self):
  1230. return super().__hash__()
  1231. def epsilon_eq(self, other, epsilon="1e-15"):
  1232. return abs(self - other) < Float(epsilon)
  1233. def __format__(self, format_spec):
  1234. return format(decimal.Decimal(str(self)), format_spec)
  1235. # Add sympify converters
  1236. _sympy_converter[float] = _sympy_converter[decimal.Decimal] = Float
  1237. # this is here to work nicely in Sage
  1238. RealNumber = Float
  1239. class Rational(Number):
  1240. """Represents rational numbers (p/q) of any size.
  1241. Examples
  1242. ========
  1243. >>> from sympy import Rational, nsimplify, S, pi
  1244. >>> Rational(1, 2)
  1245. 1/2
  1246. Rational is unprejudiced in accepting input. If a float is passed, the
  1247. underlying value of the binary representation will be returned:
  1248. >>> Rational(.5)
  1249. 1/2
  1250. >>> Rational(.2)
  1251. 3602879701896397/18014398509481984
  1252. If the simpler representation of the float is desired then consider
  1253. limiting the denominator to the desired value or convert the float to
  1254. a string (which is roughly equivalent to limiting the denominator to
  1255. 10**12):
  1256. >>> Rational(str(.2))
  1257. 1/5
  1258. >>> Rational(.2).limit_denominator(10**12)
  1259. 1/5
  1260. An arbitrarily precise Rational is obtained when a string literal is
  1261. passed:
  1262. >>> Rational("1.23")
  1263. 123/100
  1264. >>> Rational('1e-2')
  1265. 1/100
  1266. >>> Rational(".1")
  1267. 1/10
  1268. >>> Rational('1e-2/3.2')
  1269. 1/320
  1270. The conversion of other types of strings can be handled by
  1271. the sympify() function, and conversion of floats to expressions
  1272. or simple fractions can be handled with nsimplify:
  1273. >>> S('.[3]') # repeating digits in brackets
  1274. 1/3
  1275. >>> S('3**2/10') # general expressions
  1276. 9/10
  1277. >>> nsimplify(.3) # numbers that have a simple form
  1278. 3/10
  1279. But if the input does not reduce to a literal Rational, an error will
  1280. be raised:
  1281. >>> Rational(pi)
  1282. Traceback (most recent call last):
  1283. ...
  1284. TypeError: invalid input: pi
  1285. Low-level
  1286. ---------
  1287. Access numerator and denominator as .p and .q:
  1288. >>> r = Rational(3, 4)
  1289. >>> r
  1290. 3/4
  1291. >>> r.p
  1292. 3
  1293. >>> r.q
  1294. 4
  1295. Note that p and q return integers (not SymPy Integers) so some care
  1296. is needed when using them in expressions:
  1297. >>> r.p/r.q
  1298. 0.75
  1299. If an unevaluated Rational is desired, ``gcd=1`` can be passed and
  1300. this will keep common divisors of the numerator and denominator
  1301. from being eliminated. It is not possible, however, to leave a
  1302. negative value in the denominator.
  1303. >>> Rational(2, 4, gcd=1)
  1304. 2/4
  1305. >>> Rational(2, -4, gcd=1).q
  1306. 4
  1307. See Also
  1308. ========
  1309. sympy.core.sympify.sympify, sympy.simplify.simplify.nsimplify
  1310. """
  1311. is_real = True
  1312. is_integer = False
  1313. is_rational = True
  1314. is_number = True
  1315. __slots__ = ('p', 'q')
  1316. p: int
  1317. q: int
  1318. is_Rational = True
  1319. @cacheit
  1320. def __new__(cls, p, q=None, gcd=None):
  1321. if q is None:
  1322. if isinstance(p, Rational):
  1323. return p
  1324. if isinstance(p, SYMPY_INTS):
  1325. pass
  1326. else:
  1327. if isinstance(p, (float, Float)):
  1328. return Rational(*_as_integer_ratio(p))
  1329. if not isinstance(p, str):
  1330. try:
  1331. p = sympify(p)
  1332. except (SympifyError, SyntaxError):
  1333. pass # error will raise below
  1334. else:
  1335. if p.count('/') > 1:
  1336. raise TypeError('invalid input: %s' % p)
  1337. p = p.replace(' ', '')
  1338. pq = p.rsplit('/', 1)
  1339. if len(pq) == 2:
  1340. p, q = pq
  1341. fp = fractions.Fraction(p)
  1342. fq = fractions.Fraction(q)
  1343. p = fp/fq
  1344. try:
  1345. p = fractions.Fraction(p)
  1346. except ValueError:
  1347. pass # error will raise below
  1348. else:
  1349. return Rational(p.numerator, p.denominator, 1)
  1350. if not isinstance(p, Rational):
  1351. raise TypeError('invalid input: %s' % p)
  1352. q = 1
  1353. gcd = 1
  1354. Q = 1
  1355. if not isinstance(p, SYMPY_INTS):
  1356. p = Rational(p)
  1357. Q *= p.q
  1358. p = p.p
  1359. else:
  1360. p = int(p)
  1361. if not isinstance(q, SYMPY_INTS):
  1362. q = Rational(q)
  1363. p *= q.q
  1364. Q *= q.p
  1365. else:
  1366. Q *= int(q)
  1367. q = Q
  1368. # p and q are now ints
  1369. if q == 0:
  1370. if p == 0:
  1371. if _errdict["divide"]:
  1372. raise ValueError("Indeterminate 0/0")
  1373. else:
  1374. return S.NaN
  1375. return S.ComplexInfinity
  1376. if q < 0:
  1377. q = -q
  1378. p = -p
  1379. if not gcd:
  1380. gcd = igcd(abs(p), q)
  1381. if gcd > 1:
  1382. p //= gcd
  1383. q //= gcd
  1384. if q == 1:
  1385. return Integer(p)
  1386. if p == 1 and q == 2:
  1387. return S.Half
  1388. obj = Expr.__new__(cls)
  1389. obj.p = p
  1390. obj.q = q
  1391. return obj
  1392. def limit_denominator(self, max_denominator=1000000):
  1393. """Closest Rational to self with denominator at most max_denominator.
  1394. Examples
  1395. ========
  1396. >>> from sympy import Rational
  1397. >>> Rational('3.141592653589793').limit_denominator(10)
  1398. 22/7
  1399. >>> Rational('3.141592653589793').limit_denominator(100)
  1400. 311/99
  1401. """
  1402. f = fractions.Fraction(self.p, self.q)
  1403. return Rational(f.limit_denominator(fractions.Fraction(int(max_denominator))))
  1404. def __getnewargs__(self):
  1405. return (self.p, self.q)
  1406. def _hashable_content(self):
  1407. return (self.p, self.q)
  1408. def _eval_is_positive(self):
  1409. return self.p > 0
  1410. def _eval_is_zero(self):
  1411. return self.p == 0
  1412. def __neg__(self):
  1413. return Rational(-self.p, self.q)
  1414. @_sympifyit('other', NotImplemented)
  1415. def __add__(self, other):
  1416. if global_parameters.evaluate:
  1417. if isinstance(other, Integer):
  1418. return Rational(self.p + self.q*other.p, self.q, 1)
  1419. elif isinstance(other, Rational):
  1420. #TODO: this can probably be optimized more
  1421. return Rational(self.p*other.q + self.q*other.p, self.q*other.q)
  1422. elif isinstance(other, Float):
  1423. return other + self
  1424. else:
  1425. return Number.__add__(self, other)
  1426. return Number.__add__(self, other)
  1427. __radd__ = __add__
  1428. @_sympifyit('other', NotImplemented)
  1429. def __sub__(self, other):
  1430. if global_parameters.evaluate:
  1431. if isinstance(other, Integer):
  1432. return Rational(self.p - self.q*other.p, self.q, 1)
  1433. elif isinstance(other, Rational):
  1434. return Rational(self.p*other.q - self.q*other.p, self.q*other.q)
  1435. elif isinstance(other, Float):
  1436. return -other + self
  1437. else:
  1438. return Number.__sub__(self, other)
  1439. return Number.__sub__(self, other)
  1440. @_sympifyit('other', NotImplemented)
  1441. def __rsub__(self, other):
  1442. if global_parameters.evaluate:
  1443. if isinstance(other, Integer):
  1444. return Rational(self.q*other.p - self.p, self.q, 1)
  1445. elif isinstance(other, Rational):
  1446. return Rational(self.q*other.p - self.p*other.q, self.q*other.q)
  1447. elif isinstance(other, Float):
  1448. return -self + other
  1449. else:
  1450. return Number.__rsub__(self, other)
  1451. return Number.__rsub__(self, other)
  1452. @_sympifyit('other', NotImplemented)
  1453. def __mul__(self, other):
  1454. if global_parameters.evaluate:
  1455. if isinstance(other, Integer):
  1456. return Rational(self.p*other.p, self.q, igcd(other.p, self.q))
  1457. elif isinstance(other, Rational):
  1458. return Rational(self.p*other.p, self.q*other.q, igcd(self.p, other.q)*igcd(self.q, other.p))
  1459. elif isinstance(other, Float):
  1460. return other*self
  1461. else:
  1462. return Number.__mul__(self, other)
  1463. return Number.__mul__(self, other)
  1464. __rmul__ = __mul__
  1465. @_sympifyit('other', NotImplemented)
  1466. def __truediv__(self, other):
  1467. if global_parameters.evaluate:
  1468. if isinstance(other, Integer):
  1469. if self.p and other.p == S.Zero:
  1470. return S.ComplexInfinity
  1471. else:
  1472. return Rational(self.p, self.q*other.p, igcd(self.p, other.p))
  1473. elif isinstance(other, Rational):
  1474. return Rational(self.p*other.q, self.q*other.p, igcd(self.p, other.p)*igcd(self.q, other.q))
  1475. elif isinstance(other, Float):
  1476. return self*(1/other)
  1477. else:
  1478. return Number.__truediv__(self, other)
  1479. return Number.__truediv__(self, other)
  1480. @_sympifyit('other', NotImplemented)
  1481. def __rtruediv__(self, other):
  1482. if global_parameters.evaluate:
  1483. if isinstance(other, Integer):
  1484. return Rational(other.p*self.q, self.p, igcd(self.p, other.p))
  1485. elif isinstance(other, Rational):
  1486. return Rational(other.p*self.q, other.q*self.p, igcd(self.p, other.p)*igcd(self.q, other.q))
  1487. elif isinstance(other, Float):
  1488. return other*(1/self)
  1489. else:
  1490. return Number.__rtruediv__(self, other)
  1491. return Number.__rtruediv__(self, other)
  1492. @_sympifyit('other', NotImplemented)
  1493. def __mod__(self, other):
  1494. if global_parameters.evaluate:
  1495. if isinstance(other, Rational):
  1496. n = (self.p*other.q) // (other.p*self.q)
  1497. return Rational(self.p*other.q - n*other.p*self.q, self.q*other.q)
  1498. if isinstance(other, Float):
  1499. # calculate mod with Rationals, *then* round the answer
  1500. return Float(self.__mod__(Rational(other)),
  1501. precision=other._prec)
  1502. return Number.__mod__(self, other)
  1503. return Number.__mod__(self, other)
  1504. @_sympifyit('other', NotImplemented)
  1505. def __rmod__(self, other):
  1506. if isinstance(other, Rational):
  1507. return Rational.__mod__(other, self)
  1508. return Number.__rmod__(self, other)
  1509. def _eval_power(self, expt):
  1510. if isinstance(expt, Number):
  1511. if isinstance(expt, Float):
  1512. return self._eval_evalf(expt._prec)**expt
  1513. if expt.is_extended_negative:
  1514. # (3/4)**-2 -> (4/3)**2
  1515. ne = -expt
  1516. if (ne is S.One):
  1517. return Rational(self.q, self.p)
  1518. if self.is_negative:
  1519. return S.NegativeOne**expt*Rational(self.q, -self.p)**ne
  1520. else:
  1521. return Rational(self.q, self.p)**ne
  1522. if expt is S.Infinity: # -oo already caught by test for negative
  1523. if self.p > self.q:
  1524. # (3/2)**oo -> oo
  1525. return S.Infinity
  1526. if self.p < -self.q:
  1527. # (-3/2)**oo -> oo + I*oo
  1528. return S.Infinity + S.Infinity*S.ImaginaryUnit
  1529. return S.Zero
  1530. if isinstance(expt, Integer):
  1531. # (4/3)**2 -> 4**2 / 3**2
  1532. return Rational(self.p**expt.p, self.q**expt.p, 1)
  1533. if isinstance(expt, Rational):
  1534. intpart = expt.p // expt.q
  1535. if intpart:
  1536. intpart += 1
  1537. remfracpart = intpart*expt.q - expt.p
  1538. ratfracpart = Rational(remfracpart, expt.q)
  1539. if self.p != 1:
  1540. return Integer(self.p)**expt*Integer(self.q)**ratfracpart*Rational(1, self.q**intpart, 1)
  1541. return Integer(self.q)**ratfracpart*Rational(1, self.q**intpart, 1)
  1542. else:
  1543. remfracpart = expt.q - expt.p
  1544. ratfracpart = Rational(remfracpart, expt.q)
  1545. if self.p != 1:
  1546. return Integer(self.p)**expt*Integer(self.q)**ratfracpart*Rational(1, self.q, 1)
  1547. return Integer(self.q)**ratfracpart*Rational(1, self.q, 1)
  1548. if self.is_extended_negative and expt.is_even:
  1549. return (-self)**expt
  1550. return
  1551. def _as_mpf_val(self, prec):
  1552. return mlib.from_rational(self.p, self.q, prec, rnd)
  1553. def _mpmath_(self, prec, rnd):
  1554. return mpmath.make_mpf(mlib.from_rational(self.p, self.q, prec, rnd))
  1555. def __abs__(self):
  1556. return Rational(abs(self.p), self.q)
  1557. def __int__(self):
  1558. p, q = self.p, self.q
  1559. if p < 0:
  1560. return -int(-p//q)
  1561. return int(p//q)
  1562. def floor(self):
  1563. return Integer(self.p // self.q)
  1564. def ceiling(self):
  1565. return -Integer(-self.p // self.q)
  1566. def __floor__(self):
  1567. return self.floor()
  1568. def __ceil__(self):
  1569. return self.ceiling()
  1570. def __eq__(self, other):
  1571. try:
  1572. other = _sympify(other)
  1573. except SympifyError:
  1574. return NotImplemented
  1575. if not isinstance(other, Number):
  1576. # S(0) == S.false is False
  1577. # S(0) == False is True
  1578. return False
  1579. if not self:
  1580. return not other
  1581. if other.is_NumberSymbol:
  1582. if other.is_irrational:
  1583. return False
  1584. return other.__eq__(self)
  1585. if other.is_Rational:
  1586. # a Rational is always in reduced form so will never be 2/4
  1587. # so we can just check equivalence of args
  1588. return self.p == other.p and self.q == other.q
  1589. if other.is_Float:
  1590. # all Floats have a denominator that is a power of 2
  1591. # so if self doesn't, it can't be equal to other
  1592. if self.q & (self.q - 1):
  1593. return False
  1594. s, m, t = other._mpf_[:3]
  1595. if s:
  1596. m = -m
  1597. if not t:
  1598. # other is an odd integer
  1599. if not self.is_Integer or self.is_even:
  1600. return False
  1601. return m == self.p
  1602. from .power import integer_log
  1603. if t > 0:
  1604. # other is an even integer
  1605. if not self.is_Integer:
  1606. return False
  1607. # does m*2**t == self.p
  1608. return self.p and not self.p % m and \
  1609. integer_log(self.p//m, 2) == (t, True)
  1610. # does non-integer s*m/2**-t = p/q?
  1611. if self.is_Integer:
  1612. return False
  1613. return m == self.p and integer_log(self.q, 2) == (-t, True)
  1614. return False
  1615. def __ne__(self, other):
  1616. return not self == other
  1617. def _Rrel(self, other, attr):
  1618. # if you want self < other, pass self, other, __gt__
  1619. try:
  1620. other = _sympify(other)
  1621. except SympifyError:
  1622. return NotImplemented
  1623. if other.is_Number:
  1624. op = None
  1625. s, o = self, other
  1626. if other.is_NumberSymbol:
  1627. op = getattr(o, attr)
  1628. elif other.is_Float:
  1629. op = getattr(o, attr)
  1630. elif other.is_Rational:
  1631. s, o = Integer(s.p*o.q), Integer(s.q*o.p)
  1632. op = getattr(o, attr)
  1633. if op:
  1634. return op(s)
  1635. if o.is_number and o.is_extended_real:
  1636. return Integer(s.p), s.q*o
  1637. def __gt__(self, other):
  1638. rv = self._Rrel(other, '__lt__')
  1639. if rv is None:
  1640. rv = self, other
  1641. elif not isinstance(rv, tuple):
  1642. return rv
  1643. return Expr.__gt__(*rv)
  1644. def __ge__(self, other):
  1645. rv = self._Rrel(other, '__le__')
  1646. if rv is None:
  1647. rv = self, other
  1648. elif not isinstance(rv, tuple):
  1649. return rv
  1650. return Expr.__ge__(*rv)
  1651. def __lt__(self, other):
  1652. rv = self._Rrel(other, '__gt__')
  1653. if rv is None:
  1654. rv = self, other
  1655. elif not isinstance(rv, tuple):
  1656. return rv
  1657. return Expr.__lt__(*rv)
  1658. def __le__(self, other):
  1659. rv = self._Rrel(other, '__ge__')
  1660. if rv is None:
  1661. rv = self, other
  1662. elif not isinstance(rv, tuple):
  1663. return rv
  1664. return Expr.__le__(*rv)
  1665. def __hash__(self):
  1666. return super().__hash__()
  1667. def factors(self, limit=None, use_trial=True, use_rho=False,
  1668. use_pm1=False, verbose=False, visual=False):
  1669. """A wrapper to factorint which return factors of self that are
  1670. smaller than limit (or cheap to compute). Special methods of
  1671. factoring are disabled by default so that only trial division is used.
  1672. """
  1673. from sympy.ntheory.factor_ import factorrat
  1674. return factorrat(self, limit=limit, use_trial=use_trial,
  1675. use_rho=use_rho, use_pm1=use_pm1,
  1676. verbose=verbose).copy()
  1677. @property
  1678. def numerator(self):
  1679. return self.p
  1680. @property
  1681. def denominator(self):
  1682. return self.q
  1683. @_sympifyit('other', NotImplemented)
  1684. def gcd(self, other):
  1685. if isinstance(other, Rational):
  1686. if other == S.Zero:
  1687. return other
  1688. return Rational(
  1689. igcd(self.p, other.p),
  1690. ilcm(self.q, other.q))
  1691. return Number.gcd(self, other)
  1692. @_sympifyit('other', NotImplemented)
  1693. def lcm(self, other):
  1694. if isinstance(other, Rational):
  1695. return Rational(
  1696. self.p // igcd(self.p, other.p) * other.p,
  1697. igcd(self.q, other.q))
  1698. return Number.lcm(self, other)
  1699. def as_numer_denom(self):
  1700. return Integer(self.p), Integer(self.q)
  1701. def as_content_primitive(self, radical=False, clear=True):
  1702. """Return the tuple (R, self/R) where R is the positive Rational
  1703. extracted from self.
  1704. Examples
  1705. ========
  1706. >>> from sympy import S
  1707. >>> (S(-3)/2).as_content_primitive()
  1708. (3/2, -1)
  1709. See docstring of Expr.as_content_primitive for more examples.
  1710. """
  1711. if self:
  1712. if self.is_positive:
  1713. return self, S.One
  1714. return -self, S.NegativeOne
  1715. return S.One, self
  1716. def as_coeff_Mul(self, rational=False):
  1717. """Efficiently extract the coefficient of a product."""
  1718. return self, S.One
  1719. def as_coeff_Add(self, rational=False):
  1720. """Efficiently extract the coefficient of a summation."""
  1721. return self, S.Zero
  1722. class Integer(Rational):
  1723. """Represents integer numbers of any size.
  1724. Examples
  1725. ========
  1726. >>> from sympy import Integer
  1727. >>> Integer(3)
  1728. 3
  1729. If a float or a rational is passed to Integer, the fractional part
  1730. will be discarded; the effect is of rounding toward zero.
  1731. >>> Integer(3.8)
  1732. 3
  1733. >>> Integer(-3.8)
  1734. -3
  1735. A string is acceptable input if it can be parsed as an integer:
  1736. >>> Integer("9" * 20)
  1737. 99999999999999999999
  1738. It is rarely needed to explicitly instantiate an Integer, because
  1739. Python integers are automatically converted to Integer when they
  1740. are used in SymPy expressions.
  1741. """
  1742. q = 1
  1743. is_integer = True
  1744. is_number = True
  1745. is_Integer = True
  1746. __slots__ = ()
  1747. def _as_mpf_val(self, prec):
  1748. return mlib.from_int(self.p, prec, rnd)
  1749. def _mpmath_(self, prec, rnd):
  1750. return mpmath.make_mpf(self._as_mpf_val(prec))
  1751. @cacheit
  1752. def __new__(cls, i):
  1753. if isinstance(i, str):
  1754. i = i.replace(' ', '')
  1755. # whereas we cannot, in general, make a Rational from an
  1756. # arbitrary expression, we can make an Integer unambiguously
  1757. # (except when a non-integer expression happens to round to
  1758. # an integer). So we proceed by taking int() of the input and
  1759. # let the int routines determine whether the expression can
  1760. # be made into an int or whether an error should be raised.
  1761. try:
  1762. ival = int(i)
  1763. except TypeError:
  1764. raise TypeError(
  1765. "Argument of Integer should be of numeric type, got %s." % i)
  1766. # We only work with well-behaved integer types. This converts, for
  1767. # example, numpy.int32 instances.
  1768. if ival == 1:
  1769. return S.One
  1770. if ival == -1:
  1771. return S.NegativeOne
  1772. if ival == 0:
  1773. return S.Zero
  1774. obj = Expr.__new__(cls)
  1775. obj.p = ival
  1776. return obj
  1777. def __getnewargs__(self):
  1778. return (self.p,)
  1779. # Arithmetic operations are here for efficiency
  1780. def __int__(self):
  1781. return self.p
  1782. def floor(self):
  1783. return Integer(self.p)
  1784. def ceiling(self):
  1785. return Integer(self.p)
  1786. def __floor__(self):
  1787. return self.floor()
  1788. def __ceil__(self):
  1789. return self.ceiling()
  1790. def __neg__(self):
  1791. return Integer(-self.p)
  1792. def __abs__(self):
  1793. if self.p >= 0:
  1794. return self
  1795. else:
  1796. return Integer(-self.p)
  1797. def __divmod__(self, other):
  1798. if isinstance(other, Integer) and global_parameters.evaluate:
  1799. return Tuple(*(divmod(self.p, other.p)))
  1800. else:
  1801. return Number.__divmod__(self, other)
  1802. def __rdivmod__(self, other):
  1803. if isinstance(other, int) and global_parameters.evaluate:
  1804. return Tuple(*(divmod(other, self.p)))
  1805. else:
  1806. try:
  1807. other = Number(other)
  1808. except TypeError:
  1809. msg = "unsupported operand type(s) for divmod(): '%s' and '%s'"
  1810. oname = type(other).__name__
  1811. sname = type(self).__name__
  1812. raise TypeError(msg % (oname, sname))
  1813. return Number.__divmod__(other, self)
  1814. # TODO make it decorator + bytecodehacks?
  1815. def __add__(self, other):
  1816. if global_parameters.evaluate:
  1817. if isinstance(other, int):
  1818. return Integer(self.p + other)
  1819. elif isinstance(other, Integer):
  1820. return Integer(self.p + other.p)
  1821. elif isinstance(other, Rational):
  1822. return Rational(self.p*other.q + other.p, other.q, 1)
  1823. return Rational.__add__(self, other)
  1824. else:
  1825. return Add(self, other)
  1826. def __radd__(self, other):
  1827. if global_parameters.evaluate:
  1828. if isinstance(other, int):
  1829. return Integer(other + self.p)
  1830. elif isinstance(other, Rational):
  1831. return Rational(other.p + self.p*other.q, other.q, 1)
  1832. return Rational.__radd__(self, other)
  1833. return Rational.__radd__(self, other)
  1834. def __sub__(self, other):
  1835. if global_parameters.evaluate:
  1836. if isinstance(other, int):
  1837. return Integer(self.p - other)
  1838. elif isinstance(other, Integer):
  1839. return Integer(self.p - other.p)
  1840. elif isinstance(other, Rational):
  1841. return Rational(self.p*other.q - other.p, other.q, 1)
  1842. return Rational.__sub__(self, other)
  1843. return Rational.__sub__(self, other)
  1844. def __rsub__(self, other):
  1845. if global_parameters.evaluate:
  1846. if isinstance(other, int):
  1847. return Integer(other - self.p)
  1848. elif isinstance(other, Rational):
  1849. return Rational(other.p - self.p*other.q, other.q, 1)
  1850. return Rational.__rsub__(self, other)
  1851. return Rational.__rsub__(self, other)
  1852. def __mul__(self, other):
  1853. if global_parameters.evaluate:
  1854. if isinstance(other, int):
  1855. return Integer(self.p*other)
  1856. elif isinstance(other, Integer):
  1857. return Integer(self.p*other.p)
  1858. elif isinstance(other, Rational):
  1859. return Rational(self.p*other.p, other.q, igcd(self.p, other.q))
  1860. return Rational.__mul__(self, other)
  1861. return Rational.__mul__(self, other)
  1862. def __rmul__(self, other):
  1863. if global_parameters.evaluate:
  1864. if isinstance(other, int):
  1865. return Integer(other*self.p)
  1866. elif isinstance(other, Rational):
  1867. return Rational(other.p*self.p, other.q, igcd(self.p, other.q))
  1868. return Rational.__rmul__(self, other)
  1869. return Rational.__rmul__(self, other)
  1870. def __mod__(self, other):
  1871. if global_parameters.evaluate:
  1872. if isinstance(other, int):
  1873. return Integer(self.p % other)
  1874. elif isinstance(other, Integer):
  1875. return Integer(self.p % other.p)
  1876. return Rational.__mod__(self, other)
  1877. return Rational.__mod__(self, other)
  1878. def __rmod__(self, other):
  1879. if global_parameters.evaluate:
  1880. if isinstance(other, int):
  1881. return Integer(other % self.p)
  1882. elif isinstance(other, Integer):
  1883. return Integer(other.p % self.p)
  1884. return Rational.__rmod__(self, other)
  1885. return Rational.__rmod__(self, other)
  1886. def __eq__(self, other):
  1887. if isinstance(other, int):
  1888. return (self.p == other)
  1889. elif isinstance(other, Integer):
  1890. return (self.p == other.p)
  1891. return Rational.__eq__(self, other)
  1892. def __ne__(self, other):
  1893. return not self == other
  1894. def __gt__(self, other):
  1895. try:
  1896. other = _sympify(other)
  1897. except SympifyError:
  1898. return NotImplemented
  1899. if other.is_Integer:
  1900. return _sympify(self.p > other.p)
  1901. return Rational.__gt__(self, other)
  1902. def __lt__(self, other):
  1903. try:
  1904. other = _sympify(other)
  1905. except SympifyError:
  1906. return NotImplemented
  1907. if other.is_Integer:
  1908. return _sympify(self.p < other.p)
  1909. return Rational.__lt__(self, other)
  1910. def __ge__(self, other):
  1911. try:
  1912. other = _sympify(other)
  1913. except SympifyError:
  1914. return NotImplemented
  1915. if other.is_Integer:
  1916. return _sympify(self.p >= other.p)
  1917. return Rational.__ge__(self, other)
  1918. def __le__(self, other):
  1919. try:
  1920. other = _sympify(other)
  1921. except SympifyError:
  1922. return NotImplemented
  1923. if other.is_Integer:
  1924. return _sympify(self.p <= other.p)
  1925. return Rational.__le__(self, other)
  1926. def __hash__(self):
  1927. return hash(self.p)
  1928. def __index__(self):
  1929. return self.p
  1930. ########################################
  1931. def _eval_is_odd(self):
  1932. return bool(self.p % 2)
  1933. def _eval_power(self, expt):
  1934. """
  1935. Tries to do some simplifications on self**expt
  1936. Returns None if no further simplifications can be done.
  1937. Explanation
  1938. ===========
  1939. When exponent is a fraction (so we have for example a square root),
  1940. we try to find a simpler representation by factoring the argument
  1941. up to factors of 2**15, e.g.
  1942. - sqrt(4) becomes 2
  1943. - sqrt(-4) becomes 2*I
  1944. - (2**(3+7)*3**(6+7))**Rational(1,7) becomes 6*18**(3/7)
  1945. Further simplification would require a special call to factorint on
  1946. the argument which is not done here for sake of speed.
  1947. """
  1948. from sympy.ntheory.factor_ import perfect_power
  1949. if expt is S.Infinity:
  1950. if self.p > S.One:
  1951. return S.Infinity
  1952. # cases -1, 0, 1 are done in their respective classes
  1953. return S.Infinity + S.ImaginaryUnit*S.Infinity
  1954. if expt is S.NegativeInfinity:
  1955. return Rational(1, self, 1)**S.Infinity
  1956. if not isinstance(expt, Number):
  1957. # simplify when expt is even
  1958. # (-2)**k --> 2**k
  1959. if self.is_negative and expt.is_even:
  1960. return (-self)**expt
  1961. if isinstance(expt, Float):
  1962. # Rational knows how to exponentiate by a Float
  1963. return super()._eval_power(expt)
  1964. if not isinstance(expt, Rational):
  1965. return
  1966. if expt is S.Half and self.is_negative:
  1967. # we extract I for this special case since everyone is doing so
  1968. return S.ImaginaryUnit*Pow(-self, expt)
  1969. if expt.is_negative:
  1970. # invert base and change sign on exponent
  1971. ne = -expt
  1972. if self.is_negative:
  1973. return S.NegativeOne**expt*Rational(1, -self, 1)**ne
  1974. else:
  1975. return Rational(1, self.p, 1)**ne
  1976. # see if base is a perfect root, sqrt(4) --> 2
  1977. x, xexact = integer_nthroot(abs(self.p), expt.q)
  1978. if xexact:
  1979. # if it's a perfect root we've finished
  1980. result = Integer(x**abs(expt.p))
  1981. if self.is_negative:
  1982. result *= S.NegativeOne**expt
  1983. return result
  1984. # The following is an algorithm where we collect perfect roots
  1985. # from the factors of base.
  1986. # if it's not an nth root, it still might be a perfect power
  1987. b_pos = int(abs(self.p))
  1988. p = perfect_power(b_pos)
  1989. if p is not False:
  1990. dict = {p[0]: p[1]}
  1991. else:
  1992. dict = Integer(b_pos).factors(limit=2**15)
  1993. # now process the dict of factors
  1994. out_int = 1 # integer part
  1995. out_rad = 1 # extracted radicals
  1996. sqr_int = 1
  1997. sqr_gcd = 0
  1998. sqr_dict = {}
  1999. for prime, exponent in dict.items():
  2000. exponent *= expt.p
  2001. # remove multiples of expt.q: (2**12)**(1/10) -> 2*(2**2)**(1/10)
  2002. div_e, div_m = divmod(exponent, expt.q)
  2003. if div_e > 0:
  2004. out_int *= prime**div_e
  2005. if div_m > 0:
  2006. # see if the reduced exponent shares a gcd with e.q
  2007. # (2**2)**(1/10) -> 2**(1/5)
  2008. g = igcd(div_m, expt.q)
  2009. if g != 1:
  2010. out_rad *= Pow(prime, Rational(div_m//g, expt.q//g, 1))
  2011. else:
  2012. sqr_dict[prime] = div_m
  2013. # identify gcd of remaining powers
  2014. for p, ex in sqr_dict.items():
  2015. if sqr_gcd == 0:
  2016. sqr_gcd = ex
  2017. else:
  2018. sqr_gcd = igcd(sqr_gcd, ex)
  2019. if sqr_gcd == 1:
  2020. break
  2021. for k, v in sqr_dict.items():
  2022. sqr_int *= k**(v//sqr_gcd)
  2023. if sqr_int == b_pos and out_int == 1 and out_rad == 1:
  2024. result = None
  2025. else:
  2026. result = out_int*out_rad*Pow(sqr_int, Rational(sqr_gcd, expt.q))
  2027. if self.is_negative:
  2028. result *= Pow(S.NegativeOne, expt)
  2029. return result
  2030. def _eval_is_prime(self):
  2031. from sympy.ntheory.primetest import isprime
  2032. return isprime(self)
  2033. def _eval_is_composite(self):
  2034. if self > 1:
  2035. return fuzzy_not(self.is_prime)
  2036. else:
  2037. return False
  2038. def as_numer_denom(self):
  2039. return self, S.One
  2040. @_sympifyit('other', NotImplemented)
  2041. def __floordiv__(self, other):
  2042. if not isinstance(other, Expr):
  2043. return NotImplemented
  2044. if isinstance(other, Integer):
  2045. return Integer(self.p // other)
  2046. return divmod(self, other)[0]
  2047. def __rfloordiv__(self, other):
  2048. return Integer(Integer(other).p // self.p)
  2049. # These bitwise operations (__lshift__, __rlshift__, ..., __invert__) are defined
  2050. # for Integer only and not for general SymPy expressions. This is to achieve
  2051. # compatibility with the numbers.Integral ABC which only defines these operations
  2052. # among instances of numbers.Integral. Therefore, these methods check explicitly for
  2053. # integer types rather than using sympify because they should not accept arbitrary
  2054. # symbolic expressions and there is no symbolic analogue of numbers.Integral's
  2055. # bitwise operations.
  2056. def __lshift__(self, other):
  2057. if isinstance(other, (int, Integer, numbers.Integral)):
  2058. return Integer(self.p << int(other))
  2059. else:
  2060. return NotImplemented
  2061. def __rlshift__(self, other):
  2062. if isinstance(other, (int, numbers.Integral)):
  2063. return Integer(int(other) << self.p)
  2064. else:
  2065. return NotImplemented
  2066. def __rshift__(self, other):
  2067. if isinstance(other, (int, Integer, numbers.Integral)):
  2068. return Integer(self.p >> int(other))
  2069. else:
  2070. return NotImplemented
  2071. def __rrshift__(self, other):
  2072. if isinstance(other, (int, numbers.Integral)):
  2073. return Integer(int(other) >> self.p)
  2074. else:
  2075. return NotImplemented
  2076. def __and__(self, other):
  2077. if isinstance(other, (int, Integer, numbers.Integral)):
  2078. return Integer(self.p & int(other))
  2079. else:
  2080. return NotImplemented
  2081. def __rand__(self, other):
  2082. if isinstance(other, (int, numbers.Integral)):
  2083. return Integer(int(other) & self.p)
  2084. else:
  2085. return NotImplemented
  2086. def __xor__(self, other):
  2087. if isinstance(other, (int, Integer, numbers.Integral)):
  2088. return Integer(self.p ^ int(other))
  2089. else:
  2090. return NotImplemented
  2091. def __rxor__(self, other):
  2092. if isinstance(other, (int, numbers.Integral)):
  2093. return Integer(int(other) ^ self.p)
  2094. else:
  2095. return NotImplemented
  2096. def __or__(self, other):
  2097. if isinstance(other, (int, Integer, numbers.Integral)):
  2098. return Integer(self.p | int(other))
  2099. else:
  2100. return NotImplemented
  2101. def __ror__(self, other):
  2102. if isinstance(other, (int, numbers.Integral)):
  2103. return Integer(int(other) | self.p)
  2104. else:
  2105. return NotImplemented
  2106. def __invert__(self):
  2107. return Integer(~self.p)
  2108. # Add sympify converters
  2109. _sympy_converter[int] = Integer
  2110. class AlgebraicNumber(Expr):
  2111. r"""
  2112. Class for representing algebraic numbers in SymPy.
  2113. Symbolically, an instance of this class represents an element
  2114. $\alpha \in \mathbb{Q}(\theta) \hookrightarrow \mathbb{C}$. That is, the
  2115. algebraic number $\alpha$ is represented as an element of a particular
  2116. number field $\mathbb{Q}(\theta)$, with a particular embedding of this
  2117. field into the complex numbers.
  2118. Formally, the primitive element $\theta$ is given by two data points: (1)
  2119. its minimal polynomial (which defines $\mathbb{Q}(\theta)$), and (2) a
  2120. particular complex number that is a root of this polynomial (which defines
  2121. the embedding $\mathbb{Q}(\theta) \hookrightarrow \mathbb{C}$). Finally,
  2122. the algebraic number $\alpha$ which we represent is then given by the
  2123. coefficients of a polynomial in $\theta$.
  2124. """
  2125. __slots__ = ('rep', 'root', 'alias', 'minpoly', '_own_minpoly')
  2126. is_AlgebraicNumber = True
  2127. is_algebraic = True
  2128. is_number = True
  2129. kind = NumberKind
  2130. # Optional alias symbol is not free.
  2131. # Actually, alias should be a Str, but some methods
  2132. # expect that it be an instance of Expr.
  2133. free_symbols: set[Basic] = set()
  2134. def __new__(cls, expr, coeffs=None, alias=None, **args):
  2135. r"""
  2136. Construct a new algebraic number $\alpha$ belonging to a number field
  2137. $k = \mathbb{Q}(\theta)$.
  2138. There are four instance attributes to be determined:
  2139. =========== ============================================================================
  2140. Attribute Type/Meaning
  2141. =========== ============================================================================
  2142. ``root`` :py:class:`~.Expr` for $\theta$ as a complex number
  2143. ``minpoly`` :py:class:`~.Poly`, the minimal polynomial of $\theta$
  2144. ``rep`` :py:class:`~sympy.polys.polyclasses.DMP` giving $\alpha$ as poly in $\theta$
  2145. ``alias`` :py:class:`~.Symbol` for $\theta$, or ``None``
  2146. =========== ============================================================================
  2147. See Parameters section for how they are determined.
  2148. Parameters
  2149. ==========
  2150. expr : :py:class:`~.Expr`, or pair $(m, r)$
  2151. There are three distinct modes of construction, depending on what
  2152. is passed as *expr*.
  2153. **(1)** *expr* is an :py:class:`~.AlgebraicNumber`:
  2154. In this case we begin by copying all four instance attributes from
  2155. *expr*. If *coeffs* were also given, we compose the two coeff
  2156. polynomials (see below). If an *alias* was given, it overrides.
  2157. **(2)** *expr* is any other type of :py:class:`~.Expr`:
  2158. Then ``root`` will equal *expr*. Therefore it
  2159. must express an algebraic quantity, and we will compute its
  2160. ``minpoly``.
  2161. **(3)** *expr* is an ordered pair $(m, r)$ giving the
  2162. ``minpoly`` $m$, and a ``root`` $r$ thereof, which together
  2163. define $\theta$. In this case $m$ may be either a univariate
  2164. :py:class:`~.Poly` or any :py:class:`~.Expr` which represents the
  2165. same, while $r$ must be some :py:class:`~.Expr` representing a
  2166. complex number that is a root of $m$, including both explicit
  2167. expressions in radicals, and instances of
  2168. :py:class:`~.ComplexRootOf` or :py:class:`~.AlgebraicNumber`.
  2169. coeffs : list, :py:class:`~.ANP`, None, optional (default=None)
  2170. This defines ``rep``, giving the algebraic number $\alpha$ as a
  2171. polynomial in $\theta$.
  2172. If a list, the elements should be integers or rational numbers.
  2173. If an :py:class:`~.ANP`, we take its coefficients (using its
  2174. :py:meth:`~.ANP.to_list()` method). If ``None``, then the list of
  2175. coefficients defaults to ``[1, 0]``, meaning that $\alpha = \theta$
  2176. is the primitive element of the field.
  2177. If *expr* was an :py:class:`~.AlgebraicNumber`, let $g(x)$ be its
  2178. ``rep`` polynomial, and let $f(x)$ be the polynomial defined by
  2179. *coeffs*. Then ``self.rep`` will represent the composition
  2180. $(f \circ g)(x)$.
  2181. alias : str, :py:class:`~.Symbol`, None, optional (default=None)
  2182. This is a way to provide a name for the primitive element. We
  2183. described several ways in which the *expr* argument can define the
  2184. value of the primitive element, but none of these methods gave it
  2185. a name. Here, for example, *alias* could be set as
  2186. ``Symbol('theta')``, in order to make this symbol appear when
  2187. $\alpha$ is printed, or rendered as a polynomial, using the
  2188. :py:meth:`~.as_poly()` method.
  2189. Examples
  2190. ========
  2191. Recall that we are constructing an algebraic number as a field element
  2192. $\alpha \in \mathbb{Q}(\theta)$.
  2193. >>> from sympy import AlgebraicNumber, sqrt, CRootOf, S
  2194. >>> from sympy.abc import x
  2195. Example (1): $\alpha = \theta = \sqrt{2}$
  2196. >>> a1 = AlgebraicNumber(sqrt(2))
  2197. >>> a1.minpoly_of_element().as_expr(x)
  2198. x**2 - 2
  2199. >>> a1.evalf(10)
  2200. 1.414213562
  2201. Example (2): $\alpha = 3 \sqrt{2} - 5$, $\theta = \sqrt{2}$. We can
  2202. either build on the last example:
  2203. >>> a2 = AlgebraicNumber(a1, [3, -5])
  2204. >>> a2.as_expr()
  2205. -5 + 3*sqrt(2)
  2206. or start from scratch:
  2207. >>> a2 = AlgebraicNumber(sqrt(2), [3, -5])
  2208. >>> a2.as_expr()
  2209. -5 + 3*sqrt(2)
  2210. Example (3): $\alpha = 6 \sqrt{2} - 11$, $\theta = \sqrt{2}$. Again we
  2211. can build on the previous example, and we see that the coeff polys are
  2212. composed:
  2213. >>> a3 = AlgebraicNumber(a2, [2, -1])
  2214. >>> a3.as_expr()
  2215. -11 + 6*sqrt(2)
  2216. reflecting the fact that $(2x - 1) \circ (3x - 5) = 6x - 11$.
  2217. Example (4): $\alpha = \sqrt{2}$, $\theta = \sqrt{2} + \sqrt{3}$. The
  2218. easiest way is to use the :py:func:`~.to_number_field()` function:
  2219. >>> from sympy import to_number_field
  2220. >>> a4 = to_number_field(sqrt(2), sqrt(2) + sqrt(3))
  2221. >>> a4.minpoly_of_element().as_expr(x)
  2222. x**2 - 2
  2223. >>> a4.to_root()
  2224. sqrt(2)
  2225. >>> a4.primitive_element()
  2226. sqrt(2) + sqrt(3)
  2227. >>> a4.coeffs()
  2228. [1/2, 0, -9/2, 0]
  2229. but if you already knew the right coefficients, you could construct it
  2230. directly:
  2231. >>> a4 = AlgebraicNumber(sqrt(2) + sqrt(3), [S(1)/2, 0, S(-9)/2, 0])
  2232. >>> a4.to_root()
  2233. sqrt(2)
  2234. >>> a4.primitive_element()
  2235. sqrt(2) + sqrt(3)
  2236. Example (5): Construct the Golden Ratio as an element of the 5th
  2237. cyclotomic field, supposing we already know its coefficients. This time
  2238. we introduce the alias $\zeta$ for the primitive element of the field:
  2239. >>> from sympy import cyclotomic_poly
  2240. >>> from sympy.abc import zeta
  2241. >>> a5 = AlgebraicNumber(CRootOf(cyclotomic_poly(5), -1),
  2242. ... [-1, -1, 0, 0], alias=zeta)
  2243. >>> a5.as_poly().as_expr()
  2244. -zeta**3 - zeta**2
  2245. >>> a5.evalf()
  2246. 1.61803398874989
  2247. (The index ``-1`` to ``CRootOf`` selects the complex root with the
  2248. largest real and imaginary parts, which in this case is
  2249. $\mathrm{e}^{2i\pi/5}$. See :py:class:`~.ComplexRootOf`.)
  2250. Example (6): Building on the last example, construct the number
  2251. $2 \phi \in \mathbb{Q}(\phi)$, where $\phi$ is the Golden Ratio:
  2252. >>> from sympy.abc import phi
  2253. >>> a6 = AlgebraicNumber(a5.to_root(), coeffs=[2, 0], alias=phi)
  2254. >>> a6.as_poly().as_expr()
  2255. 2*phi
  2256. >>> a6.primitive_element().evalf()
  2257. 1.61803398874989
  2258. Note that we needed to use ``a5.to_root()``, since passing ``a5`` as
  2259. the first argument would have constructed the number $2 \phi$ as an
  2260. element of the field $\mathbb{Q}(\zeta)$:
  2261. >>> a6_wrong = AlgebraicNumber(a5, coeffs=[2, 0])
  2262. >>> a6_wrong.as_poly().as_expr()
  2263. -2*zeta**3 - 2*zeta**2
  2264. >>> a6_wrong.primitive_element().evalf()
  2265. 0.309016994374947 + 0.951056516295154*I
  2266. """
  2267. from sympy.polys.polyclasses import ANP, DMP
  2268. from sympy.polys.numberfields import minimal_polynomial
  2269. expr = sympify(expr)
  2270. rep0 = None
  2271. alias0 = None
  2272. if isinstance(expr, (tuple, Tuple)):
  2273. minpoly, root = expr
  2274. if not minpoly.is_Poly:
  2275. from sympy.polys.polytools import Poly
  2276. minpoly = Poly(minpoly)
  2277. elif expr.is_AlgebraicNumber:
  2278. minpoly, root, rep0, alias0 = (expr.minpoly, expr.root,
  2279. expr.rep, expr.alias)
  2280. else:
  2281. minpoly, root = minimal_polynomial(
  2282. expr, args.get('gen'), polys=True), expr
  2283. dom = minpoly.get_domain()
  2284. if coeffs is not None:
  2285. if not isinstance(coeffs, ANP):
  2286. rep = DMP.from_sympy_list(sympify(coeffs), 0, dom)
  2287. scoeffs = Tuple(*coeffs)
  2288. else:
  2289. rep = DMP.from_list(coeffs.to_list(), 0, dom)
  2290. scoeffs = Tuple(*coeffs.to_list())
  2291. else:
  2292. rep = DMP.from_list([1, 0], 0, dom)
  2293. scoeffs = Tuple(1, 0)
  2294. if rep0 is not None:
  2295. from sympy.polys.densetools import dup_compose
  2296. c = dup_compose(rep.rep, rep0.rep, dom)
  2297. rep = DMP.from_list(c, 0, dom)
  2298. scoeffs = Tuple(*c)
  2299. if rep.degree() >= minpoly.degree():
  2300. rep = rep.rem(minpoly.rep)
  2301. sargs = (root, scoeffs)
  2302. alias = alias or alias0
  2303. if alias is not None:
  2304. from .symbol import Symbol
  2305. if not isinstance(alias, Symbol):
  2306. alias = Symbol(alias)
  2307. sargs = sargs + (alias,)
  2308. obj = Expr.__new__(cls, *sargs)
  2309. obj.rep = rep
  2310. obj.root = root
  2311. obj.alias = alias
  2312. obj.minpoly = minpoly
  2313. obj._own_minpoly = None
  2314. return obj
  2315. def __hash__(self):
  2316. return super().__hash__()
  2317. def _eval_evalf(self, prec):
  2318. return self.as_expr()._evalf(prec)
  2319. @property
  2320. def is_aliased(self):
  2321. """Returns ``True`` if ``alias`` was set. """
  2322. return self.alias is not None
  2323. def as_poly(self, x=None):
  2324. """Create a Poly instance from ``self``. """
  2325. from sympy.polys.polytools import Poly, PurePoly
  2326. if x is not None:
  2327. return Poly.new(self.rep, x)
  2328. else:
  2329. if self.alias is not None:
  2330. return Poly.new(self.rep, self.alias)
  2331. else:
  2332. from .symbol import Dummy
  2333. return PurePoly.new(self.rep, Dummy('x'))
  2334. def as_expr(self, x=None):
  2335. """Create a Basic expression from ``self``. """
  2336. return self.as_poly(x or self.root).as_expr().expand()
  2337. def coeffs(self):
  2338. """Returns all SymPy coefficients of an algebraic number. """
  2339. return [ self.rep.dom.to_sympy(c) for c in self.rep.all_coeffs() ]
  2340. def native_coeffs(self):
  2341. """Returns all native coefficients of an algebraic number. """
  2342. return self.rep.all_coeffs()
  2343. def to_algebraic_integer(self):
  2344. """Convert ``self`` to an algebraic integer. """
  2345. from sympy.polys.polytools import Poly
  2346. f = self.minpoly
  2347. if f.LC() == 1:
  2348. return self
  2349. coeff = f.LC()**(f.degree() - 1)
  2350. poly = f.compose(Poly(f.gen/f.LC()))
  2351. minpoly = poly*coeff
  2352. root = f.LC()*self.root
  2353. return AlgebraicNumber((minpoly, root), self.coeffs())
  2354. def _eval_simplify(self, **kwargs):
  2355. from sympy.polys.rootoftools import CRootOf
  2356. from sympy.polys import minpoly
  2357. measure, ratio = kwargs['measure'], kwargs['ratio']
  2358. for r in [r for r in self.minpoly.all_roots() if r.func != CRootOf]:
  2359. if minpoly(self.root - r).is_Symbol:
  2360. # use the matching root if it's simpler
  2361. if measure(r) < ratio*measure(self.root):
  2362. return AlgebraicNumber(r)
  2363. return self
  2364. def field_element(self, coeffs):
  2365. r"""
  2366. Form another element of the same number field.
  2367. Explanation
  2368. ===========
  2369. If we represent $\alpha \in \mathbb{Q}(\theta)$, form another element
  2370. $\beta \in \mathbb{Q}(\theta)$ of the same number field.
  2371. Parameters
  2372. ==========
  2373. coeffs : list, :py:class:`~.ANP`
  2374. Like the *coeffs* arg to the class
  2375. :py:meth:`constructor<.AlgebraicNumber.__new__>`, defines the
  2376. new element as a polynomial in the primitive element.
  2377. If a list, the elements should be integers or rational numbers.
  2378. If an :py:class:`~.ANP`, we take its coefficients (using its
  2379. :py:meth:`~.ANP.to_list()` method).
  2380. Examples
  2381. ========
  2382. >>> from sympy import AlgebraicNumber, sqrt
  2383. >>> a = AlgebraicNumber(sqrt(5), [-1, 1])
  2384. >>> b = a.field_element([3, 2])
  2385. >>> print(a)
  2386. 1 - sqrt(5)
  2387. >>> print(b)
  2388. 2 + 3*sqrt(5)
  2389. >>> print(b.primitive_element() == a.primitive_element())
  2390. True
  2391. See Also
  2392. ========
  2393. AlgebraicNumber
  2394. """
  2395. return AlgebraicNumber(
  2396. (self.minpoly, self.root), coeffs=coeffs, alias=self.alias)
  2397. @property
  2398. def is_primitive_element(self):
  2399. r"""
  2400. Say whether this algebraic number $\alpha \in \mathbb{Q}(\theta)$ is
  2401. equal to the primitive element $\theta$ for its field.
  2402. """
  2403. c = self.coeffs()
  2404. # Second case occurs if self.minpoly is linear:
  2405. return c == [1, 0] or c == [self.root]
  2406. def primitive_element(self):
  2407. r"""
  2408. Get the primitive element $\theta$ for the number field
  2409. $\mathbb{Q}(\theta)$ to which this algebraic number $\alpha$ belongs.
  2410. Returns
  2411. =======
  2412. AlgebraicNumber
  2413. """
  2414. if self.is_primitive_element:
  2415. return self
  2416. return self.field_element([1, 0])
  2417. def to_primitive_element(self, radicals=True):
  2418. r"""
  2419. Convert ``self`` to an :py:class:`~.AlgebraicNumber` instance that is
  2420. equal to its own primitive element.
  2421. Explanation
  2422. ===========
  2423. If we represent $\alpha \in \mathbb{Q}(\theta)$, $\alpha \neq \theta$,
  2424. construct a new :py:class:`~.AlgebraicNumber` that represents
  2425. $\alpha \in \mathbb{Q}(\alpha)$.
  2426. Examples
  2427. ========
  2428. >>> from sympy import sqrt, to_number_field
  2429. >>> from sympy.abc import x
  2430. >>> a = to_number_field(sqrt(2), sqrt(2) + sqrt(3))
  2431. The :py:class:`~.AlgebraicNumber` ``a`` represents the number
  2432. $\sqrt{2}$ in the field $\mathbb{Q}(\sqrt{2} + \sqrt{3})$. Rendering
  2433. ``a`` as a polynomial,
  2434. >>> a.as_poly().as_expr(x)
  2435. x**3/2 - 9*x/2
  2436. reflects the fact that $\sqrt{2} = \theta^3/2 - 9 \theta/2$, where
  2437. $\theta = \sqrt{2} + \sqrt{3}$.
  2438. ``a`` is not equal to its own primitive element. Its minpoly
  2439. >>> a.minpoly.as_poly().as_expr(x)
  2440. x**4 - 10*x**2 + 1
  2441. is that of $\theta$.
  2442. Converting to a primitive element,
  2443. >>> a_prim = a.to_primitive_element()
  2444. >>> a_prim.minpoly.as_poly().as_expr(x)
  2445. x**2 - 2
  2446. we obtain an :py:class:`~.AlgebraicNumber` whose ``minpoly`` is that of
  2447. the number itself.
  2448. Parameters
  2449. ==========
  2450. radicals : boolean, optional (default=True)
  2451. If ``True``, then we will try to return an
  2452. :py:class:`~.AlgebraicNumber` whose ``root`` is an expression
  2453. in radicals. If that is not possible (or if *radicals* is
  2454. ``False``), ``root`` will be a :py:class:`~.ComplexRootOf`.
  2455. Returns
  2456. =======
  2457. AlgebraicNumber
  2458. See Also
  2459. ========
  2460. is_primitive_element
  2461. """
  2462. if self.is_primitive_element:
  2463. return self
  2464. m = self.minpoly_of_element()
  2465. r = self.to_root(radicals=radicals)
  2466. return AlgebraicNumber((m, r))
  2467. def minpoly_of_element(self):
  2468. r"""
  2469. Compute the minimal polynomial for this algebraic number.
  2470. Explanation
  2471. ===========
  2472. Recall that we represent an element $\alpha \in \mathbb{Q}(\theta)$.
  2473. Our instance attribute ``self.minpoly`` is the minimal polynomial for
  2474. our primitive element $\theta$. This method computes the minimal
  2475. polynomial for $\alpha$.
  2476. """
  2477. if self._own_minpoly is None:
  2478. if self.is_primitive_element:
  2479. self._own_minpoly = self.minpoly
  2480. else:
  2481. from sympy.polys.numberfields.minpoly import minpoly
  2482. theta = self.primitive_element()
  2483. self._own_minpoly = minpoly(self.as_expr(theta), polys=True)
  2484. return self._own_minpoly
  2485. def to_root(self, radicals=True, minpoly=None):
  2486. """
  2487. Convert to an :py:class:`~.Expr` that is not an
  2488. :py:class:`~.AlgebraicNumber`, specifically, either a
  2489. :py:class:`~.ComplexRootOf`, or, optionally and where possible, an
  2490. expression in radicals.
  2491. Parameters
  2492. ==========
  2493. radicals : boolean, optional (default=True)
  2494. If ``True``, then we will try to return the root as an expression
  2495. in radicals. If that is not possible, we will return a
  2496. :py:class:`~.ComplexRootOf`.
  2497. minpoly : :py:class:`~.Poly`
  2498. If the minimal polynomial for `self` has been pre-computed, it can
  2499. be passed in order to save time.
  2500. """
  2501. if self.is_primitive_element and not isinstance(self.root, AlgebraicNumber):
  2502. return self.root
  2503. m = minpoly or self.minpoly_of_element()
  2504. roots = m.all_roots(radicals=radicals)
  2505. if len(roots) == 1:
  2506. return roots[0]
  2507. ex = self.as_expr()
  2508. for b in roots:
  2509. if m.same_root(b, ex):
  2510. return b
  2511. class RationalConstant(Rational):
  2512. """
  2513. Abstract base class for rationals with specific behaviors
  2514. Derived classes must define class attributes p and q and should probably all
  2515. be singletons.
  2516. """
  2517. __slots__ = ()
  2518. def __new__(cls):
  2519. return AtomicExpr.__new__(cls)
  2520. class IntegerConstant(Integer):
  2521. __slots__ = ()
  2522. def __new__(cls):
  2523. return AtomicExpr.__new__(cls)
  2524. class Zero(IntegerConstant, metaclass=Singleton):
  2525. """The number zero.
  2526. Zero is a singleton, and can be accessed by ``S.Zero``
  2527. Examples
  2528. ========
  2529. >>> from sympy import S, Integer
  2530. >>> Integer(0) is S.Zero
  2531. True
  2532. >>> 1/S.Zero
  2533. zoo
  2534. References
  2535. ==========
  2536. .. [1] https://en.wikipedia.org/wiki/Zero
  2537. """
  2538. p = 0
  2539. q = 1
  2540. is_positive = False
  2541. is_negative = False
  2542. is_zero = True
  2543. is_number = True
  2544. is_comparable = True
  2545. __slots__ = ()
  2546. def __getnewargs__(self):
  2547. return ()
  2548. @staticmethod
  2549. def __abs__():
  2550. return S.Zero
  2551. @staticmethod
  2552. def __neg__():
  2553. return S.Zero
  2554. def _eval_power(self, expt):
  2555. if expt.is_extended_positive:
  2556. return self
  2557. if expt.is_extended_negative:
  2558. return S.ComplexInfinity
  2559. if expt.is_extended_real is False:
  2560. return S.NaN
  2561. if expt.is_zero:
  2562. return S.One
  2563. # infinities are already handled with pos and neg
  2564. # tests above; now throw away leading numbers on Mul
  2565. # exponent since 0**-x = zoo**x even when x == 0
  2566. coeff, terms = expt.as_coeff_Mul()
  2567. if coeff.is_negative:
  2568. return S.ComplexInfinity**terms
  2569. if coeff is not S.One: # there is a Number to discard
  2570. return self**terms
  2571. def _eval_order(self, *symbols):
  2572. # Order(0,x) -> 0
  2573. return self
  2574. def __bool__(self):
  2575. return False
  2576. class One(IntegerConstant, metaclass=Singleton):
  2577. """The number one.
  2578. One is a singleton, and can be accessed by ``S.One``.
  2579. Examples
  2580. ========
  2581. >>> from sympy import S, Integer
  2582. >>> Integer(1) is S.One
  2583. True
  2584. References
  2585. ==========
  2586. .. [1] https://en.wikipedia.org/wiki/1_%28number%29
  2587. """
  2588. is_number = True
  2589. is_positive = True
  2590. p = 1
  2591. q = 1
  2592. __slots__ = ()
  2593. def __getnewargs__(self):
  2594. return ()
  2595. @staticmethod
  2596. def __abs__():
  2597. return S.One
  2598. @staticmethod
  2599. def __neg__():
  2600. return S.NegativeOne
  2601. def _eval_power(self, expt):
  2602. return self
  2603. def _eval_order(self, *symbols):
  2604. return
  2605. @staticmethod
  2606. def factors(limit=None, use_trial=True, use_rho=False, use_pm1=False,
  2607. verbose=False, visual=False):
  2608. if visual:
  2609. return S.One
  2610. else:
  2611. return {}
  2612. class NegativeOne(IntegerConstant, metaclass=Singleton):
  2613. """The number negative one.
  2614. NegativeOne is a singleton, and can be accessed by ``S.NegativeOne``.
  2615. Examples
  2616. ========
  2617. >>> from sympy import S, Integer
  2618. >>> Integer(-1) is S.NegativeOne
  2619. True
  2620. See Also
  2621. ========
  2622. One
  2623. References
  2624. ==========
  2625. .. [1] https://en.wikipedia.org/wiki/%E2%88%921_%28number%29
  2626. """
  2627. is_number = True
  2628. p = -1
  2629. q = 1
  2630. __slots__ = ()
  2631. def __getnewargs__(self):
  2632. return ()
  2633. @staticmethod
  2634. def __abs__():
  2635. return S.One
  2636. @staticmethod
  2637. def __neg__():
  2638. return S.One
  2639. def _eval_power(self, expt):
  2640. if expt.is_odd:
  2641. return S.NegativeOne
  2642. if expt.is_even:
  2643. return S.One
  2644. if isinstance(expt, Number):
  2645. if isinstance(expt, Float):
  2646. return Float(-1.0)**expt
  2647. if expt is S.NaN:
  2648. return S.NaN
  2649. if expt in (S.Infinity, S.NegativeInfinity):
  2650. return S.NaN
  2651. if expt is S.Half:
  2652. return S.ImaginaryUnit
  2653. if isinstance(expt, Rational):
  2654. if expt.q == 2:
  2655. return S.ImaginaryUnit**Integer(expt.p)
  2656. i, r = divmod(expt.p, expt.q)
  2657. if i:
  2658. return self**i*self**Rational(r, expt.q)
  2659. return
  2660. class Half(RationalConstant, metaclass=Singleton):
  2661. """The rational number 1/2.
  2662. Half is a singleton, and can be accessed by ``S.Half``.
  2663. Examples
  2664. ========
  2665. >>> from sympy import S, Rational
  2666. >>> Rational(1, 2) is S.Half
  2667. True
  2668. References
  2669. ==========
  2670. .. [1] https://en.wikipedia.org/wiki/One_half
  2671. """
  2672. is_number = True
  2673. p = 1
  2674. q = 2
  2675. __slots__ = ()
  2676. def __getnewargs__(self):
  2677. return ()
  2678. @staticmethod
  2679. def __abs__():
  2680. return S.Half
  2681. class Infinity(Number, metaclass=Singleton):
  2682. r"""Positive infinite quantity.
  2683. Explanation
  2684. ===========
  2685. In real analysis the symbol `\infty` denotes an unbounded
  2686. limit: `x\to\infty` means that `x` grows without bound.
  2687. Infinity is often used not only to define a limit but as a value
  2688. in the affinely extended real number system. Points labeled `+\infty`
  2689. and `-\infty` can be added to the topological space of the real numbers,
  2690. producing the two-point compactification of the real numbers. Adding
  2691. algebraic properties to this gives us the extended real numbers.
  2692. Infinity is a singleton, and can be accessed by ``S.Infinity``,
  2693. or can be imported as ``oo``.
  2694. Examples
  2695. ========
  2696. >>> from sympy import oo, exp, limit, Symbol
  2697. >>> 1 + oo
  2698. oo
  2699. >>> 42/oo
  2700. 0
  2701. >>> x = Symbol('x')
  2702. >>> limit(exp(x), x, oo)
  2703. oo
  2704. See Also
  2705. ========
  2706. NegativeInfinity, NaN
  2707. References
  2708. ==========
  2709. .. [1] https://en.wikipedia.org/wiki/Infinity
  2710. """
  2711. is_commutative = True
  2712. is_number = True
  2713. is_complex = False
  2714. is_extended_real = True
  2715. is_infinite = True
  2716. is_comparable = True
  2717. is_extended_positive = True
  2718. is_prime = False
  2719. __slots__ = ()
  2720. def __new__(cls):
  2721. return AtomicExpr.__new__(cls)
  2722. def _latex(self, printer):
  2723. return r"\infty"
  2724. def _eval_subs(self, old, new):
  2725. if self == old:
  2726. return new
  2727. def _eval_evalf(self, prec=None):
  2728. return Float('inf')
  2729. def evalf(self, prec=None, **options):
  2730. return self._eval_evalf(prec)
  2731. @_sympifyit('other', NotImplemented)
  2732. def __add__(self, other):
  2733. if isinstance(other, Number) and global_parameters.evaluate:
  2734. if other in (S.NegativeInfinity, S.NaN):
  2735. return S.NaN
  2736. return self
  2737. return Number.__add__(self, other)
  2738. __radd__ = __add__
  2739. @_sympifyit('other', NotImplemented)
  2740. def __sub__(self, other):
  2741. if isinstance(other, Number) and global_parameters.evaluate:
  2742. if other in (S.Infinity, S.NaN):
  2743. return S.NaN
  2744. return self
  2745. return Number.__sub__(self, other)
  2746. @_sympifyit('other', NotImplemented)
  2747. def __rsub__(self, other):
  2748. return (-self).__add__(other)
  2749. @_sympifyit('other', NotImplemented)
  2750. def __mul__(self, other):
  2751. if isinstance(other, Number) and global_parameters.evaluate:
  2752. if other.is_zero or other is S.NaN:
  2753. return S.NaN
  2754. if other.is_extended_positive:
  2755. return self
  2756. return S.NegativeInfinity
  2757. return Number.__mul__(self, other)
  2758. __rmul__ = __mul__
  2759. @_sympifyit('other', NotImplemented)
  2760. def __truediv__(self, other):
  2761. if isinstance(other, Number) and global_parameters.evaluate:
  2762. if other is S.Infinity or \
  2763. other is S.NegativeInfinity or \
  2764. other is S.NaN:
  2765. return S.NaN
  2766. if other.is_extended_nonnegative:
  2767. return self
  2768. return S.NegativeInfinity
  2769. return Number.__truediv__(self, other)
  2770. def __abs__(self):
  2771. return S.Infinity
  2772. def __neg__(self):
  2773. return S.NegativeInfinity
  2774. def _eval_power(self, expt):
  2775. """
  2776. ``expt`` is symbolic object but not equal to 0 or 1.
  2777. ================ ======= ==============================
  2778. Expression Result Notes
  2779. ================ ======= ==============================
  2780. ``oo ** nan`` ``nan``
  2781. ``oo ** -p`` ``0`` ``p`` is number, ``oo``
  2782. ================ ======= ==============================
  2783. See Also
  2784. ========
  2785. Pow
  2786. NaN
  2787. NegativeInfinity
  2788. """
  2789. if expt.is_extended_positive:
  2790. return S.Infinity
  2791. if expt.is_extended_negative:
  2792. return S.Zero
  2793. if expt is S.NaN:
  2794. return S.NaN
  2795. if expt is S.ComplexInfinity:
  2796. return S.NaN
  2797. if expt.is_extended_real is False and expt.is_number:
  2798. from sympy.functions.elementary.complexes import re
  2799. expt_real = re(expt)
  2800. if expt_real.is_positive:
  2801. return S.ComplexInfinity
  2802. if expt_real.is_negative:
  2803. return S.Zero
  2804. if expt_real.is_zero:
  2805. return S.NaN
  2806. return self**expt.evalf()
  2807. def _as_mpf_val(self, prec):
  2808. return mlib.finf
  2809. def __hash__(self):
  2810. return super().__hash__()
  2811. def __eq__(self, other):
  2812. return other is S.Infinity or other == float('inf')
  2813. def __ne__(self, other):
  2814. return other is not S.Infinity and other != float('inf')
  2815. __gt__ = Expr.__gt__
  2816. __ge__ = Expr.__ge__
  2817. __lt__ = Expr.__lt__
  2818. __le__ = Expr.__le__
  2819. @_sympifyit('other', NotImplemented)
  2820. def __mod__(self, other):
  2821. if not isinstance(other, Expr):
  2822. return NotImplemented
  2823. return S.NaN
  2824. __rmod__ = __mod__
  2825. def floor(self):
  2826. return self
  2827. def ceiling(self):
  2828. return self
  2829. oo = S.Infinity
  2830. class NegativeInfinity(Number, metaclass=Singleton):
  2831. """Negative infinite quantity.
  2832. NegativeInfinity is a singleton, and can be accessed
  2833. by ``S.NegativeInfinity``.
  2834. See Also
  2835. ========
  2836. Infinity
  2837. """
  2838. is_extended_real = True
  2839. is_complex = False
  2840. is_commutative = True
  2841. is_infinite = True
  2842. is_comparable = True
  2843. is_extended_negative = True
  2844. is_number = True
  2845. is_prime = False
  2846. __slots__ = ()
  2847. def __new__(cls):
  2848. return AtomicExpr.__new__(cls)
  2849. def _latex(self, printer):
  2850. return r"-\infty"
  2851. def _eval_subs(self, old, new):
  2852. if self == old:
  2853. return new
  2854. def _eval_evalf(self, prec=None):
  2855. return Float('-inf')
  2856. def evalf(self, prec=None, **options):
  2857. return self._eval_evalf(prec)
  2858. @_sympifyit('other', NotImplemented)
  2859. def __add__(self, other):
  2860. if isinstance(other, Number) and global_parameters.evaluate:
  2861. if other in (S.Infinity, S.NaN):
  2862. return S.NaN
  2863. return self
  2864. return Number.__add__(self, other)
  2865. __radd__ = __add__
  2866. @_sympifyit('other', NotImplemented)
  2867. def __sub__(self, other):
  2868. if isinstance(other, Number) and global_parameters.evaluate:
  2869. if other in (S.NegativeInfinity, S.NaN):
  2870. return S.NaN
  2871. return self
  2872. return Number.__sub__(self, other)
  2873. @_sympifyit('other', NotImplemented)
  2874. def __rsub__(self, other):
  2875. return (-self).__add__(other)
  2876. @_sympifyit('other', NotImplemented)
  2877. def __mul__(self, other):
  2878. if isinstance(other, Number) and global_parameters.evaluate:
  2879. if other.is_zero or other is S.NaN:
  2880. return S.NaN
  2881. if other.is_extended_positive:
  2882. return self
  2883. return S.Infinity
  2884. return Number.__mul__(self, other)
  2885. __rmul__ = __mul__
  2886. @_sympifyit('other', NotImplemented)
  2887. def __truediv__(self, other):
  2888. if isinstance(other, Number) and global_parameters.evaluate:
  2889. if other is S.Infinity or \
  2890. other is S.NegativeInfinity or \
  2891. other is S.NaN:
  2892. return S.NaN
  2893. if other.is_extended_nonnegative:
  2894. return self
  2895. return S.Infinity
  2896. return Number.__truediv__(self, other)
  2897. def __abs__(self):
  2898. return S.Infinity
  2899. def __neg__(self):
  2900. return S.Infinity
  2901. def _eval_power(self, expt):
  2902. """
  2903. ``expt`` is symbolic object but not equal to 0 or 1.
  2904. ================ ======= ==============================
  2905. Expression Result Notes
  2906. ================ ======= ==============================
  2907. ``(-oo) ** nan`` ``nan``
  2908. ``(-oo) ** oo`` ``nan``
  2909. ``(-oo) ** -oo`` ``nan``
  2910. ``(-oo) ** e`` ``oo`` ``e`` is positive even integer
  2911. ``(-oo) ** o`` ``-oo`` ``o`` is positive odd integer
  2912. ================ ======= ==============================
  2913. See Also
  2914. ========
  2915. Infinity
  2916. Pow
  2917. NaN
  2918. """
  2919. if expt.is_number:
  2920. if expt is S.NaN or \
  2921. expt is S.Infinity or \
  2922. expt is S.NegativeInfinity:
  2923. return S.NaN
  2924. if isinstance(expt, Integer) and expt.is_extended_positive:
  2925. if expt.is_odd:
  2926. return S.NegativeInfinity
  2927. else:
  2928. return S.Infinity
  2929. inf_part = S.Infinity**expt
  2930. s_part = S.NegativeOne**expt
  2931. if inf_part == 0 and s_part.is_finite:
  2932. return inf_part
  2933. if (inf_part is S.ComplexInfinity and
  2934. s_part.is_finite and not s_part.is_zero):
  2935. return S.ComplexInfinity
  2936. return s_part*inf_part
  2937. def _as_mpf_val(self, prec):
  2938. return mlib.fninf
  2939. def __hash__(self):
  2940. return super().__hash__()
  2941. def __eq__(self, other):
  2942. return other is S.NegativeInfinity or other == float('-inf')
  2943. def __ne__(self, other):
  2944. return other is not S.NegativeInfinity and other != float('-inf')
  2945. __gt__ = Expr.__gt__
  2946. __ge__ = Expr.__ge__
  2947. __lt__ = Expr.__lt__
  2948. __le__ = Expr.__le__
  2949. @_sympifyit('other', NotImplemented)
  2950. def __mod__(self, other):
  2951. if not isinstance(other, Expr):
  2952. return NotImplemented
  2953. return S.NaN
  2954. __rmod__ = __mod__
  2955. def floor(self):
  2956. return self
  2957. def ceiling(self):
  2958. return self
  2959. def as_powers_dict(self):
  2960. return {S.NegativeOne: 1, S.Infinity: 1}
  2961. class NaN(Number, metaclass=Singleton):
  2962. """
  2963. Not a Number.
  2964. Explanation
  2965. ===========
  2966. This serves as a place holder for numeric values that are indeterminate.
  2967. Most operations on NaN, produce another NaN. Most indeterminate forms,
  2968. such as ``0/0`` or ``oo - oo` produce NaN. Two exceptions are ``0**0``
  2969. and ``oo**0``, which all produce ``1`` (this is consistent with Python's
  2970. float).
  2971. NaN is loosely related to floating point nan, which is defined in the
  2972. IEEE 754 floating point standard, and corresponds to the Python
  2973. ``float('nan')``. Differences are noted below.
  2974. NaN is mathematically not equal to anything else, even NaN itself. This
  2975. explains the initially counter-intuitive results with ``Eq`` and ``==`` in
  2976. the examples below.
  2977. NaN is not comparable so inequalities raise a TypeError. This is in
  2978. contrast with floating point nan where all inequalities are false.
  2979. NaN is a singleton, and can be accessed by ``S.NaN``, or can be imported
  2980. as ``nan``.
  2981. Examples
  2982. ========
  2983. >>> from sympy import nan, S, oo, Eq
  2984. >>> nan is S.NaN
  2985. True
  2986. >>> oo - oo
  2987. nan
  2988. >>> nan + 1
  2989. nan
  2990. >>> Eq(nan, nan) # mathematical equality
  2991. False
  2992. >>> nan == nan # structural equality
  2993. True
  2994. References
  2995. ==========
  2996. .. [1] https://en.wikipedia.org/wiki/NaN
  2997. """
  2998. is_commutative = True
  2999. is_extended_real = None
  3000. is_real = None
  3001. is_rational = None
  3002. is_algebraic = None
  3003. is_transcendental = None
  3004. is_integer = None
  3005. is_comparable = False
  3006. is_finite = None
  3007. is_zero = None
  3008. is_prime = None
  3009. is_positive = None
  3010. is_negative = None
  3011. is_number = True
  3012. __slots__ = ()
  3013. def __new__(cls):
  3014. return AtomicExpr.__new__(cls)
  3015. def _latex(self, printer):
  3016. return r"\text{NaN}"
  3017. def __neg__(self):
  3018. return self
  3019. @_sympifyit('other', NotImplemented)
  3020. def __add__(self, other):
  3021. return self
  3022. @_sympifyit('other', NotImplemented)
  3023. def __sub__(self, other):
  3024. return self
  3025. @_sympifyit('other', NotImplemented)
  3026. def __mul__(self, other):
  3027. return self
  3028. @_sympifyit('other', NotImplemented)
  3029. def __truediv__(self, other):
  3030. return self
  3031. def floor(self):
  3032. return self
  3033. def ceiling(self):
  3034. return self
  3035. def _as_mpf_val(self, prec):
  3036. return _mpf_nan
  3037. def __hash__(self):
  3038. return super().__hash__()
  3039. def __eq__(self, other):
  3040. # NaN is structurally equal to another NaN
  3041. return other is S.NaN
  3042. def __ne__(self, other):
  3043. return other is not S.NaN
  3044. # Expr will _sympify and raise TypeError
  3045. __gt__ = Expr.__gt__
  3046. __ge__ = Expr.__ge__
  3047. __lt__ = Expr.__lt__
  3048. __le__ = Expr.__le__
  3049. nan = S.NaN
  3050. @dispatch(NaN, Expr) # type:ignore
  3051. def _eval_is_eq(a, b): # noqa:F811
  3052. return False
  3053. class ComplexInfinity(AtomicExpr, metaclass=Singleton):
  3054. r"""Complex infinity.
  3055. Explanation
  3056. ===========
  3057. In complex analysis the symbol `\tilde\infty`, called "complex
  3058. infinity", represents a quantity with infinite magnitude, but
  3059. undetermined complex phase.
  3060. ComplexInfinity is a singleton, and can be accessed by
  3061. ``S.ComplexInfinity``, or can be imported as ``zoo``.
  3062. Examples
  3063. ========
  3064. >>> from sympy import zoo
  3065. >>> zoo + 42
  3066. zoo
  3067. >>> 42/zoo
  3068. 0
  3069. >>> zoo + zoo
  3070. nan
  3071. >>> zoo*zoo
  3072. zoo
  3073. See Also
  3074. ========
  3075. Infinity
  3076. """
  3077. is_commutative = True
  3078. is_infinite = True
  3079. is_number = True
  3080. is_prime = False
  3081. is_complex = False
  3082. is_extended_real = False
  3083. kind = NumberKind
  3084. __slots__ = ()
  3085. def __new__(cls):
  3086. return AtomicExpr.__new__(cls)
  3087. def _latex(self, printer):
  3088. return r"\tilde{\infty}"
  3089. @staticmethod
  3090. def __abs__():
  3091. return S.Infinity
  3092. def floor(self):
  3093. return self
  3094. def ceiling(self):
  3095. return self
  3096. @staticmethod
  3097. def __neg__():
  3098. return S.ComplexInfinity
  3099. def _eval_power(self, expt):
  3100. if expt is S.ComplexInfinity:
  3101. return S.NaN
  3102. if isinstance(expt, Number):
  3103. if expt.is_zero:
  3104. return S.NaN
  3105. else:
  3106. if expt.is_positive:
  3107. return S.ComplexInfinity
  3108. else:
  3109. return S.Zero
  3110. zoo = S.ComplexInfinity
  3111. class NumberSymbol(AtomicExpr):
  3112. is_commutative = True
  3113. is_finite = True
  3114. is_number = True
  3115. __slots__ = ()
  3116. is_NumberSymbol = True
  3117. kind = NumberKind
  3118. def __new__(cls):
  3119. return AtomicExpr.__new__(cls)
  3120. def approximation(self, number_cls):
  3121. """ Return an interval with number_cls endpoints
  3122. that contains the value of NumberSymbol.
  3123. If not implemented, then return None.
  3124. """
  3125. def _eval_evalf(self, prec):
  3126. return Float._new(self._as_mpf_val(prec), prec)
  3127. def __eq__(self, other):
  3128. try:
  3129. other = _sympify(other)
  3130. except SympifyError:
  3131. return NotImplemented
  3132. if self is other:
  3133. return True
  3134. if other.is_Number and self.is_irrational:
  3135. return False
  3136. return False # NumberSymbol != non-(Number|self)
  3137. def __ne__(self, other):
  3138. return not self == other
  3139. def __le__(self, other):
  3140. if self is other:
  3141. return S.true
  3142. return Expr.__le__(self, other)
  3143. def __ge__(self, other):
  3144. if self is other:
  3145. return S.true
  3146. return Expr.__ge__(self, other)
  3147. def __int__(self):
  3148. # subclass with appropriate return value
  3149. raise NotImplementedError
  3150. def __hash__(self):
  3151. return super().__hash__()
  3152. class Exp1(NumberSymbol, metaclass=Singleton):
  3153. r"""The `e` constant.
  3154. Explanation
  3155. ===========
  3156. The transcendental number `e = 2.718281828\ldots` is the base of the
  3157. natural logarithm and of the exponential function, `e = \exp(1)`.
  3158. Sometimes called Euler's number or Napier's constant.
  3159. Exp1 is a singleton, and can be accessed by ``S.Exp1``,
  3160. or can be imported as ``E``.
  3161. Examples
  3162. ========
  3163. >>> from sympy import exp, log, E
  3164. >>> E is exp(1)
  3165. True
  3166. >>> log(E)
  3167. 1
  3168. References
  3169. ==========
  3170. .. [1] https://en.wikipedia.org/wiki/E_%28mathematical_constant%29
  3171. """
  3172. is_real = True
  3173. is_positive = True
  3174. is_negative = False # XXX Forces is_negative/is_nonnegative
  3175. is_irrational = True
  3176. is_number = True
  3177. is_algebraic = False
  3178. is_transcendental = True
  3179. __slots__ = ()
  3180. def _latex(self, printer):
  3181. return r"e"
  3182. @staticmethod
  3183. def __abs__():
  3184. return S.Exp1
  3185. def __int__(self):
  3186. return 2
  3187. def _as_mpf_val(self, prec):
  3188. return mpf_e(prec)
  3189. def approximation_interval(self, number_cls):
  3190. if issubclass(number_cls, Integer):
  3191. return (Integer(2), Integer(3))
  3192. elif issubclass(number_cls, Rational):
  3193. pass
  3194. def _eval_power(self, expt):
  3195. if global_parameters.exp_is_pow:
  3196. return self._eval_power_exp_is_pow(expt)
  3197. else:
  3198. from sympy.functions.elementary.exponential import exp
  3199. return exp(expt)
  3200. def _eval_power_exp_is_pow(self, arg):
  3201. if arg.is_Number:
  3202. if arg is oo:
  3203. return oo
  3204. elif arg == -oo:
  3205. return S.Zero
  3206. from sympy.functions.elementary.exponential import log
  3207. if isinstance(arg, log):
  3208. return arg.args[0]
  3209. # don't autoexpand Pow or Mul (see the issue 3351):
  3210. elif not arg.is_Add:
  3211. Ioo = I*oo
  3212. if arg in [Ioo, -Ioo]:
  3213. return nan
  3214. coeff = arg.coeff(pi*I)
  3215. if coeff:
  3216. if (2*coeff).is_integer:
  3217. if coeff.is_even:
  3218. return S.One
  3219. elif coeff.is_odd:
  3220. return S.NegativeOne
  3221. elif (coeff + S.Half).is_even:
  3222. return -I
  3223. elif (coeff + S.Half).is_odd:
  3224. return I
  3225. elif coeff.is_Rational:
  3226. ncoeff = coeff % 2 # restrict to [0, 2pi)
  3227. if ncoeff > 1: # restrict to (-pi, pi]
  3228. ncoeff -= 2
  3229. if ncoeff != coeff:
  3230. return S.Exp1**(ncoeff*S.Pi*S.ImaginaryUnit)
  3231. # Warning: code in risch.py will be very sensitive to changes
  3232. # in this (see DifferentialExtension).
  3233. # look for a single log factor
  3234. coeff, terms = arg.as_coeff_Mul()
  3235. # but it can't be multiplied by oo
  3236. if coeff in (oo, -oo):
  3237. return
  3238. coeffs, log_term = [coeff], None
  3239. for term in Mul.make_args(terms):
  3240. if isinstance(term, log):
  3241. if log_term is None:
  3242. log_term = term.args[0]
  3243. else:
  3244. return
  3245. elif term.is_comparable:
  3246. coeffs.append(term)
  3247. else:
  3248. return
  3249. return log_term**Mul(*coeffs) if log_term else None
  3250. elif arg.is_Add:
  3251. out = []
  3252. add = []
  3253. argchanged = False
  3254. for a in arg.args:
  3255. if a is S.One:
  3256. add.append(a)
  3257. continue
  3258. newa = self**a
  3259. if isinstance(newa, Pow) and newa.base is self:
  3260. if newa.exp != a:
  3261. add.append(newa.exp)
  3262. argchanged = True
  3263. else:
  3264. add.append(a)
  3265. else:
  3266. out.append(newa)
  3267. if out or argchanged:
  3268. return Mul(*out)*Pow(self, Add(*add), evaluate=False)
  3269. elif arg.is_Matrix:
  3270. return arg.exp()
  3271. def _eval_rewrite_as_sin(self, **kwargs):
  3272. from sympy.functions.elementary.trigonometric import sin
  3273. return sin(I + S.Pi/2) - I*sin(I)
  3274. def _eval_rewrite_as_cos(self, **kwargs):
  3275. from sympy.functions.elementary.trigonometric import cos
  3276. return cos(I) + I*cos(I + S.Pi/2)
  3277. E = S.Exp1
  3278. class Pi(NumberSymbol, metaclass=Singleton):
  3279. r"""The `\pi` constant.
  3280. Explanation
  3281. ===========
  3282. The transcendental number `\pi = 3.141592654\ldots` represents the ratio
  3283. of a circle's circumference to its diameter, the area of the unit circle,
  3284. the half-period of trigonometric functions, and many other things
  3285. in mathematics.
  3286. Pi is a singleton, and can be accessed by ``S.Pi``, or can
  3287. be imported as ``pi``.
  3288. Examples
  3289. ========
  3290. >>> from sympy import S, pi, oo, sin, exp, integrate, Symbol
  3291. >>> S.Pi
  3292. pi
  3293. >>> pi > 3
  3294. True
  3295. >>> pi.is_irrational
  3296. True
  3297. >>> x = Symbol('x')
  3298. >>> sin(x + 2*pi)
  3299. sin(x)
  3300. >>> integrate(exp(-x**2), (x, -oo, oo))
  3301. sqrt(pi)
  3302. References
  3303. ==========
  3304. .. [1] https://en.wikipedia.org/wiki/Pi
  3305. """
  3306. is_real = True
  3307. is_positive = True
  3308. is_negative = False
  3309. is_irrational = True
  3310. is_number = True
  3311. is_algebraic = False
  3312. is_transcendental = True
  3313. __slots__ = ()
  3314. def _latex(self, printer):
  3315. return r"\pi"
  3316. @staticmethod
  3317. def __abs__():
  3318. return S.Pi
  3319. def __int__(self):
  3320. return 3
  3321. def _as_mpf_val(self, prec):
  3322. return mpf_pi(prec)
  3323. def approximation_interval(self, number_cls):
  3324. if issubclass(number_cls, Integer):
  3325. return (Integer(3), Integer(4))
  3326. elif issubclass(number_cls, Rational):
  3327. return (Rational(223, 71, 1), Rational(22, 7, 1))
  3328. pi = S.Pi
  3329. class GoldenRatio(NumberSymbol, metaclass=Singleton):
  3330. r"""The golden ratio, `\phi`.
  3331. Explanation
  3332. ===========
  3333. `\phi = \frac{1 + \sqrt{5}}{2}` is an algebraic number. Two quantities
  3334. are in the golden ratio if their ratio is the same as the ratio of
  3335. their sum to the larger of the two quantities, i.e. their maximum.
  3336. GoldenRatio is a singleton, and can be accessed by ``S.GoldenRatio``.
  3337. Examples
  3338. ========
  3339. >>> from sympy import S
  3340. >>> S.GoldenRatio > 1
  3341. True
  3342. >>> S.GoldenRatio.expand(func=True)
  3343. 1/2 + sqrt(5)/2
  3344. >>> S.GoldenRatio.is_irrational
  3345. True
  3346. References
  3347. ==========
  3348. .. [1] https://en.wikipedia.org/wiki/Golden_ratio
  3349. """
  3350. is_real = True
  3351. is_positive = True
  3352. is_negative = False
  3353. is_irrational = True
  3354. is_number = True
  3355. is_algebraic = True
  3356. is_transcendental = False
  3357. __slots__ = ()
  3358. def _latex(self, printer):
  3359. return r"\phi"
  3360. def __int__(self):
  3361. return 1
  3362. def _as_mpf_val(self, prec):
  3363. # XXX track down why this has to be increased
  3364. rv = mlib.from_man_exp(phi_fixed(prec + 10), -prec - 10)
  3365. return mpf_norm(rv, prec)
  3366. def _eval_expand_func(self, **hints):
  3367. from sympy.functions.elementary.miscellaneous import sqrt
  3368. return S.Half + S.Half*sqrt(5)
  3369. def approximation_interval(self, number_cls):
  3370. if issubclass(number_cls, Integer):
  3371. return (S.One, Rational(2))
  3372. elif issubclass(number_cls, Rational):
  3373. pass
  3374. _eval_rewrite_as_sqrt = _eval_expand_func
  3375. class TribonacciConstant(NumberSymbol, metaclass=Singleton):
  3376. r"""The tribonacci constant.
  3377. Explanation
  3378. ===========
  3379. The tribonacci numbers are like the Fibonacci numbers, but instead
  3380. of starting with two predetermined terms, the sequence starts with
  3381. three predetermined terms and each term afterwards is the sum of the
  3382. preceding three terms.
  3383. The tribonacci constant is the ratio toward which adjacent tribonacci
  3384. numbers tend. It is a root of the polynomial `x^3 - x^2 - x - 1 = 0`,
  3385. and also satisfies the equation `x + x^{-3} = 2`.
  3386. TribonacciConstant is a singleton, and can be accessed
  3387. by ``S.TribonacciConstant``.
  3388. Examples
  3389. ========
  3390. >>> from sympy import S
  3391. >>> S.TribonacciConstant > 1
  3392. True
  3393. >>> S.TribonacciConstant.expand(func=True)
  3394. 1/3 + (19 - 3*sqrt(33))**(1/3)/3 + (3*sqrt(33) + 19)**(1/3)/3
  3395. >>> S.TribonacciConstant.is_irrational
  3396. True
  3397. >>> S.TribonacciConstant.n(20)
  3398. 1.8392867552141611326
  3399. References
  3400. ==========
  3401. .. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers
  3402. """
  3403. is_real = True
  3404. is_positive = True
  3405. is_negative = False
  3406. is_irrational = True
  3407. is_number = True
  3408. is_algebraic = True
  3409. is_transcendental = False
  3410. __slots__ = ()
  3411. def _latex(self, printer):
  3412. return r"\text{TribonacciConstant}"
  3413. def __int__(self):
  3414. return 1
  3415. def _eval_evalf(self, prec):
  3416. rv = self._eval_expand_func(function=True)._eval_evalf(prec + 4)
  3417. return Float(rv, precision=prec)
  3418. def _eval_expand_func(self, **hints):
  3419. from sympy.functions.elementary.miscellaneous import cbrt, sqrt
  3420. return (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
  3421. def approximation_interval(self, number_cls):
  3422. if issubclass(number_cls, Integer):
  3423. return (S.One, Rational(2))
  3424. elif issubclass(number_cls, Rational):
  3425. pass
  3426. _eval_rewrite_as_sqrt = _eval_expand_func
  3427. class EulerGamma(NumberSymbol, metaclass=Singleton):
  3428. r"""The Euler-Mascheroni constant.
  3429. Explanation
  3430. ===========
  3431. `\gamma = 0.5772157\ldots` (also called Euler's constant) is a mathematical
  3432. constant recurring in analysis and number theory. It is defined as the
  3433. limiting difference between the harmonic series and the
  3434. natural logarithm:
  3435. .. math:: \gamma = \lim\limits_{n\to\infty}
  3436. \left(\sum\limits_{k=1}^n\frac{1}{k} - \ln n\right)
  3437. EulerGamma is a singleton, and can be accessed by ``S.EulerGamma``.
  3438. Examples
  3439. ========
  3440. >>> from sympy import S
  3441. >>> S.EulerGamma.is_irrational
  3442. >>> S.EulerGamma > 0
  3443. True
  3444. >>> S.EulerGamma > 1
  3445. False
  3446. References
  3447. ==========
  3448. .. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant
  3449. """
  3450. is_real = True
  3451. is_positive = True
  3452. is_negative = False
  3453. is_irrational = None
  3454. is_number = True
  3455. __slots__ = ()
  3456. def _latex(self, printer):
  3457. return r"\gamma"
  3458. def __int__(self):
  3459. return 0
  3460. def _as_mpf_val(self, prec):
  3461. # XXX track down why this has to be increased
  3462. v = mlib.libhyper.euler_fixed(prec + 10)
  3463. rv = mlib.from_man_exp(v, -prec - 10)
  3464. return mpf_norm(rv, prec)
  3465. def approximation_interval(self, number_cls):
  3466. if issubclass(number_cls, Integer):
  3467. return (S.Zero, S.One)
  3468. elif issubclass(number_cls, Rational):
  3469. return (S.Half, Rational(3, 5, 1))
  3470. class Catalan(NumberSymbol, metaclass=Singleton):
  3471. r"""Catalan's constant.
  3472. Explanation
  3473. ===========
  3474. $G = 0.91596559\ldots$ is given by the infinite series
  3475. .. math:: G = \sum_{k=0}^{\infty} \frac{(-1)^k}{(2k+1)^2}
  3476. Catalan is a singleton, and can be accessed by ``S.Catalan``.
  3477. Examples
  3478. ========
  3479. >>> from sympy import S
  3480. >>> S.Catalan.is_irrational
  3481. >>> S.Catalan > 0
  3482. True
  3483. >>> S.Catalan > 1
  3484. False
  3485. References
  3486. ==========
  3487. .. [1] https://en.wikipedia.org/wiki/Catalan%27s_constant
  3488. """
  3489. is_real = True
  3490. is_positive = True
  3491. is_negative = False
  3492. is_irrational = None
  3493. is_number = True
  3494. __slots__ = ()
  3495. def __int__(self):
  3496. return 0
  3497. def _as_mpf_val(self, prec):
  3498. # XXX track down why this has to be increased
  3499. v = mlib.catalan_fixed(prec + 10)
  3500. rv = mlib.from_man_exp(v, -prec - 10)
  3501. return mpf_norm(rv, prec)
  3502. def approximation_interval(self, number_cls):
  3503. if issubclass(number_cls, Integer):
  3504. return (S.Zero, S.One)
  3505. elif issubclass(number_cls, Rational):
  3506. return (Rational(9, 10, 1), S.One)
  3507. def _eval_rewrite_as_Sum(self, k_sym=None, symbols=None):
  3508. if (k_sym is not None) or (symbols is not None):
  3509. return self
  3510. from .symbol import Dummy
  3511. from sympy.concrete.summations import Sum
  3512. k = Dummy('k', integer=True, nonnegative=True)
  3513. return Sum(S.NegativeOne**k / (2*k+1)**2, (k, 0, S.Infinity))
  3514. def _latex(self, printer):
  3515. return "G"
  3516. class ImaginaryUnit(AtomicExpr, metaclass=Singleton):
  3517. r"""The imaginary unit, `i = \sqrt{-1}`.
  3518. I is a singleton, and can be accessed by ``S.I``, or can be
  3519. imported as ``I``.
  3520. Examples
  3521. ========
  3522. >>> from sympy import I, sqrt
  3523. >>> sqrt(-1)
  3524. I
  3525. >>> I*I
  3526. -1
  3527. >>> 1/I
  3528. -I
  3529. References
  3530. ==========
  3531. .. [1] https://en.wikipedia.org/wiki/Imaginary_unit
  3532. """
  3533. is_commutative = True
  3534. is_imaginary = True
  3535. is_finite = True
  3536. is_number = True
  3537. is_algebraic = True
  3538. is_transcendental = False
  3539. kind = NumberKind
  3540. __slots__ = ()
  3541. def _latex(self, printer):
  3542. return printer._settings['imaginary_unit_latex']
  3543. @staticmethod
  3544. def __abs__():
  3545. return S.One
  3546. def _eval_evalf(self, prec):
  3547. return self
  3548. def _eval_conjugate(self):
  3549. return -S.ImaginaryUnit
  3550. def _eval_power(self, expt):
  3551. """
  3552. b is I = sqrt(-1)
  3553. e is symbolic object but not equal to 0, 1
  3554. I**r -> (-1)**(r/2) -> exp(r/2*Pi*I) -> sin(Pi*r/2) + cos(Pi*r/2)*I, r is decimal
  3555. I**0 mod 4 -> 1
  3556. I**1 mod 4 -> I
  3557. I**2 mod 4 -> -1
  3558. I**3 mod 4 -> -I
  3559. """
  3560. if isinstance(expt, Integer):
  3561. expt = expt % 4
  3562. if expt == 0:
  3563. return S.One
  3564. elif expt == 1:
  3565. return S.ImaginaryUnit
  3566. elif expt == 2:
  3567. return S.NegativeOne
  3568. elif expt == 3:
  3569. return -S.ImaginaryUnit
  3570. if isinstance(expt, Rational):
  3571. i, r = divmod(expt, 2)
  3572. rv = Pow(S.ImaginaryUnit, r, evaluate=False)
  3573. if i % 2:
  3574. return Mul(S.NegativeOne, rv, evaluate=False)
  3575. return rv
  3576. def as_base_exp(self):
  3577. return S.NegativeOne, S.Half
  3578. @property
  3579. def _mpc_(self):
  3580. return (Float(0)._mpf_, Float(1)._mpf_)
  3581. I = S.ImaginaryUnit
  3582. def equal_valued(x, y):
  3583. """Compare expressions treating plain floats as rationals.
  3584. Examples
  3585. ========
  3586. >>> from sympy import S, symbols, Rational, Float
  3587. >>> from sympy.core.numbers import equal_valued
  3588. >>> equal_valued(1, 2)
  3589. False
  3590. >>> equal_valued(1, 1)
  3591. True
  3592. In SymPy expressions with Floats compare unequal to corresponding
  3593. expressions with rationals:
  3594. >>> x = symbols('x')
  3595. >>> x**2 == x**2.0
  3596. False
  3597. However an individual Float compares equal to a Rational:
  3598. >>> Rational(1, 2) == Float(0.5)
  3599. True
  3600. In a future version of SymPy this might change so that Rational and Float
  3601. compare unequal. This function provides the behavior currently expected of
  3602. ``==`` so that it could still be used if the behavior of ``==`` were to
  3603. change in future.
  3604. >>> equal_valued(1, 1.0) # Float vs Rational
  3605. True
  3606. >>> equal_valued(S(1).n(3), S(1).n(5)) # Floats of different precision
  3607. True
  3608. Explanation
  3609. ===========
  3610. In future SymPy verions Float and Rational might compare unequal and floats
  3611. with different precisions might compare unequal. In that context a function
  3612. is needed that can check if a number is equal to 1 or 0 etc. The idea is
  3613. that instead of testing ``if x == 1:`` if we want to accept floats like
  3614. ``1.0`` as well then the test can be written as ``if equal_valued(x, 1):``
  3615. or ``if equal_valued(x, 2):``. Since this function is intended to be used
  3616. in situations where one or both operands are expected to be concrete
  3617. numbers like 1 or 0 the function does not recurse through the args of any
  3618. compound expression to compare any nested floats.
  3619. References
  3620. ==========
  3621. .. [1] https://github.com/sympy/sympy/pull/20033
  3622. """
  3623. x = _sympify(x)
  3624. y = _sympify(y)
  3625. # Handle everything except Float/Rational first
  3626. if not x.is_Float and not y.is_Float:
  3627. return x == y
  3628. elif x.is_Float and y.is_Float:
  3629. # Compare values without regard for precision
  3630. return x._mpf_ == y._mpf_
  3631. elif x.is_Float:
  3632. x, y = y, x
  3633. if not x.is_Rational:
  3634. return False
  3635. # Now y is Float and x is Rational. A simple approach at this point would
  3636. # just be x == Rational(y) but if y has a large exponent creating a
  3637. # Rational could be prohibitively expensive.
  3638. sign, man, exp, _ = y._mpf_
  3639. p, q = x.p, x.q
  3640. if sign:
  3641. man = -man
  3642. if exp == 0:
  3643. # y odd integer
  3644. return q == 1 and man == p
  3645. elif exp > 0:
  3646. # y even integer
  3647. if q != 1:
  3648. return False
  3649. if p.bit_length() != man.bit_length() + exp:
  3650. return False
  3651. return man << exp == p
  3652. else:
  3653. # y non-integer. Need p == man and q == 2**-exp
  3654. if p != man:
  3655. return False
  3656. neg_exp = -exp
  3657. if q.bit_length() - 1 != neg_exp:
  3658. return False
  3659. return (1 << neg_exp) == q
  3660. @dispatch(Tuple, Number) # type:ignore
  3661. def _eval_is_eq(self, other): # noqa: F811
  3662. return False
  3663. def sympify_fractions(f):
  3664. return Rational(f.numerator, f.denominator, 1)
  3665. _sympy_converter[fractions.Fraction] = sympify_fractions
  3666. if HAS_GMPY:
  3667. def sympify_mpz(x):
  3668. return Integer(int(x))
  3669. # XXX: The sympify_mpq function here was never used because it is
  3670. # overridden by the other sympify_mpq function below. Maybe it should just
  3671. # be removed or maybe it should be used for something...
  3672. def sympify_mpq(x):
  3673. return Rational(int(x.numerator), int(x.denominator))
  3674. _sympy_converter[type(gmpy.mpz(1))] = sympify_mpz
  3675. _sympy_converter[type(gmpy.mpq(1, 2))] = sympify_mpq
  3676. def sympify_mpmath_mpq(x):
  3677. p, q = x._mpq_
  3678. return Rational(p, q, 1)
  3679. _sympy_converter[type(mpmath.rational.mpq(1, 2))] = sympify_mpmath_mpq
  3680. def sympify_mpmath(x):
  3681. return Expr._from_mpmath(x, x.context.prec)
  3682. _sympy_converter[mpnumeric] = sympify_mpmath
  3683. def sympify_complex(a):
  3684. real, imag = list(map(sympify, (a.real, a.imag)))
  3685. return real + S.ImaginaryUnit*imag
  3686. _sympy_converter[complex] = sympify_complex
  3687. from .power import Pow, integer_nthroot
  3688. from .mul import Mul
  3689. Mul.identity = One()
  3690. from .add import Add
  3691. Add.identity = Zero()
  3692. def _register_classes():
  3693. numbers.Number.register(Number)
  3694. numbers.Real.register(Float)
  3695. numbers.Rational.register(Rational)
  3696. numbers.Integral.register(Integer)
  3697. _register_classes()
  3698. _illegal = (S.NaN, S.Infinity, S.NegativeInfinity, S.ComplexInfinity)