numbers.py 134 KB

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