expr.py 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194
  1. from __future__ import annotations
  2. from typing import TYPE_CHECKING, overload
  3. from collections.abc import Iterable, Mapping
  4. from functools import reduce
  5. import re
  6. from .sympify import sympify, _sympify
  7. from .basic import Basic, Atom
  8. from .singleton import S
  9. from .evalf import EvalfMixin, pure_complex, DEFAULT_MAXPREC
  10. from .decorators import call_highest_priority, sympify_method_args, sympify_return
  11. from .cache import cacheit
  12. from .logic import fuzzy_or, fuzzy_not
  13. from .intfunc import mod_inverse
  14. from .sorting import default_sort_key
  15. from .kind import NumberKind
  16. from sympy.utilities.exceptions import sympy_deprecation_warning
  17. from sympy.utilities.misc import as_int, func_name, filldedent
  18. from sympy.utilities.iterables import has_variety, sift
  19. from mpmath.libmp import mpf_log, prec_to_dps
  20. from mpmath.libmp.libintmath import giant_steps
  21. if TYPE_CHECKING:
  22. from typing import Any
  23. from typing_extensions import Self
  24. from .numbers import Number
  25. from collections import defaultdict
  26. def _corem(eq, c): # helper for extract_additively
  27. # return co, diff from co*c + diff
  28. co = []
  29. non = []
  30. for i in Add.make_args(eq):
  31. ci = i.coeff(c)
  32. if not ci:
  33. non.append(i)
  34. else:
  35. co.append(ci)
  36. return Add(*co), Add(*non)
  37. @sympify_method_args
  38. class Expr(Basic, EvalfMixin):
  39. """
  40. Base class for algebraic expressions.
  41. Explanation
  42. ===========
  43. Everything that requires arithmetic operations to be defined
  44. should subclass this class, instead of Basic (which should be
  45. used only for argument storage and expression manipulation, i.e.
  46. pattern matching, substitutions, etc).
  47. If you want to override the comparisons of expressions:
  48. Should use _eval_is_ge for inequality, or _eval_is_eq, with multiple dispatch.
  49. _eval_is_ge return true if x >= y, false if x < y, and None if the two types
  50. are not comparable or the comparison is indeterminate
  51. See Also
  52. ========
  53. sympy.core.basic.Basic
  54. """
  55. __slots__: tuple[str, ...] = ()
  56. if TYPE_CHECKING:
  57. def __new__(cls, *args: Basic) -> Self:
  58. ...
  59. @overload # type: ignore
  60. def subs(self, arg1: Mapping[Basic | complex, Expr | complex], arg2: None=None) -> Expr: ...
  61. @overload
  62. def subs(self, arg1: Iterable[tuple[Basic | complex, Expr | complex]], arg2: None=None, **kwargs: Any) -> Expr: ...
  63. @overload
  64. def subs(self, arg1: Expr | complex, arg2: Expr | complex) -> Expr: ...
  65. @overload
  66. def subs(self, arg1: Mapping[Basic | complex, Basic | complex], arg2: None=None, **kwargs: Any) -> Basic: ...
  67. @overload
  68. def subs(self, arg1: Iterable[tuple[Basic | complex, Basic | complex]], arg2: None=None, **kwargs: Any) -> Basic: ...
  69. @overload
  70. def subs(self, arg1: Basic | complex, arg2: Basic | complex, **kwargs: Any) -> Basic: ...
  71. def subs(self, arg1: Mapping[Basic | complex, Basic | complex] | Basic | complex, # type: ignore
  72. arg2: Basic | complex | None = None, **kwargs: Any) -> Basic:
  73. ...
  74. def simplify(self, **kwargs) -> Expr:
  75. ...
  76. def evalf(self, n: int = 15, subs: dict[Basic, Basic | float] | None = None,
  77. maxn: int = 100, chop: bool = False, strict: bool = False,
  78. quad: str | None = None, verbose: bool = False) -> Expr:
  79. ...
  80. n = evalf
  81. is_scalar = True # self derivative is 1
  82. @property
  83. def _diff_wrt(self):
  84. """Return True if one can differentiate with respect to this
  85. object, else False.
  86. Explanation
  87. ===========
  88. Subclasses such as Symbol, Function and Derivative return True
  89. to enable derivatives wrt them. The implementation in Derivative
  90. separates the Symbol and non-Symbol (_diff_wrt=True) variables and
  91. temporarily converts the non-Symbols into Symbols when performing
  92. the differentiation. By default, any object deriving from Expr
  93. will behave like a scalar with self.diff(self) == 1. If this is
  94. not desired then the object must also set `is_scalar = False` or
  95. else define an _eval_derivative routine.
  96. Note, see the docstring of Derivative for how this should work
  97. mathematically. In particular, note that expr.subs(yourclass, Symbol)
  98. should be well-defined on a structural level, or this will lead to
  99. inconsistent results.
  100. Examples
  101. ========
  102. >>> from sympy import Expr
  103. >>> e = Expr()
  104. >>> e._diff_wrt
  105. False
  106. >>> class MyScalar(Expr):
  107. ... _diff_wrt = True
  108. ...
  109. >>> MyScalar().diff(MyScalar())
  110. 1
  111. >>> class MySymbol(Expr):
  112. ... _diff_wrt = True
  113. ... is_scalar = False
  114. ...
  115. >>> MySymbol().diff(MySymbol())
  116. Derivative(MySymbol(), MySymbol())
  117. """
  118. return False
  119. @cacheit
  120. def sort_key(self, order=None):
  121. coeff, expr = self.as_coeff_Mul()
  122. if expr.is_Pow:
  123. base, exp = expr.as_base_exp()
  124. if base is S.Exp1:
  125. # If we remove this, many doctests will go crazy:
  126. # (keeps E**x sorted like the exp(x) function,
  127. # part of exp(x) to E**x transition)
  128. base, exp = Function("exp")(exp), S.One
  129. expr = base
  130. else:
  131. exp = S.One
  132. if expr.is_Dummy:
  133. args = (expr.sort_key(),)
  134. elif expr.is_Atom:
  135. args = (str(expr),)
  136. else:
  137. if expr.is_Add:
  138. args = expr.as_ordered_terms(order=order)
  139. elif expr.is_Mul:
  140. args = expr.as_ordered_factors(order=order)
  141. else:
  142. args = expr.args
  143. args = tuple(
  144. [ default_sort_key(arg, order=order) for arg in args ])
  145. args = (len(args), tuple(args))
  146. exp = exp.sort_key(order=order)
  147. return expr.class_key(), args, exp, coeff
  148. def _hashable_content(self):
  149. """Return a tuple of information about self that can be used to
  150. compute the hash. If a class defines additional attributes,
  151. like ``name`` in Symbol, then this method should be updated
  152. accordingly to return such relevant attributes.
  153. Defining more than _hashable_content is necessary if __eq__ has
  154. been defined by a class. See note about this in Basic.__eq__."""
  155. return self._args
  156. # ***************
  157. # * Arithmetics *
  158. # ***************
  159. # Expr and its subclasses use _op_priority to determine which object
  160. # passed to a binary special method (__mul__, etc.) will handle the
  161. # operation. In general, the 'call_highest_priority' decorator will choose
  162. # the object with the highest _op_priority to handle the call.
  163. # Custom subclasses that want to define their own binary special methods
  164. # should set an _op_priority value that is higher than the default.
  165. #
  166. # **NOTE**:
  167. # This is a temporary fix, and will eventually be replaced with
  168. # something better and more powerful. See issue 5510.
  169. _op_priority = 10.0
  170. @property
  171. def _add_handler(self):
  172. return Add
  173. @property
  174. def _mul_handler(self):
  175. return Mul
  176. def __pos__(self) -> Expr:
  177. return self
  178. def __neg__(self) -> Expr:
  179. # Mul has its own __neg__ routine, so we just
  180. # create a 2-args Mul with the -1 in the canonical
  181. # slot 0.
  182. c = self.is_commutative
  183. return Mul._from_args((S.NegativeOne, self), c)
  184. def __abs__(self) -> Expr:
  185. from sympy.functions.elementary.complexes import Abs
  186. return Abs(self)
  187. @sympify_return([('other', 'Expr')], NotImplemented)
  188. @call_highest_priority('__radd__')
  189. def __add__(self, other) -> Expr:
  190. return Add(self, other)
  191. @sympify_return([('other', 'Expr')], NotImplemented)
  192. @call_highest_priority('__add__')
  193. def __radd__(self, other) -> Expr:
  194. return Add(other, self)
  195. @sympify_return([('other', 'Expr')], NotImplemented)
  196. @call_highest_priority('__rsub__')
  197. def __sub__(self, other) -> Expr:
  198. return Add(self, -other)
  199. @sympify_return([('other', 'Expr')], NotImplemented)
  200. @call_highest_priority('__sub__')
  201. def __rsub__(self, other) -> Expr:
  202. return Add(other, -self)
  203. @sympify_return([('other', 'Expr')], NotImplemented)
  204. @call_highest_priority('__rmul__')
  205. def __mul__(self, other) -> Expr:
  206. return Mul(self, other)
  207. @sympify_return([('other', 'Expr')], NotImplemented)
  208. @call_highest_priority('__mul__')
  209. def __rmul__(self, other) -> Expr:
  210. return Mul(other, self)
  211. @sympify_return([('other', 'Expr')], NotImplemented)
  212. @call_highest_priority('__rpow__')
  213. def _pow(self, other):
  214. return Pow(self, other)
  215. def __pow__(self, other, mod=None) -> Expr:
  216. if mod is None:
  217. return self._pow(other)
  218. try:
  219. _self, other, mod = as_int(self), as_int(other), as_int(mod)
  220. if other >= 0:
  221. return _sympify(pow(_self, other, mod))
  222. else:
  223. return _sympify(mod_inverse(pow(_self, -other, mod), mod))
  224. except ValueError:
  225. power = self._pow(other)
  226. try:
  227. return power%mod
  228. except TypeError:
  229. return NotImplemented
  230. @sympify_return([('other', 'Expr')], NotImplemented)
  231. @call_highest_priority('__pow__')
  232. def __rpow__(self, other) -> Expr:
  233. return Pow(other, self)
  234. @sympify_return([('other', 'Expr')], NotImplemented)
  235. @call_highest_priority('__rtruediv__')
  236. def __truediv__(self, other) -> Expr:
  237. denom = Pow(other, S.NegativeOne)
  238. if self is S.One:
  239. return denom
  240. else:
  241. return Mul(self, denom)
  242. @sympify_return([('other', 'Expr')], NotImplemented)
  243. @call_highest_priority('__truediv__')
  244. def __rtruediv__(self, other) -> Expr:
  245. denom = Pow(self, S.NegativeOne)
  246. if other is S.One:
  247. return denom
  248. else:
  249. return Mul(other, denom)
  250. @sympify_return([('other', 'Expr')], NotImplemented)
  251. @call_highest_priority('__rmod__')
  252. def __mod__(self, other) -> Expr:
  253. return Mod(self, other)
  254. @sympify_return([('other', 'Expr')], NotImplemented)
  255. @call_highest_priority('__mod__')
  256. def __rmod__(self, other) -> Expr:
  257. return Mod(other, self)
  258. @sympify_return([('other', 'Expr')], NotImplemented)
  259. @call_highest_priority('__rfloordiv__')
  260. def __floordiv__(self, other) -> Expr:
  261. from sympy.functions.elementary.integers import floor
  262. return floor(self / other)
  263. @sympify_return([('other', 'Expr')], NotImplemented)
  264. @call_highest_priority('__floordiv__')
  265. def __rfloordiv__(self, other) -> Expr:
  266. from sympy.functions.elementary.integers import floor
  267. return floor(other / self)
  268. @sympify_return([('other', 'Expr')], NotImplemented)
  269. @call_highest_priority('__rdivmod__')
  270. def __divmod__(self, other) -> tuple[Expr, Expr]:
  271. from sympy.functions.elementary.integers import floor
  272. return floor(self / other), Mod(self, other)
  273. @sympify_return([('other', 'Expr')], NotImplemented)
  274. @call_highest_priority('__divmod__')
  275. def __rdivmod__(self, other) -> tuple[Expr, Expr]:
  276. from sympy.functions.elementary.integers import floor
  277. return floor(other / self), Mod(other, self)
  278. def __int__(self) -> int:
  279. if not self.is_number:
  280. raise TypeError("Cannot convert symbols to int")
  281. r = self.round(2)
  282. if not r.is_Number:
  283. raise TypeError("Cannot convert complex to int")
  284. if r in (S.NaN, S.Infinity, S.NegativeInfinity):
  285. raise TypeError("Cannot convert %s to int" % r)
  286. i = int(r)
  287. if not i:
  288. return i
  289. if int_valued(r):
  290. # non-integer self should pass one of these tests
  291. if (self > i) is S.true:
  292. return i
  293. if (self < i) is S.true:
  294. return i - 1
  295. ok = self.equals(i)
  296. if ok is None:
  297. raise TypeError('cannot compute int value accurately')
  298. if ok:
  299. return i
  300. # off by one
  301. return i - (1 if i > 0 else -1)
  302. return i
  303. def __float__(self) -> float:
  304. # Don't bother testing if it's a number; if it's not this is going
  305. # to fail, and if it is we still need to check that it evalf'ed to
  306. # a number.
  307. result = self.evalf()
  308. if result.is_Number:
  309. return float(result)
  310. if result.is_number and result.as_real_imag()[1]:
  311. raise TypeError("Cannot convert complex to float")
  312. raise TypeError("Cannot convert expression to float")
  313. def __complex__(self) -> complex:
  314. result = self.evalf()
  315. re, im = result.as_real_imag()
  316. return complex(float(re), float(im))
  317. @sympify_return([('other', 'Expr')], NotImplemented)
  318. def __ge__(self, other):
  319. from .relational import GreaterThan
  320. return GreaterThan(self, other)
  321. @sympify_return([('other', 'Expr')], NotImplemented)
  322. def __le__(self, other):
  323. from .relational import LessThan
  324. return LessThan(self, other)
  325. @sympify_return([('other', 'Expr')], NotImplemented)
  326. def __gt__(self, other):
  327. from .relational import StrictGreaterThan
  328. return StrictGreaterThan(self, other)
  329. @sympify_return([('other', 'Expr')], NotImplemented)
  330. def __lt__(self, other):
  331. from .relational import StrictLessThan
  332. return StrictLessThan(self, other)
  333. def __trunc__(self):
  334. if not self.is_number:
  335. raise TypeError("Cannot truncate symbols and expressions")
  336. else:
  337. return Integer(self)
  338. def __format__(self, format_spec: str):
  339. if self.is_number:
  340. mt = re.match(r'\+?\d*\.(\d+)f', format_spec)
  341. if mt:
  342. prec = int(mt.group(1))
  343. rounded = self.round(prec)
  344. if rounded.is_Integer:
  345. return format(int(rounded), format_spec)
  346. if rounded.is_Float:
  347. return format(rounded, format_spec)
  348. return super().__format__(format_spec)
  349. @staticmethod
  350. def _from_mpmath(x, prec):
  351. if hasattr(x, "_mpf_"):
  352. return Float._new(x._mpf_, prec)
  353. elif hasattr(x, "_mpc_"):
  354. re, im = x._mpc_
  355. re = Float._new(re, prec)
  356. im = Float._new(im, prec)*S.ImaginaryUnit
  357. return re + im
  358. else:
  359. raise TypeError("expected mpmath number (mpf or mpc)")
  360. @property
  361. def is_number(self):
  362. """Returns True if ``self`` has no free symbols and no
  363. undefined functions (AppliedUndef, to be precise). It will be
  364. faster than ``if not self.free_symbols``, however, since
  365. ``is_number`` will fail as soon as it hits a free symbol
  366. or undefined function.
  367. Examples
  368. ========
  369. >>> from sympy import Function, Integral, cos, sin, pi
  370. >>> from sympy.abc import x
  371. >>> f = Function('f')
  372. >>> x.is_number
  373. False
  374. >>> f(1).is_number
  375. False
  376. >>> (2*x).is_number
  377. False
  378. >>> (2 + Integral(2, x)).is_number
  379. False
  380. >>> (2 + Integral(2, (x, 1, 2))).is_number
  381. True
  382. Not all numbers are Numbers in the SymPy sense:
  383. >>> pi.is_number, pi.is_Number
  384. (True, False)
  385. If something is a number it should evaluate to a number with
  386. real and imaginary parts that are Numbers; the result may not
  387. be comparable, however, since the real and/or imaginary part
  388. of the result may not have precision.
  389. >>> cos(1).is_number and cos(1).is_comparable
  390. True
  391. >>> z = cos(1)**2 + sin(1)**2 - 1
  392. >>> z.is_number
  393. True
  394. >>> z.is_comparable
  395. False
  396. See Also
  397. ========
  398. sympy.core.basic.Basic.is_comparable
  399. """
  400. return all(obj.is_number for obj in self.args)
  401. def _eval_is_comparable(self):
  402. # Basic._eval_is_comparable always returns False, so we override it
  403. # here
  404. is_extended_real = self.is_extended_real
  405. if is_extended_real is False:
  406. return False
  407. if not self.is_number:
  408. return False
  409. # XXX: as_real_imag() can be a very expensive operation. It should not
  410. # be used here because is_comparable is used implicitly in many places.
  411. # Probably this method should just return self.evalf(2).is_Number.
  412. n, i = self.as_real_imag()
  413. if not n.is_Number:
  414. n = n.evalf(2)
  415. if not n.is_Number:
  416. return False
  417. if not i.is_Number:
  418. i = i.evalf(2)
  419. if not i.is_Number:
  420. return False
  421. if i:
  422. # if _prec = 1 we can't decide and if not,
  423. # the answer is False because numbers with
  424. # imaginary parts can't be compared
  425. # so return False
  426. return False
  427. else:
  428. return n._prec != 1
  429. def _random(self, n=None, re_min=-1, im_min=-1, re_max=1, im_max=1):
  430. """Return self evaluated, if possible, replacing free symbols with
  431. random complex values, if necessary.
  432. Explanation
  433. ===========
  434. The random complex value for each free symbol is generated
  435. by the random_complex_number routine giving real and imaginary
  436. parts in the range given by the re_min, re_max, im_min, and im_max
  437. values. The returned value is evaluated to a precision of n
  438. (if given) else the maximum of 15 and the precision needed
  439. to get more than 1 digit of precision. If the expression
  440. could not be evaluated to a number, or could not be evaluated
  441. to more than 1 digit of precision, then None is returned.
  442. Examples
  443. ========
  444. >>> from sympy import sqrt
  445. >>> from sympy.abc import x, y
  446. >>> x._random() # doctest: +SKIP
  447. 0.0392918155679172 + 0.916050214307199*I
  448. >>> x._random(2) # doctest: +SKIP
  449. -0.77 - 0.87*I
  450. >>> (x + y/2)._random(2) # doctest: +SKIP
  451. -0.57 + 0.16*I
  452. >>> sqrt(2)._random(2)
  453. 1.4
  454. See Also
  455. ========
  456. sympy.core.random.random_complex_number
  457. """
  458. free = self.free_symbols
  459. prec = 1
  460. if free:
  461. from sympy.core.random import random_complex_number
  462. a, c, b, d = re_min, re_max, im_min, im_max
  463. reps = dict(list(zip(free, [random_complex_number(a, b, c, d, rational=True)
  464. for zi in free])))
  465. try:
  466. nmag = abs(self.evalf(2, subs=reps))
  467. except (ValueError, TypeError):
  468. # if an out of range value resulted in evalf problems
  469. # then return None -- XXX is there a way to know how to
  470. # select a good random number for a given expression?
  471. # e.g. when calculating n! negative values for n should not
  472. # be used
  473. return None
  474. else:
  475. reps = {}
  476. nmag = abs(self.evalf(2))
  477. if not hasattr(nmag, '_prec'):
  478. # e.g. exp_polar(2*I*pi) doesn't evaluate but is_number is True
  479. return None
  480. if nmag._prec == 1:
  481. # increase the precision up to the default maximum
  482. # precision to see if we can get any significance
  483. # evaluate
  484. for prec in giant_steps(2, DEFAULT_MAXPREC):
  485. nmag = abs(self.evalf(prec, subs=reps))
  486. if nmag._prec != 1:
  487. break
  488. if nmag._prec != 1:
  489. if n is None:
  490. n = max(prec, 15)
  491. return self.evalf(n, subs=reps)
  492. # never got any significance
  493. return None
  494. def is_constant(self, *wrt, **flags):
  495. """Return True if self is constant, False if not, or None if
  496. the constancy could not be determined conclusively.
  497. Explanation
  498. ===========
  499. If an expression has no free symbols then it is a constant. If
  500. there are free symbols it is possible that the expression is a
  501. constant, perhaps (but not necessarily) zero. To test such
  502. expressions, a few strategies are tried:
  503. 1) numerical evaluation at two random points. If two such evaluations
  504. give two different values and the values have a precision greater than
  505. 1 then self is not constant. If the evaluations agree or could not be
  506. obtained with any precision, no decision is made. The numerical testing
  507. is done only if ``wrt`` is different than the free symbols.
  508. 2) differentiation with respect to variables in 'wrt' (or all free
  509. symbols if omitted) to see if the expression is constant or not. This
  510. will not always lead to an expression that is zero even though an
  511. expression is constant (see added test in test_expr.py). If
  512. all derivatives are zero then self is constant with respect to the
  513. given symbols.
  514. 3) finding out zeros of denominator expression with free_symbols.
  515. It will not be constant if there are zeros. It gives more negative
  516. answers for expression that are not constant.
  517. If neither evaluation nor differentiation can prove the expression is
  518. constant, None is returned unless two numerical values happened to be
  519. the same and the flag ``failing_number`` is True -- in that case the
  520. numerical value will be returned.
  521. If flag simplify=False is passed, self will not be simplified;
  522. the default is True since self should be simplified before testing.
  523. Examples
  524. ========
  525. >>> from sympy import cos, sin, Sum, S, pi
  526. >>> from sympy.abc import a, n, x, y
  527. >>> x.is_constant()
  528. False
  529. >>> S(2).is_constant()
  530. True
  531. >>> Sum(x, (x, 1, 10)).is_constant()
  532. True
  533. >>> Sum(x, (x, 1, n)).is_constant()
  534. False
  535. >>> Sum(x, (x, 1, n)).is_constant(y)
  536. True
  537. >>> Sum(x, (x, 1, n)).is_constant(n)
  538. False
  539. >>> Sum(x, (x, 1, n)).is_constant(x)
  540. True
  541. >>> eq = a*cos(x)**2 + a*sin(x)**2 - a
  542. >>> eq.is_constant()
  543. True
  544. >>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
  545. True
  546. >>> (0**x).is_constant()
  547. False
  548. >>> x.is_constant()
  549. False
  550. >>> (x**x).is_constant()
  551. False
  552. >>> one = cos(x)**2 + sin(x)**2
  553. >>> one.is_constant()
  554. True
  555. >>> ((one - 1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1
  556. True
  557. """
  558. simplify = flags.get('simplify', True)
  559. if self.is_number:
  560. return True
  561. free = self.free_symbols
  562. if not free:
  563. return True # assume f(1) is some constant
  564. # if we are only interested in some symbols and they are not in the
  565. # free symbols then this expression is constant wrt those symbols
  566. wrt = set(wrt)
  567. if wrt and not wrt & free:
  568. return True
  569. wrt = wrt or free
  570. # simplify unless this has already been done
  571. expr = self
  572. if simplify:
  573. expr = expr.simplify()
  574. # is_zero should be a quick assumptions check; it can be wrong for
  575. # numbers (see test_is_not_constant test), giving False when it
  576. # shouldn't, but hopefully it will never give True unless it is sure.
  577. if expr.is_zero:
  578. return True
  579. # Don't attempt substitution or differentiation with non-number symbols
  580. wrt_number = {sym for sym in wrt if sym.kind is NumberKind}
  581. # try numerical evaluation to see if we get two different values
  582. failing_number = None
  583. if wrt_number == free:
  584. # try 0 (for a) and 1 (for b)
  585. try:
  586. a = expr.subs(list(zip(free, [0]*len(free))),
  587. simultaneous=True)
  588. if a is S.NaN:
  589. # evaluation may succeed when substitution fails
  590. a = expr._random(None, 0, 0, 0, 0)
  591. except ZeroDivisionError:
  592. a = None
  593. if a is not None and a is not S.NaN:
  594. try:
  595. b = expr.subs(list(zip(free, [1]*len(free))),
  596. simultaneous=True)
  597. if b is S.NaN:
  598. # evaluation may succeed when substitution fails
  599. b = expr._random(None, 1, 0, 1, 0)
  600. except ZeroDivisionError:
  601. b = None
  602. if b is not None and b is not S.NaN and b.equals(a) is False:
  603. return False
  604. # try random real
  605. b = expr._random(None, -1, 0, 1, 0)
  606. if b is not None and b is not S.NaN and b.equals(a) is False:
  607. return False
  608. # try random complex
  609. b = expr._random()
  610. if b is not None and b is not S.NaN:
  611. if b.equals(a) is False:
  612. return False
  613. failing_number = a if a.is_number else b
  614. # now we will test each wrt symbol (or all free symbols) to see if the
  615. # expression depends on them or not using differentiation. This is
  616. # not sufficient for all expressions, however, so we don't return
  617. # False if we get a derivative other than 0 with free symbols.
  618. for w in wrt_number:
  619. deriv = expr.diff(w)
  620. if simplify:
  621. deriv = deriv.simplify()
  622. if deriv != 0:
  623. if not (pure_complex(deriv, or_real=True)):
  624. if flags.get('failing_number', False):
  625. return failing_number
  626. return False
  627. from sympy.solvers.solvers import denoms
  628. return fuzzy_not(fuzzy_or(den.is_zero for den in denoms(self)))
  629. def equals(self, other, failing_expression=False):
  630. """Return True if self == other, False if it does not, or None. If
  631. failing_expression is True then the expression which did not simplify
  632. to a 0 will be returned instead of None.
  633. Explanation
  634. ===========
  635. If ``self`` is a Number (or complex number) that is not zero, then
  636. the result is False.
  637. If ``self`` is a number and has not evaluated to zero, evalf will be
  638. used to test whether the expression evaluates to zero. If it does so
  639. and the result has significance (i.e. the precision is either -1, for
  640. a Rational result, or is greater than 1) then the evalf value will be
  641. used to return True or False.
  642. """
  643. from sympy.simplify.simplify import nsimplify, simplify
  644. from sympy.solvers.solvers import solve
  645. from sympy.polys.polyerrors import NotAlgebraic
  646. from sympy.polys.numberfields import minimal_polynomial
  647. other = sympify(other)
  648. if not isinstance(other, Expr):
  649. return False
  650. if self == other:
  651. return True
  652. # they aren't the same so see if we can make the difference 0;
  653. # don't worry about doing simplification steps one at a time
  654. # because if the expression ever goes to 0 then the subsequent
  655. # simplification steps that are done will be very fast.
  656. diff = factor_terms(simplify(self - other), radical=True)
  657. if not diff:
  658. return True
  659. if not diff.has(Add, Mod):
  660. # if there is no expanding to be done after simplifying
  661. # then this can't be a zero
  662. return False
  663. factors = diff.as_coeff_mul()[1]
  664. if len(factors) > 1: # avoid infinity recursion
  665. fac_zero = [fac.equals(0) for fac in factors]
  666. if None not in fac_zero: # every part can be decided
  667. return any(fac_zero)
  668. constant = diff.is_constant(simplify=False, failing_number=True)
  669. if constant is False:
  670. return False
  671. if not diff.is_number:
  672. if constant is None:
  673. # e.g. unless the right simplification is done, a symbolic
  674. # zero is possible (see expression of issue 6829: without
  675. # simplification constant will be None).
  676. return
  677. if constant is True:
  678. # this gives a number whether there are free symbols or not
  679. ndiff = diff._random()
  680. # is_comparable will work whether the result is real
  681. # or complex; it could be None, however.
  682. if ndiff and ndiff.is_comparable:
  683. return False
  684. # sometimes we can use a simplified result to give a clue as to
  685. # what the expression should be; if the expression is *not* zero
  686. # then we should have been able to compute that and so now
  687. # we can just consider the cases where the approximation appears
  688. # to be zero -- we try to prove it via minimal_polynomial.
  689. #
  690. # removed
  691. # ns = nsimplify(diff)
  692. # if diff.is_number and (not ns or ns == diff):
  693. #
  694. # The thought was that if it nsimplifies to 0 that's a sure sign
  695. # to try the following to prove it; or if it changed but wasn't
  696. # zero that might be a sign that it's not going to be easy to
  697. # prove. But tests seem to be working without that logic.
  698. #
  699. if diff.is_number:
  700. # try to prove via self-consistency
  701. surds = [s for s in diff.atoms(Pow) if s.args[0].is_Integer]
  702. # it seems to work better to try big ones first
  703. surds.sort(key=lambda x: -x.args[0])
  704. for s in surds:
  705. try:
  706. # simplify is False here -- this expression has already
  707. # been identified as being hard to identify as zero;
  708. # we will handle the checking ourselves using nsimplify
  709. # to see if we are in the right ballpark or not and if so
  710. # *then* the simplification will be attempted.
  711. sol = solve(diff, s, simplify=False)
  712. if sol:
  713. if s in sol:
  714. # the self-consistent result is present
  715. return True
  716. if all(si.is_Integer for si in sol):
  717. # perfect powers are removed at instantiation
  718. # so surd s cannot be an integer
  719. return False
  720. if all(i.is_algebraic is False for i in sol):
  721. # a surd is algebraic
  722. return False
  723. if any(si in surds for si in sol):
  724. # it wasn't equal to s but it is in surds
  725. # and different surds are not equal
  726. return False
  727. if any(nsimplify(s - si) == 0 and
  728. simplify(s - si) == 0 for si in sol):
  729. return True
  730. if s.is_real:
  731. if any(nsimplify(si, [s]) == s and simplify(si) == s
  732. for si in sol):
  733. return True
  734. except NotImplementedError:
  735. pass
  736. # try to prove with minimal_polynomial but know when
  737. # *not* to use this or else it can take a long time. e.g. issue 8354
  738. if True: # change True to condition that assures non-hang
  739. try:
  740. mp = minimal_polynomial(diff)
  741. if mp.is_Symbol:
  742. return True
  743. return False
  744. except (NotAlgebraic, NotImplementedError):
  745. pass
  746. # diff has not simplified to zero; constant is either None, True
  747. # or the number with significance (is_comparable) that was randomly
  748. # calculated twice as the same value.
  749. if constant not in (True, None) and constant != 0:
  750. return False
  751. if failing_expression:
  752. return diff
  753. return None
  754. def _eval_is_extended_positive_negative(self, positive):
  755. from sympy.polys.numberfields import minimal_polynomial
  756. from sympy.polys.polyerrors import NotAlgebraic
  757. if self.is_number:
  758. # check to see that we can get a value
  759. try:
  760. n2 = self._eval_evalf(2)
  761. # XXX: This shouldn't be caught here
  762. # Catches ValueError: hypsum() failed to converge to the requested
  763. # 34 bits of accuracy
  764. except ValueError:
  765. return None
  766. if n2 is None:
  767. return None
  768. if getattr(n2, '_prec', 1) == 1: # no significance
  769. return None
  770. if n2 is S.NaN:
  771. return None
  772. f = self.evalf(2)
  773. if f.is_Float:
  774. match = f, S.Zero
  775. else:
  776. match = pure_complex(f)
  777. if match is None:
  778. return False
  779. r, i = match
  780. if not (i.is_Number and r.is_Number):
  781. return False
  782. if r._prec != 1 and i._prec != 1:
  783. return bool(not i and ((r > 0) if positive else (r < 0)))
  784. elif r._prec == 1 and (not i or i._prec == 1) and \
  785. self._eval_is_algebraic() and not self.has(Function):
  786. try:
  787. if minimal_polynomial(self).is_Symbol:
  788. return False
  789. except (NotAlgebraic, NotImplementedError):
  790. pass
  791. def _eval_is_extended_positive(self):
  792. return self._eval_is_extended_positive_negative(positive=True)
  793. def _eval_is_extended_negative(self):
  794. return self._eval_is_extended_positive_negative(positive=False)
  795. def _eval_interval(self, x, a, b):
  796. """
  797. Returns evaluation over an interval. For most functions this is:
  798. self.subs(x, b) - self.subs(x, a),
  799. possibly using limit() if NaN is returned from subs, or if
  800. singularities are found between a and b.
  801. If b or a is None, it only evaluates -self.subs(x, a) or self.subs(b, x),
  802. respectively.
  803. """
  804. from sympy.calculus.accumulationbounds import AccumBounds
  805. from sympy.functions.elementary.exponential import log
  806. from sympy.series.limits import limit, Limit
  807. from sympy.sets.sets import Interval
  808. from sympy.solvers.solveset import solveset
  809. if (a is None and b is None):
  810. raise ValueError('Both interval ends cannot be None.')
  811. def _eval_endpoint(left):
  812. c = a if left else b
  813. if c is None:
  814. return S.Zero
  815. else:
  816. C = self.subs(x, c)
  817. if C.has(S.NaN, S.Infinity, S.NegativeInfinity,
  818. S.ComplexInfinity, AccumBounds):
  819. if (a < b) != False:
  820. C = limit(self, x, c, "+" if left else "-")
  821. else:
  822. C = limit(self, x, c, "-" if left else "+")
  823. if isinstance(C, Limit):
  824. raise NotImplementedError("Could not compute limit")
  825. return C
  826. if a == b:
  827. return S.Zero
  828. A = _eval_endpoint(left=True)
  829. if A is S.NaN:
  830. return A
  831. B = _eval_endpoint(left=False)
  832. if (a and b) is None:
  833. return B - A
  834. value = B - A
  835. if a.is_comparable and b.is_comparable:
  836. if a < b:
  837. domain = Interval(a, b)
  838. else:
  839. domain = Interval(b, a)
  840. # check the singularities of self within the interval
  841. # if singularities is a ConditionSet (not iterable), catch the exception and pass
  842. singularities = solveset(self.cancel().as_numer_denom()[1], x,
  843. domain=domain)
  844. for logterm in self.atoms(log):
  845. singularities = singularities | solveset(logterm.args[0], x,
  846. domain=domain)
  847. try:
  848. for s in singularities:
  849. if value is S.NaN:
  850. # no need to keep adding, it will stay NaN
  851. break
  852. if not s.is_comparable:
  853. continue
  854. if (a < s) == (s < b) == True:
  855. value += -limit(self, x, s, "+") + limit(self, x, s, "-")
  856. elif (b < s) == (s < a) == True:
  857. value += limit(self, x, s, "+") - limit(self, x, s, "-")
  858. except TypeError:
  859. pass
  860. return value
  861. def _eval_power(self, expt) -> Expr | None:
  862. # subclass to compute self**other for cases when
  863. # other is not NaN, 0, or 1
  864. return None
  865. def _eval_conjugate(self):
  866. if self.is_extended_real:
  867. return self
  868. elif self.is_imaginary:
  869. return -self
  870. def conjugate(self):
  871. """Returns the complex conjugate of 'self'."""
  872. from sympy.functions.elementary.complexes import conjugate as c
  873. return c(self)
  874. def dir(self, x, cdir):
  875. if self.is_zero:
  876. return S.Zero
  877. from sympy.functions.elementary.exponential import log
  878. minexp = S.Zero
  879. arg = self
  880. while arg:
  881. minexp += S.One
  882. arg = arg.diff(x)
  883. coeff = arg.subs(x, 0)
  884. if coeff is S.NaN:
  885. coeff = arg.limit(x, 0)
  886. if coeff is S.ComplexInfinity:
  887. try:
  888. coeff, _ = arg.leadterm(x)
  889. if coeff.has(log(x)):
  890. raise ValueError()
  891. except ValueError:
  892. coeff = arg.limit(x, 0)
  893. if coeff != S.Zero:
  894. break
  895. return coeff*cdir**minexp
  896. def _eval_transpose(self):
  897. from sympy.functions.elementary.complexes import conjugate
  898. if self.is_commutative:
  899. return self
  900. elif self.is_hermitian:
  901. return conjugate(self)
  902. elif self.is_antihermitian:
  903. return -conjugate(self)
  904. def transpose(self):
  905. from sympy.functions.elementary.complexes import transpose
  906. return transpose(self)
  907. def _eval_adjoint(self):
  908. from sympy.functions.elementary.complexes import conjugate, transpose
  909. if self.is_hermitian:
  910. return self
  911. elif self.is_antihermitian:
  912. return -self
  913. obj = self._eval_conjugate()
  914. if obj is not None:
  915. return transpose(obj)
  916. obj = self._eval_transpose()
  917. if obj is not None:
  918. return conjugate(obj)
  919. def adjoint(self):
  920. from sympy.functions.elementary.complexes import adjoint
  921. return adjoint(self)
  922. @classmethod
  923. def _parse_order(cls, order):
  924. """Parse and configure the ordering of terms. """
  925. from sympy.polys.orderings import monomial_key
  926. startswith = getattr(order, "startswith", None)
  927. if startswith is None:
  928. reverse = False
  929. else:
  930. reverse = startswith('rev-')
  931. if reverse:
  932. order = order[4:]
  933. monom_key = monomial_key(order)
  934. def neg(monom):
  935. return tuple([neg(m) if isinstance(m, tuple) else -m for m in monom])
  936. def key(term):
  937. _, ((re, im), monom, ncpart) = term
  938. monom = neg(monom_key(monom))
  939. ncpart = tuple([e.sort_key(order=order) for e in ncpart])
  940. coeff = ((bool(im), im), (re, im))
  941. return monom, ncpart, coeff
  942. return key, reverse
  943. def as_ordered_factors(self, order=None):
  944. """Return list of ordered factors (if Mul) else [self]."""
  945. return [self]
  946. def as_poly(self, *gens, **args):
  947. """Converts ``self`` to a polynomial or returns ``None``.
  948. Explanation
  949. ===========
  950. >>> from sympy import sin
  951. >>> from sympy.abc import x, y
  952. >>> print((x**2 + x*y).as_poly())
  953. Poly(x**2 + x*y, x, y, domain='ZZ')
  954. >>> print((x**2 + x*y).as_poly(x, y))
  955. Poly(x**2 + x*y, x, y, domain='ZZ')
  956. >>> print((x**2 + sin(y)).as_poly(x, y))
  957. None
  958. """
  959. from sympy.polys.polyerrors import PolynomialError, GeneratorsNeeded
  960. from sympy.polys.polytools import Poly
  961. try:
  962. poly = Poly(self, *gens, **args)
  963. if not poly.is_Poly:
  964. return None
  965. else:
  966. return poly
  967. except (PolynomialError, GeneratorsNeeded):
  968. # PolynomialError is caught for e.g. exp(x).as_poly(x)
  969. # GeneratorsNeeded is caught for e.g. S(2).as_poly()
  970. return None
  971. def as_ordered_terms(self, order=None, data=False):
  972. """
  973. Transform an expression to an ordered list of terms.
  974. Examples
  975. ========
  976. >>> from sympy import sin, cos
  977. >>> from sympy.abc import x
  978. >>> (sin(x)**2*cos(x) + sin(x)**2 + 1).as_ordered_terms()
  979. [sin(x)**2*cos(x), sin(x)**2, 1]
  980. """
  981. from .numbers import Number, NumberSymbol
  982. if order is None and self.is_Add:
  983. # Spot the special case of Add(Number, Mul(Number, expr)) with the
  984. # first number positive and the second number negative
  985. key = lambda x:not isinstance(x, (Number, NumberSymbol))
  986. add_args = sorted(Add.make_args(self), key=key)
  987. if (len(add_args) == 2
  988. and isinstance(add_args[0], (Number, NumberSymbol))
  989. and isinstance(add_args[1], Mul)):
  990. mul_args = sorted(Mul.make_args(add_args[1]), key=key)
  991. if (len(mul_args) == 2
  992. and isinstance(mul_args[0], Number)
  993. and add_args[0].is_positive
  994. and mul_args[0].is_negative):
  995. return add_args
  996. key, reverse = self._parse_order(order)
  997. terms, gens = self.as_terms()
  998. if not any(term.is_Order for term, _ in terms):
  999. ordered = sorted(terms, key=key, reverse=reverse)
  1000. else:
  1001. _terms, _order = [], []
  1002. for term, repr in terms:
  1003. if not term.is_Order:
  1004. _terms.append((term, repr))
  1005. else:
  1006. _order.append((term, repr))
  1007. ordered = sorted(_terms, key=key, reverse=True) \
  1008. + sorted(_order, key=key, reverse=True)
  1009. if data:
  1010. return ordered, gens
  1011. else:
  1012. return [term for term, _ in ordered]
  1013. def as_terms(self):
  1014. """Transform an expression to a list of terms. """
  1015. from .exprtools import decompose_power
  1016. gens, terms = set(), []
  1017. for term in Add.make_args(self):
  1018. coeff, _term = term.as_coeff_Mul()
  1019. coeff = complex(coeff)
  1020. cpart, ncpart = {}, []
  1021. if _term is not S.One:
  1022. for factor in Mul.make_args(_term):
  1023. if factor.is_number:
  1024. try:
  1025. coeff *= complex(factor)
  1026. except (TypeError, ValueError):
  1027. pass
  1028. else:
  1029. continue
  1030. if factor.is_commutative:
  1031. base, exp = decompose_power(factor)
  1032. cpart[base] = exp
  1033. gens.add(base)
  1034. else:
  1035. ncpart.append(factor)
  1036. coeff = coeff.real, coeff.imag
  1037. ncpart = tuple(ncpart)
  1038. terms.append((term, (coeff, cpart, ncpart)))
  1039. gens = sorted(gens, key=default_sort_key)
  1040. k, indices = len(gens), {}
  1041. for i, g in enumerate(gens):
  1042. indices[g] = i
  1043. result = []
  1044. for term, (coeff, cpart, ncpart) in terms:
  1045. monom = [0]*k
  1046. for base, exp in cpart.items():
  1047. monom[indices[base]] = exp
  1048. result.append((term, (coeff, tuple(monom), ncpart)))
  1049. return result, gens
  1050. def removeO(self) -> Expr:
  1051. """Removes the additive O(..) symbol if there is one"""
  1052. return self
  1053. def getO(self) -> Expr | None:
  1054. """Returns the additive O(..) symbol if there is one, else None."""
  1055. return None
  1056. def getn(self):
  1057. """
  1058. Returns the order of the expression.
  1059. Explanation
  1060. ===========
  1061. The order is determined either from the O(...) term. If there
  1062. is no O(...) term, it returns None.
  1063. Examples
  1064. ========
  1065. >>> from sympy import O
  1066. >>> from sympy.abc import x
  1067. >>> (1 + x + O(x**2)).getn()
  1068. 2
  1069. >>> (1 + x).getn()
  1070. """
  1071. o = self.getO()
  1072. if o is None:
  1073. return None
  1074. elif o.is_Order:
  1075. o = o.expr
  1076. if o is S.One:
  1077. return S.Zero
  1078. if o.is_Symbol:
  1079. return S.One
  1080. if o.is_Pow:
  1081. return o.args[1]
  1082. if o.is_Mul: # x**n*log(x)**n or x**n/log(x)**n
  1083. for oi in o.args:
  1084. if oi.is_Symbol:
  1085. return S.One
  1086. if oi.is_Pow:
  1087. from .symbol import Dummy, Symbol
  1088. syms = oi.atoms(Symbol)
  1089. if len(syms) == 1:
  1090. x = syms.pop()
  1091. oi = oi.subs(x, Dummy('x', positive=True))
  1092. if oi.base.is_Symbol and oi.exp.is_Rational:
  1093. return abs(oi.exp)
  1094. raise NotImplementedError('not sure of order of %s' % o)
  1095. def count_ops(self, visual=False):
  1096. from .function import count_ops
  1097. return count_ops(self, visual)
  1098. def args_cnc(self, cset=False, warn=True, split_1=True):
  1099. """Return [commutative factors, non-commutative factors] of self.
  1100. Explanation
  1101. ===========
  1102. self is treated as a Mul and the ordering of the factors is maintained.
  1103. If ``cset`` is True the commutative factors will be returned in a set.
  1104. If there were repeated factors (as may happen with an unevaluated Mul)
  1105. then an error will be raised unless it is explicitly suppressed by
  1106. setting ``warn`` to False.
  1107. Note: -1 is always separated from a Number unless split_1 is False.
  1108. Examples
  1109. ========
  1110. >>> from sympy import symbols, oo
  1111. >>> A, B = symbols('A B', commutative=0)
  1112. >>> x, y = symbols('x y')
  1113. >>> (-2*x*y).args_cnc()
  1114. [[-1, 2, x, y], []]
  1115. >>> (-2.5*x).args_cnc()
  1116. [[-1, 2.5, x], []]
  1117. >>> (-2*x*A*B*y).args_cnc()
  1118. [[-1, 2, x, y], [A, B]]
  1119. >>> (-2*x*A*B*y).args_cnc(split_1=False)
  1120. [[-2, x, y], [A, B]]
  1121. >>> (-2*x*y).args_cnc(cset=True)
  1122. [{-1, 2, x, y}, []]
  1123. The arg is always treated as a Mul:
  1124. >>> (-2 + x + A).args_cnc()
  1125. [[], [x - 2 + A]]
  1126. >>> (-oo).args_cnc() # -oo is a singleton
  1127. [[-1, oo], []]
  1128. """
  1129. args = list(Mul.make_args(self))
  1130. for i, mi in enumerate(args):
  1131. if not mi.is_commutative:
  1132. c = args[:i]
  1133. nc = args[i:]
  1134. break
  1135. else:
  1136. c = args
  1137. nc = []
  1138. if c and split_1 and (
  1139. c[0].is_Number and
  1140. c[0].is_extended_negative and
  1141. c[0] is not S.NegativeOne):
  1142. c[:1] = [S.NegativeOne, -c[0]]
  1143. if cset:
  1144. clen = len(c)
  1145. c = set(c)
  1146. if clen and warn and len(c) != clen:
  1147. raise ValueError('repeated commutative arguments: %s' %
  1148. [ci for ci in c if list(self.args).count(ci) > 1])
  1149. return [c, nc]
  1150. def coeff(self, x: Expr, n=1, right=False, _first=True):
  1151. """
  1152. Returns the coefficient from the term(s) containing ``x**n``. If ``n``
  1153. is zero then all terms independent of ``x`` will be returned.
  1154. Explanation
  1155. ===========
  1156. When ``x`` is noncommutative, the coefficient to the left (default) or
  1157. right of ``x`` can be returned. The keyword 'right' is ignored when
  1158. ``x`` is commutative.
  1159. Examples
  1160. ========
  1161. >>> from sympy import symbols
  1162. >>> from sympy.abc import x, y, z
  1163. You can select terms that have an explicit negative in front of them:
  1164. >>> (-x + 2*y).coeff(-1)
  1165. x
  1166. >>> (x - 2*y).coeff(-1)
  1167. 2*y
  1168. You can select terms with no Rational coefficient:
  1169. >>> (x + 2*y).coeff(1)
  1170. x
  1171. >>> (3 + 2*x + 4*x**2).coeff(1)
  1172. 0
  1173. You can select terms independent of x by making n=0; in this case
  1174. expr.as_independent(x)[0] is returned (and 0 will be returned instead
  1175. of None):
  1176. >>> (3 + 2*x + 4*x**2).coeff(x, 0)
  1177. 3
  1178. >>> eq = ((x + 1)**3).expand() + 1
  1179. >>> eq
  1180. x**3 + 3*x**2 + 3*x + 2
  1181. >>> [eq.coeff(x, i) for i in reversed(range(4))]
  1182. [1, 3, 3, 2]
  1183. >>> eq -= 2
  1184. >>> [eq.coeff(x, i) for i in reversed(range(4))]
  1185. [1, 3, 3, 0]
  1186. You can select terms that have a numerical term in front of them:
  1187. >>> (-x - 2*y).coeff(2)
  1188. -y
  1189. >>> from sympy import sqrt
  1190. >>> (x + sqrt(2)*x).coeff(sqrt(2))
  1191. x
  1192. The matching is exact:
  1193. >>> (3 + 2*x + 4*x**2).coeff(x)
  1194. 2
  1195. >>> (3 + 2*x + 4*x**2).coeff(x**2)
  1196. 4
  1197. >>> (3 + 2*x + 4*x**2).coeff(x**3)
  1198. 0
  1199. >>> (z*(x + y)**2).coeff((x + y)**2)
  1200. z
  1201. >>> (z*(x + y)**2).coeff(x + y)
  1202. 0
  1203. In addition, no factoring is done, so 1 + z*(1 + y) is not obtained
  1204. from the following:
  1205. >>> (x + z*(x + x*y)).coeff(x)
  1206. 1
  1207. If such factoring is desired, factor_terms can be used first:
  1208. >>> from sympy import factor_terms
  1209. >>> factor_terms(x + z*(x + x*y)).coeff(x)
  1210. z*(y + 1) + 1
  1211. >>> n, m, o = symbols('n m o', commutative=False)
  1212. >>> n.coeff(n)
  1213. 1
  1214. >>> (3*n).coeff(n)
  1215. 3
  1216. >>> (n*m + m*n*m).coeff(n) # = (1 + m)*n*m
  1217. 1 + m
  1218. >>> (n*m + m*n*m).coeff(n, right=True) # = (1 + m)*n*m
  1219. m
  1220. If there is more than one possible coefficient 0 is returned:
  1221. >>> (n*m + m*n).coeff(n)
  1222. 0
  1223. If there is only one possible coefficient, it is returned:
  1224. >>> (n*m + x*m*n).coeff(m*n)
  1225. x
  1226. >>> (n*m + x*m*n).coeff(m*n, right=1)
  1227. 1
  1228. See Also
  1229. ========
  1230. as_coefficient: separate the expression into a coefficient and factor
  1231. as_coeff_Add: separate the additive constant from an expression
  1232. as_coeff_Mul: separate the multiplicative constant from an expression
  1233. as_independent: separate x-dependent terms/factors from others
  1234. sympy.polys.polytools.Poly.coeff_monomial: efficiently find the single coefficient of a monomial in Poly
  1235. sympy.polys.polytools.Poly.nth: like coeff_monomial but powers of monomial terms are used
  1236. """
  1237. x = sympify(x)
  1238. if not isinstance(x, Basic):
  1239. return S.Zero
  1240. n = as_int(n)
  1241. if not x:
  1242. return S.Zero
  1243. if x == self:
  1244. if n == 1:
  1245. return S.One
  1246. return S.Zero
  1247. co2: list[Expr]
  1248. if x is S.One:
  1249. co2 = [a for a in Add.make_args(self) if a.as_coeff_Mul()[0] is S.One]
  1250. if not co2:
  1251. return S.Zero
  1252. return Add(*co2)
  1253. if n == 0:
  1254. if x.is_Add and self.is_Add:
  1255. c = self.coeff(x, right=right)
  1256. if not c:
  1257. return S.Zero
  1258. if not right:
  1259. return self - Add(*[a*x for a in Add.make_args(c)])
  1260. return self - Add(*[x*a for a in Add.make_args(c)])
  1261. return self.as_independent(x, as_Add=True)[0]
  1262. # continue with the full method, looking for this power of x:
  1263. x = x**n
  1264. def incommon(l1, l2):
  1265. if not l1 or not l2:
  1266. return []
  1267. n = min(len(l1), len(l2))
  1268. for i in range(n):
  1269. if l1[i] != l2[i]:
  1270. return l1[:i]
  1271. return l1[:]
  1272. def find(l, sub, first=True):
  1273. """ Find where list sub appears in list l. When ``first`` is True
  1274. the first occurrence from the left is returned, else the last
  1275. occurrence is returned. Return None if sub is not in l.
  1276. Examples
  1277. ========
  1278. >> l = range(5)*2
  1279. >> find(l, [2, 3])
  1280. 2
  1281. >> find(l, [2, 3], first=0)
  1282. 7
  1283. >> find(l, [2, 4])
  1284. None
  1285. """
  1286. if not sub or not l or len(sub) > len(l):
  1287. return None
  1288. n = len(sub)
  1289. if not first:
  1290. l.reverse()
  1291. sub.reverse()
  1292. for i in range(len(l) - n + 1):
  1293. if all(l[i + j] == sub[j] for j in range(n)):
  1294. break
  1295. else:
  1296. i = None
  1297. if not first:
  1298. l.reverse()
  1299. sub.reverse()
  1300. if i is not None and not first:
  1301. i = len(l) - (i + n)
  1302. return i
  1303. co2 = []
  1304. co: list[tuple[set[Expr], list[Expr]]] = []
  1305. args = Add.make_args(self)
  1306. self_c = self.is_commutative
  1307. x_c = x.is_commutative
  1308. if self_c and not x_c:
  1309. return S.Zero
  1310. if _first and self.is_Add and not self_c and not x_c:
  1311. # get the part that depends on x exactly
  1312. xargs = Mul.make_args(x)
  1313. d = Add(*[i for i in Add.make_args(self.as_independent(x)[1])
  1314. if all(xi in Mul.make_args(i) for xi in xargs)])
  1315. rv = d.coeff(x, right=right, _first=False)
  1316. if not rv.is_Add or not right:
  1317. return rv
  1318. c_part, nc_part = zip(*[i.args_cnc() for i in rv.args])
  1319. if has_variety(c_part):
  1320. return rv
  1321. return Add(*[Mul._from_args(i) for i in nc_part])
  1322. one_c = self_c or x_c
  1323. xargs, nx = x.args_cnc(cset=True, warn=bool(not x_c))
  1324. # find the parts that pass the commutative terms
  1325. for a in args:
  1326. margs, nc = a.args_cnc(cset=True, warn=bool(not self_c))
  1327. if nc is None:
  1328. nc = []
  1329. if len(xargs) > len(margs):
  1330. continue
  1331. resid = margs.difference(xargs)
  1332. if len(resid) + len(xargs) == len(margs):
  1333. if one_c:
  1334. co2.append(Mul(*(list(resid) + nc)))
  1335. else:
  1336. co.append((resid, nc))
  1337. if one_c:
  1338. if co2 == []:
  1339. return S.Zero
  1340. elif co2:
  1341. return Add(*co2)
  1342. else: # both nc
  1343. # now check the non-comm parts
  1344. if not co:
  1345. return S.Zero
  1346. if all(n == co[0][1] for r, n in co):
  1347. ii = find(co[0][1], nx, right)
  1348. if ii is not None:
  1349. if not right:
  1350. return Mul(Add(*[Mul(*r) for r, c in co]), Mul(*co[0][1][:ii]))
  1351. else:
  1352. return Mul(*co[0][1][ii + len(nx):])
  1353. beg = reduce(incommon, (n[1] for n in co))
  1354. if beg:
  1355. ii = find(beg, nx, right)
  1356. if ii is not None:
  1357. if not right:
  1358. gcdc = co[0][0]
  1359. for i in range(1, len(co)):
  1360. gcdc = gcdc.intersection(co[i][0])
  1361. if not gcdc:
  1362. break
  1363. return Mul(*(list(gcdc) + beg[:ii]))
  1364. else:
  1365. m = ii + len(nx)
  1366. return Add(*[Mul(*(list(r) + n[m:])) for r, n in co])
  1367. end = list(reversed(
  1368. reduce(incommon, (list(reversed(n[1])) for n in co))))
  1369. if end:
  1370. ii = find(end, nx, right)
  1371. if ii is not None:
  1372. if not right:
  1373. return Add(*[Mul(*(list(r) + n[:-len(end) + ii])) for r, n in co])
  1374. else:
  1375. return Mul(*end[ii + len(nx):])
  1376. # look for single match
  1377. hit = None
  1378. for i, (r, n) in enumerate(co):
  1379. ii = find(n, nx, right)
  1380. if ii is not None:
  1381. if not hit:
  1382. hit = ii, r, n
  1383. else:
  1384. break
  1385. else:
  1386. if hit:
  1387. ii, r, n = hit
  1388. if not right:
  1389. return Mul(*(list(r) + n[:ii]))
  1390. else:
  1391. return Mul(*n[ii + len(nx):])
  1392. return S.Zero
  1393. def as_expr(self, *gens):
  1394. """
  1395. Convert a polynomial to a SymPy expression.
  1396. Examples
  1397. ========
  1398. >>> from sympy import sin
  1399. >>> from sympy.abc import x, y
  1400. >>> f = (x**2 + x*y).as_poly(x, y)
  1401. >>> f.as_expr()
  1402. x**2 + x*y
  1403. >>> sin(x).as_expr()
  1404. sin(x)
  1405. """
  1406. return self
  1407. def as_coefficient(self, expr: Expr) -> Expr | None:
  1408. """
  1409. Extracts symbolic coefficient at the given expression. In
  1410. other words, this functions separates 'self' into the product
  1411. of 'expr' and 'expr'-free coefficient. If such separation
  1412. is not possible it will return None.
  1413. Examples
  1414. ========
  1415. >>> from sympy import E, pi, sin, I, Poly
  1416. >>> from sympy.abc import x
  1417. >>> E.as_coefficient(E)
  1418. 1
  1419. >>> (2*E).as_coefficient(E)
  1420. 2
  1421. >>> (2*sin(E)*E).as_coefficient(E)
  1422. Two terms have E in them so a sum is returned. (If one were
  1423. desiring the coefficient of the term exactly matching E then
  1424. the constant from the returned expression could be selected.
  1425. Or, for greater precision, a method of Poly can be used to
  1426. indicate the desired term from which the coefficient is
  1427. desired.)
  1428. >>> (2*E + x*E).as_coefficient(E)
  1429. x + 2
  1430. >>> _.args[0] # just want the exact match
  1431. 2
  1432. >>> p = Poly(2*E + x*E); p
  1433. Poly(x*E + 2*E, x, E, domain='ZZ')
  1434. >>> p.coeff_monomial(E)
  1435. 2
  1436. >>> p.nth(0, 1)
  1437. 2
  1438. Since the following cannot be written as a product containing
  1439. E as a factor, None is returned. (If the coefficient ``2*x`` is
  1440. desired then the ``coeff`` method should be used.)
  1441. >>> (2*E*x + x).as_coefficient(E)
  1442. >>> (2*E*x + x).coeff(E)
  1443. 2*x
  1444. >>> (E*(x + 1) + x).as_coefficient(E)
  1445. >>> (2*pi*I).as_coefficient(pi*I)
  1446. 2
  1447. >>> (2*I).as_coefficient(pi*I)
  1448. See Also
  1449. ========
  1450. coeff: return sum of terms have a given factor
  1451. as_coeff_Add: separate the additive constant from an expression
  1452. as_coeff_Mul: separate the multiplicative constant from an expression
  1453. as_independent: separate x-dependent terms/factors from others
  1454. sympy.polys.polytools.Poly.coeff_monomial: efficiently find the single coefficient of a monomial in Poly
  1455. sympy.polys.polytools.Poly.nth: like coeff_monomial but powers of monomial terms are used
  1456. """
  1457. r = self.extract_multiplicatively(expr)
  1458. if r and not r.has(expr):
  1459. return r
  1460. else:
  1461. return None
  1462. def as_independent(self, *deps, **hint) -> tuple[Expr, Expr]:
  1463. """
  1464. A mostly naive separation of a Mul or Add into arguments that are not
  1465. are dependent on deps. To obtain as complete a separation of variables
  1466. as possible, use a separation method first, e.g.:
  1467. * separatevars() to change Mul, Add and Pow (including exp) into Mul
  1468. * .expand(mul=True) to change Add or Mul into Add
  1469. * .expand(log=True) to change log expr into an Add
  1470. The only non-naive thing that is done here is to respect noncommutative
  1471. ordering of variables and to always return (0, 0) for `self` of zero
  1472. regardless of hints.
  1473. For nonzero `self`, the returned tuple (i, d) has the
  1474. following interpretation:
  1475. * i will has no variable that appears in deps
  1476. * d will either have terms that contain variables that are in deps, or
  1477. be equal to 0 (when self is an Add) or 1 (when self is a Mul)
  1478. * if self is an Add then self = i + d
  1479. * if self is a Mul then self = i*d
  1480. * otherwise (self, S.One) or (S.One, self) is returned.
  1481. To force the expression to be treated as an Add, use the hint as_Add=True
  1482. Examples
  1483. ========
  1484. -- self is an Add
  1485. >>> from sympy import sin, cos, exp
  1486. >>> from sympy.abc import x, y, z
  1487. >>> (x + x*y).as_independent(x)
  1488. (0, x*y + x)
  1489. >>> (x + x*y).as_independent(y)
  1490. (x, x*y)
  1491. >>> (2*x*sin(x) + y + x + z).as_independent(x)
  1492. (y + z, 2*x*sin(x) + x)
  1493. >>> (2*x*sin(x) + y + x + z).as_independent(x, y)
  1494. (z, 2*x*sin(x) + x + y)
  1495. -- self is a Mul
  1496. >>> (x*sin(x)*cos(y)).as_independent(x)
  1497. (cos(y), x*sin(x))
  1498. non-commutative terms cannot always be separated out when self is a Mul
  1499. >>> from sympy import symbols
  1500. >>> n1, n2, n3 = symbols('n1 n2 n3', commutative=False)
  1501. >>> (n1 + n1*n2).as_independent(n2)
  1502. (n1, n1*n2)
  1503. >>> (n2*n1 + n1*n2).as_independent(n2)
  1504. (0, n1*n2 + n2*n1)
  1505. >>> (n1*n2*n3).as_independent(n1)
  1506. (1, n1*n2*n3)
  1507. >>> (n1*n2*n3).as_independent(n2)
  1508. (n1, n2*n3)
  1509. >>> ((x-n1)*(x-y)).as_independent(x)
  1510. (1, (x - y)*(x - n1))
  1511. -- self is anything else:
  1512. >>> (sin(x)).as_independent(x)
  1513. (1, sin(x))
  1514. >>> (sin(x)).as_independent(y)
  1515. (sin(x), 1)
  1516. >>> exp(x+y).as_independent(x)
  1517. (1, exp(x + y))
  1518. -- force self to be treated as an Add:
  1519. >>> (3*x).as_independent(x, as_Add=True)
  1520. (0, 3*x)
  1521. -- force self to be treated as a Mul:
  1522. >>> (3+x).as_independent(x, as_Add=False)
  1523. (1, x + 3)
  1524. >>> (-3+x).as_independent(x, as_Add=False)
  1525. (1, x - 3)
  1526. Note how the below differs from the above in making the
  1527. constant on the dep term positive.
  1528. >>> (y*(-3+x)).as_independent(x)
  1529. (y, x - 3)
  1530. -- use .as_independent() for true independence testing instead
  1531. of .has(). The former considers only symbols in the free
  1532. symbols while the latter considers all symbols
  1533. >>> from sympy import Integral
  1534. >>> I = Integral(x, (x, 1, 2))
  1535. >>> I.has(x)
  1536. True
  1537. >>> x in I.free_symbols
  1538. False
  1539. >>> I.as_independent(x) == (I, 1)
  1540. True
  1541. >>> (I + x).as_independent(x) == (I, x)
  1542. True
  1543. Note: when trying to get independent terms, a separation method
  1544. might need to be used first. In this case, it is important to keep
  1545. track of what you send to this routine so you know how to interpret
  1546. the returned values
  1547. >>> from sympy import separatevars, log
  1548. >>> separatevars(exp(x+y)).as_independent(x)
  1549. (exp(y), exp(x))
  1550. >>> (x + x*y).as_independent(y)
  1551. (x, x*y)
  1552. >>> separatevars(x + x*y).as_independent(y)
  1553. (x, y + 1)
  1554. >>> (x*(1 + y)).as_independent(y)
  1555. (x, y + 1)
  1556. >>> (x*(1 + y)).expand(mul=True).as_independent(y)
  1557. (x, x*y)
  1558. >>> a, b=symbols('a b', positive=True)
  1559. >>> (log(a*b).expand(log=True)).as_independent(b)
  1560. (log(a), log(b))
  1561. See Also
  1562. ========
  1563. separatevars
  1564. expand_log
  1565. sympy.core.add.Add.as_two_terms
  1566. sympy.core.mul.Mul.as_two_terms
  1567. as_coeff_mul
  1568. """
  1569. from .symbol import Symbol
  1570. from .add import _unevaluated_Add
  1571. from .mul import _unevaluated_Mul
  1572. if self is S.Zero:
  1573. return (self, self)
  1574. func = self.func
  1575. want: type[Add] | type[Mul]
  1576. if hint.get('as_Add', isinstance(self, Add) ):
  1577. want = Add
  1578. else:
  1579. want = Mul
  1580. # sift out deps into symbolic and other and ignore
  1581. # all symbols but those that are in the free symbols
  1582. sym = set()
  1583. other = []
  1584. for d in deps:
  1585. if isinstance(d, Symbol): # Symbol.is_Symbol is True
  1586. sym.add(d)
  1587. else:
  1588. other.append(d)
  1589. def has(e):
  1590. """return the standard has() if there are no literal symbols, else
  1591. check to see that symbol-deps are in the free symbols."""
  1592. has_other = e.has(*other)
  1593. if not sym:
  1594. return has_other
  1595. return has_other or e.has(*(e.free_symbols & sym))
  1596. if (want is not func or
  1597. func is not Add and func is not Mul):
  1598. if has(self):
  1599. return (want.identity, self)
  1600. else:
  1601. return (self, want.identity)
  1602. else:
  1603. if func is Add:
  1604. args = list(self.args)
  1605. else:
  1606. args, nc = self.args_cnc()
  1607. d = sift(args, has)
  1608. depend = d[True]
  1609. indep = d[False]
  1610. if func is Add: # all terms were treated as commutative
  1611. return (Add(*indep), _unevaluated_Add(*depend))
  1612. else: # handle noncommutative by stopping at first dependent term
  1613. for i, n in enumerate(nc):
  1614. if has(n):
  1615. depend.extend(nc[i:])
  1616. break
  1617. indep.append(n)
  1618. return Mul(*indep), _unevaluated_Mul(*depend)
  1619. def as_real_imag(self, deep=True, **hints) -> tuple[Expr, Expr]:
  1620. """Performs complex expansion on 'self' and returns a tuple
  1621. containing collected both real and imaginary parts. This
  1622. method cannot be confused with re() and im() functions,
  1623. which does not perform complex expansion at evaluation.
  1624. However it is possible to expand both re() and im()
  1625. functions and get exactly the same results as with
  1626. a single call to this function.
  1627. >>> from sympy import symbols, I
  1628. >>> x, y = symbols('x,y', real=True)
  1629. >>> (x + y*I).as_real_imag()
  1630. (x, y)
  1631. >>> from sympy.abc import z, w
  1632. >>> (z + w*I).as_real_imag()
  1633. (re(z) - im(w), re(w) + im(z))
  1634. """
  1635. if hints.get('ignore') == self:
  1636. return None # type: ignore
  1637. else:
  1638. from sympy.functions.elementary.complexes import im, re
  1639. return (re(self), im(self))
  1640. def as_powers_dict(self):
  1641. """Return self as a dictionary of factors with each factor being
  1642. treated as a power. The keys are the bases of the factors and the
  1643. values, the corresponding exponents. The resulting dictionary should
  1644. be used with caution if the expression is a Mul and contains non-
  1645. commutative factors since the order that they appeared will be lost in
  1646. the dictionary.
  1647. See Also
  1648. ========
  1649. as_ordered_factors: An alternative for noncommutative applications,
  1650. returning an ordered list of factors.
  1651. args_cnc: Similar to as_ordered_factors, but guarantees separation
  1652. of commutative and noncommutative factors.
  1653. """
  1654. d = defaultdict(int)
  1655. d.update([self.as_base_exp()])
  1656. return d
  1657. def as_coefficients_dict(self, *syms):
  1658. """Return a dictionary mapping terms to their Rational coefficient.
  1659. Since the dictionary is a defaultdict, inquiries about terms which
  1660. were not present will return a coefficient of 0.
  1661. If symbols ``syms`` are provided, any multiplicative terms
  1662. independent of them will be considered a coefficient and a
  1663. regular dictionary of syms-dependent generators as keys and
  1664. their corresponding coefficients as values will be returned.
  1665. Examples
  1666. ========
  1667. >>> from sympy.abc import a, x, y
  1668. >>> (3*x + a*x + 4).as_coefficients_dict()
  1669. {1: 4, x: 3, a*x: 1}
  1670. >>> _[a]
  1671. 0
  1672. >>> (3*a*x).as_coefficients_dict()
  1673. {a*x: 3}
  1674. >>> (3*a*x).as_coefficients_dict(x)
  1675. {x: 3*a}
  1676. >>> (3*a*x).as_coefficients_dict(y)
  1677. {1: 3*a*x}
  1678. """
  1679. d = defaultdict(list)
  1680. if not syms:
  1681. for ai in Add.make_args(self):
  1682. c, m = ai.as_coeff_Mul()
  1683. d[m].append(c)
  1684. for k, v in d.items():
  1685. if len(v) == 1:
  1686. d[k] = v[0]
  1687. else:
  1688. d[k] = Add(*v)
  1689. else:
  1690. ind, dep = self.as_independent(*syms, as_Add=True)
  1691. for i in Add.make_args(dep):
  1692. if i.is_Mul:
  1693. c, x = i.as_coeff_mul(*syms)
  1694. if c is S.One:
  1695. d[i].append(c)
  1696. else:
  1697. d[i._new_rawargs(*x)].append(c)
  1698. elif i:
  1699. d[i].append(S.One)
  1700. d = {k: Add(*d[k]) for k in d}
  1701. if ind is not S.Zero:
  1702. d.update({S.One: ind})
  1703. di = defaultdict(int)
  1704. di.update(d)
  1705. return di
  1706. def as_base_exp(self) -> tuple[Expr, Expr]:
  1707. # a -> b ** e
  1708. return self, S.One
  1709. def as_coeff_mul(self, *deps, **kwargs) -> tuple[Expr, tuple[Expr, ...]]:
  1710. """Return the tuple (c, args) where self is written as a Mul, ``m``.
  1711. c should be a Rational multiplied by any factors of the Mul that are
  1712. independent of deps.
  1713. args should be a tuple of all other factors of m; args is empty
  1714. if self is a Number or if self is independent of deps (when given).
  1715. This should be used when you do not know if self is a Mul or not but
  1716. you want to treat self as a Mul or if you want to process the
  1717. individual arguments of the tail of self as a Mul.
  1718. - if you know self is a Mul and want only the head, use self.args[0];
  1719. - if you do not want to process the arguments of the tail but need the
  1720. tail then use self.as_two_terms() which gives the head and tail;
  1721. - if you want to split self into an independent and dependent parts
  1722. use ``self.as_independent(*deps)``
  1723. >>> from sympy import S
  1724. >>> from sympy.abc import x, y
  1725. >>> (S(3)).as_coeff_mul()
  1726. (3, ())
  1727. >>> (3*x*y).as_coeff_mul()
  1728. (3, (x, y))
  1729. >>> (3*x*y).as_coeff_mul(x)
  1730. (3*y, (x,))
  1731. >>> (3*y).as_coeff_mul(x)
  1732. (3*y, ())
  1733. """
  1734. if deps:
  1735. if not self.has(*deps):
  1736. return self, ()
  1737. return S.One, (self,)
  1738. def as_coeff_add(self, *deps) -> tuple[Expr, tuple[Expr, ...]]:
  1739. """Return the tuple (c, args) where self is written as an Add, ``a``.
  1740. c should be a Rational added to any terms of the Add that are
  1741. independent of deps.
  1742. args should be a tuple of all other terms of ``a``; args is empty
  1743. if self is a Number or if self is independent of deps (when given).
  1744. This should be used when you do not know if self is an Add or not but
  1745. you want to treat self as an Add or if you want to process the
  1746. individual arguments of the tail of self as an Add.
  1747. - if you know self is an Add and want only the head, use self.args[0];
  1748. - if you do not want to process the arguments of the tail but need the
  1749. tail then use self.as_two_terms() which gives the head and tail.
  1750. - if you want to split self into an independent and dependent parts
  1751. use ``self.as_independent(*deps)``
  1752. >>> from sympy import S
  1753. >>> from sympy.abc import x, y
  1754. >>> (S(3)).as_coeff_add()
  1755. (3, ())
  1756. >>> (3 + x).as_coeff_add()
  1757. (3, (x,))
  1758. >>> (3 + x + y).as_coeff_add(x)
  1759. (y + 3, (x,))
  1760. >>> (3 + y).as_coeff_add(x)
  1761. (y + 3, ())
  1762. """
  1763. if deps:
  1764. if not self.has_free(*deps):
  1765. return self, ()
  1766. return S.Zero, (self,)
  1767. def primitive(self) -> tuple[Number, Expr]:
  1768. """Return the positive Rational that can be extracted non-recursively
  1769. from every term of self (i.e., self is treated like an Add). This is
  1770. like the as_coeff_Mul() method but primitive always extracts a positive
  1771. Rational (never a negative or a Float).
  1772. Examples
  1773. ========
  1774. >>> from sympy.abc import x
  1775. >>> (3*(x + 1)**2).primitive()
  1776. (3, (x + 1)**2)
  1777. >>> a = (6*x + 2); a.primitive()
  1778. (2, 3*x + 1)
  1779. >>> b = (x/2 + 3); b.primitive()
  1780. (1/2, x + 6)
  1781. >>> (a*b).primitive() == (1, a*b)
  1782. True
  1783. """
  1784. if not self:
  1785. return S.One, S.Zero
  1786. c, r = self.as_coeff_Mul(rational=True)
  1787. if c.is_negative:
  1788. c, r = -c, -r
  1789. return c, r
  1790. def as_content_primitive(self, radical=False, clear=True):
  1791. """This method should recursively remove a Rational from all arguments
  1792. and return that (content) and the new self (primitive). The content
  1793. should always be positive and ``Mul(*foo.as_content_primitive()) == foo``.
  1794. The primitive need not be in canonical form and should try to preserve
  1795. the underlying structure if possible (i.e. expand_mul should not be
  1796. applied to self).
  1797. Examples
  1798. ========
  1799. >>> from sympy import sqrt
  1800. >>> from sympy.abc import x, y, z
  1801. >>> eq = 2 + 2*x + 2*y*(3 + 3*y)
  1802. The as_content_primitive function is recursive and retains structure:
  1803. >>> eq.as_content_primitive()
  1804. (2, x + 3*y*(y + 1) + 1)
  1805. Integer powers will have Rationals extracted from the base:
  1806. >>> ((2 + 6*x)**2).as_content_primitive()
  1807. (4, (3*x + 1)**2)
  1808. >>> ((2 + 6*x)**(2*y)).as_content_primitive()
  1809. (1, (2*(3*x + 1))**(2*y))
  1810. Terms may end up joining once their as_content_primitives are added:
  1811. >>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
  1812. (11, x*(y + 1))
  1813. >>> ((3*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
  1814. (9, x*(y + 1))
  1815. >>> ((3*(z*(1 + y)) + 2.0*x*(3 + 3*y))).as_content_primitive()
  1816. (1, 6.0*x*(y + 1) + 3*z*(y + 1))
  1817. >>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive()
  1818. (121, x**2*(y + 1)**2)
  1819. >>> ((x*(1 + y) + 0.4*x*(3 + 3*y))**2).as_content_primitive()
  1820. (1, 4.84*x**2*(y + 1)**2)
  1821. Radical content can also be factored out of the primitive:
  1822. >>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
  1823. (2, sqrt(2)*(1 + 2*sqrt(5)))
  1824. If clear=False (default is True) then content will not be removed
  1825. from an Add if it can be distributed to leave one or more
  1826. terms with integer coefficients.
  1827. >>> (x/2 + y).as_content_primitive()
  1828. (1/2, x + 2*y)
  1829. >>> (x/2 + y).as_content_primitive(clear=False)
  1830. (1, x/2 + y)
  1831. """
  1832. return S.One, self
  1833. def as_numer_denom(self) -> tuple[Expr, Expr]:
  1834. """Return the numerator and the denominator of an expression.
  1835. expression -> a/b -> a, b
  1836. This is just a stub that should be defined by
  1837. an object's class methods to get anything else.
  1838. See Also
  1839. ========
  1840. normal: return ``a/b`` instead of ``(a, b)``
  1841. """
  1842. return self, S.One
  1843. def normal(self):
  1844. """Return the expression as a fraction.
  1845. expression -> a/b
  1846. See Also
  1847. ========
  1848. as_numer_denom: return ``(a, b)`` instead of ``a/b``
  1849. """
  1850. from .mul import _unevaluated_Mul
  1851. n, d = self.as_numer_denom()
  1852. if d is S.One:
  1853. return n
  1854. if d.is_Number:
  1855. return _unevaluated_Mul(n, 1/d)
  1856. else:
  1857. return n/d
  1858. def extract_multiplicatively(self, c: Expr) -> Expr | None:
  1859. """Return None if it's not possible to make self in the form
  1860. c * something in a nice way, i.e. preserving the properties
  1861. of arguments of self.
  1862. Examples
  1863. ========
  1864. >>> from sympy import symbols, Rational
  1865. >>> x, y = symbols('x,y', real=True)
  1866. >>> ((x*y)**3).extract_multiplicatively(x**2 * y)
  1867. x*y**2
  1868. >>> ((x*y)**3).extract_multiplicatively(x**4 * y)
  1869. >>> (2*x).extract_multiplicatively(2)
  1870. x
  1871. >>> (2*x).extract_multiplicatively(3)
  1872. >>> (Rational(1, 2)*x).extract_multiplicatively(3)
  1873. x/6
  1874. """
  1875. from sympy.functions.elementary.exponential import exp
  1876. from .add import _unevaluated_Add
  1877. c = sympify(c)
  1878. if self is S.NaN:
  1879. return None
  1880. if c is S.One:
  1881. return self
  1882. elif c == self:
  1883. return S.One
  1884. if c.is_Add:
  1885. cc, pc = c.primitive()
  1886. if cc is not S.One:
  1887. c = Mul(cc, pc, evaluate=False)
  1888. if c.is_Mul:
  1889. a, b = c.as_two_terms() # type: ignore
  1890. x = self.extract_multiplicatively(a)
  1891. if x is not None:
  1892. return x.extract_multiplicatively(b)
  1893. else:
  1894. return x
  1895. quotient = self / c
  1896. if self.is_Number:
  1897. if self is S.Infinity:
  1898. if c.is_positive:
  1899. return S.Infinity
  1900. elif self is S.NegativeInfinity:
  1901. if c.is_negative:
  1902. return S.Infinity
  1903. elif c.is_positive:
  1904. return S.NegativeInfinity
  1905. elif self is S.ComplexInfinity:
  1906. if not c.is_zero:
  1907. return S.ComplexInfinity
  1908. elif self.is_Integer:
  1909. if not quotient.is_Integer:
  1910. return None
  1911. elif self.is_positive and quotient.is_negative:
  1912. return None
  1913. else:
  1914. return quotient
  1915. elif self.is_Rational:
  1916. if not quotient.is_Rational:
  1917. return None
  1918. elif self.is_positive and quotient.is_negative:
  1919. return None
  1920. else:
  1921. return quotient
  1922. elif self.is_Float:
  1923. if not quotient.is_Float:
  1924. return None
  1925. elif self.is_positive and quotient.is_negative:
  1926. return None
  1927. else:
  1928. return quotient
  1929. elif self.is_NumberSymbol or self.is_Symbol or self is S.ImaginaryUnit:
  1930. if quotient.is_Mul and len(quotient.args) == 2:
  1931. if quotient.args[0].is_Integer and quotient.args[0].is_positive and quotient.args[1] == self:
  1932. return quotient
  1933. elif quotient.is_Integer and c.is_Number:
  1934. return quotient
  1935. elif self.is_Add:
  1936. cs, ps = self.primitive()
  1937. # assert cs >= 1
  1938. if c.is_Number and c is not S.NegativeOne:
  1939. # assert c != 1 (handled at top)
  1940. if cs is not S.One:
  1941. if c.is_negative:
  1942. xc = cs.extract_multiplicatively(-c)
  1943. if xc is not None:
  1944. xc = -xc
  1945. else:
  1946. xc = cs.extract_multiplicatively(c)
  1947. if xc is not None:
  1948. return xc*ps # rely on 2-arg Mul to restore Add
  1949. return None # |c| != 1 can only be extracted from cs
  1950. if c == ps:
  1951. return cs
  1952. # check args of ps
  1953. newargs = []
  1954. arg: Expr
  1955. for arg in ps.args: # type: ignore
  1956. newarg = arg.extract_multiplicatively(c)
  1957. if newarg is None:
  1958. return None # all or nothing
  1959. newargs.append(newarg)
  1960. if cs is not S.One:
  1961. args = [cs*t for t in newargs]
  1962. # args may be in different order
  1963. return _unevaluated_Add(*args)
  1964. else:
  1965. return Add._from_args(newargs)
  1966. elif self.is_Mul:
  1967. args: list[Expr] = list(self.args) # type: ignore
  1968. for i, arg in enumerate(args):
  1969. newarg = arg.extract_multiplicatively(c)
  1970. if newarg is not None:
  1971. args[i] = newarg
  1972. return Mul(*args)
  1973. elif self.is_Pow or isinstance(self, exp):
  1974. sb, se = self.as_base_exp()
  1975. cb, ce = c.as_base_exp()
  1976. if cb == sb:
  1977. new_exp = se.extract_additively(ce)
  1978. if new_exp is not None:
  1979. return Pow(sb, new_exp)
  1980. elif c == sb:
  1981. new_exp = se.extract_additively(1)
  1982. if new_exp is not None:
  1983. return Pow(sb, new_exp)
  1984. return None
  1985. def extract_additively(self, c):
  1986. """Return self - c if it's possible to subtract c from self and
  1987. make all matching coefficients move towards zero, else return None.
  1988. Examples
  1989. ========
  1990. >>> from sympy.abc import x, y
  1991. >>> e = 2*x + 3
  1992. >>> e.extract_additively(x + 1)
  1993. x + 2
  1994. >>> e.extract_additively(3*x)
  1995. >>> e.extract_additively(4)
  1996. >>> (y*(x + 1)).extract_additively(x + 1)
  1997. >>> ((x + 1)*(x + 2*y + 1) + 3).extract_additively(x + 1)
  1998. (x + 1)*(x + 2*y) + 3
  1999. See Also
  2000. ========
  2001. extract_multiplicatively
  2002. coeff
  2003. as_coefficient
  2004. """
  2005. c = sympify(c)
  2006. if self is S.NaN:
  2007. return None
  2008. if c.is_zero:
  2009. return self
  2010. elif c == self:
  2011. return S.Zero
  2012. elif self == S.Zero:
  2013. return None
  2014. if self.is_Number:
  2015. if not c.is_Number:
  2016. return None
  2017. co = self
  2018. diff = co - c
  2019. # XXX should we match types? i.e should 3 - .1 succeed?
  2020. if (co > 0 and diff >= 0 and diff < co or
  2021. co < 0 and diff <= 0 and diff > co):
  2022. return diff
  2023. return None
  2024. if c.is_Number:
  2025. co, t = self.as_coeff_Add()
  2026. xa = co.extract_additively(c)
  2027. if xa is None:
  2028. return None
  2029. return xa + t
  2030. # handle the args[0].is_Number case separately
  2031. # since we will have trouble looking for the coeff of
  2032. # a number.
  2033. if c.is_Add and c.args[0].is_Number:
  2034. # whole term as a term factor
  2035. co = self.coeff(c)
  2036. xa0 = (co.extract_additively(1) or 0)*c
  2037. if xa0:
  2038. diff = self - co*c
  2039. return (xa0 + (diff.extract_additively(c) or diff)) or None
  2040. # term-wise
  2041. h, t = c.as_coeff_Add()
  2042. sh, st = self.as_coeff_Add()
  2043. xa = sh.extract_additively(h)
  2044. if xa is None:
  2045. return None
  2046. xa2 = st.extract_additively(t)
  2047. if xa2 is None:
  2048. return None
  2049. return xa + xa2
  2050. # whole term as a term factor
  2051. co, diff = _corem(self, c)
  2052. xa0 = (co.extract_additively(1) or 0)*c
  2053. if xa0:
  2054. return (xa0 + (diff.extract_additively(c) or diff)) or None
  2055. # term-wise
  2056. coeffs = []
  2057. for a in Add.make_args(c):
  2058. ac, at = a.as_coeff_Mul()
  2059. co = self.coeff(at)
  2060. if not co:
  2061. return None
  2062. coc, cot = co.as_coeff_Add()
  2063. xa = coc.extract_additively(ac)
  2064. if xa is None:
  2065. return None
  2066. self -= co*at
  2067. coeffs.append((cot + xa)*at)
  2068. coeffs.append(self)
  2069. return Add(*coeffs)
  2070. @property
  2071. def expr_free_symbols(self):
  2072. """
  2073. Like ``free_symbols``, but returns the free symbols only if
  2074. they are contained in an expression node.
  2075. Examples
  2076. ========
  2077. >>> from sympy.abc import x, y
  2078. >>> (x + y).expr_free_symbols # doctest: +SKIP
  2079. {x, y}
  2080. If the expression is contained in a non-expression object, do not return
  2081. the free symbols. Compare:
  2082. >>> from sympy import Tuple
  2083. >>> t = Tuple(x + y)
  2084. >>> t.expr_free_symbols # doctest: +SKIP
  2085. set()
  2086. >>> t.free_symbols
  2087. {x, y}
  2088. """
  2089. sympy_deprecation_warning("""
  2090. The expr_free_symbols property is deprecated. Use free_symbols to get
  2091. the free symbols of an expression.
  2092. """,
  2093. deprecated_since_version="1.9",
  2094. active_deprecations_target="deprecated-expr-free-symbols")
  2095. return {j for i in self.args for j in i.expr_free_symbols}
  2096. def could_extract_minus_sign(self) -> bool:
  2097. """Return True if self has -1 as a leading factor or has
  2098. more literal negative signs than positive signs in a sum,
  2099. otherwise False.
  2100. Examples
  2101. ========
  2102. >>> from sympy.abc import x, y
  2103. >>> e = x - y
  2104. >>> {i.could_extract_minus_sign() for i in (e, -e)}
  2105. {False, True}
  2106. Though the ``y - x`` is considered like ``-(x - y)``, since it
  2107. is in a product without a leading factor of -1, the result is
  2108. false below:
  2109. >>> (x*(y - x)).could_extract_minus_sign()
  2110. False
  2111. To put something in canonical form wrt to sign, use `signsimp`:
  2112. >>> from sympy import signsimp
  2113. >>> signsimp(x*(y - x))
  2114. -x*(x - y)
  2115. >>> _.could_extract_minus_sign()
  2116. True
  2117. """
  2118. return False
  2119. def extract_branch_factor(self, allow_half=False):
  2120. """
  2121. Try to write self as ``exp_polar(2*pi*I*n)*z`` in a nice way.
  2122. Return (z, n).
  2123. >>> from sympy import exp_polar, I, pi
  2124. >>> from sympy.abc import x, y
  2125. >>> exp_polar(I*pi).extract_branch_factor()
  2126. (exp_polar(I*pi), 0)
  2127. >>> exp_polar(2*I*pi).extract_branch_factor()
  2128. (1, 1)
  2129. >>> exp_polar(-pi*I).extract_branch_factor()
  2130. (exp_polar(I*pi), -1)
  2131. >>> exp_polar(3*pi*I + x).extract_branch_factor()
  2132. (exp_polar(x + I*pi), 1)
  2133. >>> (y*exp_polar(-5*pi*I)*exp_polar(3*pi*I + 2*pi*x)).extract_branch_factor()
  2134. (y*exp_polar(2*pi*x), -1)
  2135. >>> exp_polar(-I*pi/2).extract_branch_factor()
  2136. (exp_polar(-I*pi/2), 0)
  2137. If allow_half is True, also extract exp_polar(I*pi):
  2138. >>> exp_polar(I*pi).extract_branch_factor(allow_half=True)
  2139. (1, 1/2)
  2140. >>> exp_polar(2*I*pi).extract_branch_factor(allow_half=True)
  2141. (1, 1)
  2142. >>> exp_polar(3*I*pi).extract_branch_factor(allow_half=True)
  2143. (1, 3/2)
  2144. >>> exp_polar(-I*pi).extract_branch_factor(allow_half=True)
  2145. (1, -1/2)
  2146. """
  2147. from sympy.functions.elementary.exponential import exp_polar
  2148. from sympy.functions.elementary.integers import ceiling
  2149. n = S.Zero
  2150. res = S.One
  2151. args = Mul.make_args(self)
  2152. exps = []
  2153. for arg in args:
  2154. if isinstance(arg, exp_polar):
  2155. exps += [arg.exp]
  2156. else:
  2157. res *= arg
  2158. piimult = S.Zero
  2159. extras = []
  2160. ipi = S.Pi*S.ImaginaryUnit
  2161. while exps:
  2162. exp = exps.pop()
  2163. if exp.is_Add:
  2164. exps += exp.args
  2165. continue
  2166. if exp.is_Mul:
  2167. coeff = exp.as_coefficient(ipi)
  2168. if coeff is not None:
  2169. piimult += coeff
  2170. continue
  2171. extras += [exp]
  2172. if piimult.is_number:
  2173. coeff = piimult
  2174. tail = ()
  2175. else:
  2176. coeff, tail = piimult.as_coeff_add(*piimult.free_symbols)
  2177. # round down to nearest multiple of 2
  2178. branchfact = ceiling(coeff/2 - S.Half)*2
  2179. n += branchfact/2
  2180. c = coeff - branchfact
  2181. if allow_half:
  2182. nc = c.extract_additively(1)
  2183. if nc is not None:
  2184. n += S.Half
  2185. c = nc
  2186. newexp = ipi*Add(*((c, ) + tail)) + Add(*extras)
  2187. if newexp != 0:
  2188. res *= exp_polar(newexp)
  2189. return res, n
  2190. def is_polynomial(self, *syms):
  2191. r"""
  2192. Return True if self is a polynomial in syms and False otherwise.
  2193. This checks if self is an exact polynomial in syms. This function
  2194. returns False for expressions that are "polynomials" with symbolic
  2195. exponents. Thus, you should be able to apply polynomial algorithms to
  2196. expressions for which this returns True, and Poly(expr, \*syms) should
  2197. work if and only if expr.is_polynomial(\*syms) returns True. The
  2198. polynomial does not have to be in expanded form. If no symbols are
  2199. given, all free symbols in the expression will be used.
  2200. This is not part of the assumptions system. You cannot do
  2201. Symbol('z', polynomial=True).
  2202. Examples
  2203. ========
  2204. >>> from sympy import Symbol, Function
  2205. >>> x = Symbol('x')
  2206. >>> ((x**2 + 1)**4).is_polynomial(x)
  2207. True
  2208. >>> ((x**2 + 1)**4).is_polynomial()
  2209. True
  2210. >>> (2**x + 1).is_polynomial(x)
  2211. False
  2212. >>> (2**x + 1).is_polynomial(2**x)
  2213. True
  2214. >>> f = Function('f')
  2215. >>> (f(x) + 1).is_polynomial(x)
  2216. False
  2217. >>> (f(x) + 1).is_polynomial(f(x))
  2218. True
  2219. >>> (1/f(x) + 1).is_polynomial(f(x))
  2220. False
  2221. >>> n = Symbol('n', nonnegative=True, integer=True)
  2222. >>> (x**n + 1).is_polynomial(x)
  2223. False
  2224. This function does not attempt any nontrivial simplifications that may
  2225. result in an expression that does not appear to be a polynomial to
  2226. become one.
  2227. >>> from sympy import sqrt, factor, cancel
  2228. >>> y = Symbol('y', positive=True)
  2229. >>> a = sqrt(y**2 + 2*y + 1)
  2230. >>> a.is_polynomial(y)
  2231. False
  2232. >>> factor(a)
  2233. y + 1
  2234. >>> factor(a).is_polynomial(y)
  2235. True
  2236. >>> b = (y**2 + 2*y + 1)/(y + 1)
  2237. >>> b.is_polynomial(y)
  2238. False
  2239. >>> cancel(b)
  2240. y + 1
  2241. >>> cancel(b).is_polynomial(y)
  2242. True
  2243. See also .is_rational_function()
  2244. """
  2245. if syms:
  2246. syms = set(map(sympify, syms))
  2247. else:
  2248. syms = self.free_symbols
  2249. if not syms:
  2250. return True
  2251. return self._eval_is_polynomial(syms)
  2252. def _eval_is_polynomial(self, syms) -> bool | None:
  2253. if self in syms:
  2254. return True
  2255. if not self.has_free(*syms):
  2256. # constant polynomial
  2257. return True
  2258. # subclasses should return True or False
  2259. return None
  2260. def is_rational_function(self, *syms):
  2261. """
  2262. Test whether function is a ratio of two polynomials in the given
  2263. symbols, syms. When syms is not given, all free symbols will be used.
  2264. The rational function does not have to be in expanded or in any kind of
  2265. canonical form.
  2266. This function returns False for expressions that are "rational
  2267. functions" with symbolic exponents. Thus, you should be able to call
  2268. .as_numer_denom() and apply polynomial algorithms to the result for
  2269. expressions for which this returns True.
  2270. This is not part of the assumptions system. You cannot do
  2271. Symbol('z', rational_function=True).
  2272. Examples
  2273. ========
  2274. >>> from sympy import Symbol, sin
  2275. >>> from sympy.abc import x, y
  2276. >>> (x/y).is_rational_function()
  2277. True
  2278. >>> (x**2).is_rational_function()
  2279. True
  2280. >>> (x/sin(y)).is_rational_function(y)
  2281. False
  2282. >>> n = Symbol('n', integer=True)
  2283. >>> (x**n + 1).is_rational_function(x)
  2284. False
  2285. This function does not attempt any nontrivial simplifications that may
  2286. result in an expression that does not appear to be a rational function
  2287. to become one.
  2288. >>> from sympy import sqrt, factor
  2289. >>> y = Symbol('y', positive=True)
  2290. >>> a = sqrt(y**2 + 2*y + 1)/y
  2291. >>> a.is_rational_function(y)
  2292. False
  2293. >>> factor(a)
  2294. (y + 1)/y
  2295. >>> factor(a).is_rational_function(y)
  2296. True
  2297. See also is_algebraic_expr().
  2298. """
  2299. if syms:
  2300. syms = set(map(sympify, syms))
  2301. else:
  2302. syms = self.free_symbols
  2303. if not syms:
  2304. return self not in _illegal
  2305. return self._eval_is_rational_function(syms)
  2306. def _eval_is_rational_function(self, syms) -> bool | None:
  2307. if self in syms:
  2308. return True
  2309. if not self.has_xfree(syms):
  2310. return True
  2311. # subclasses should return True or False
  2312. return None
  2313. def is_meromorphic(self, x, a):
  2314. """
  2315. This tests whether an expression is meromorphic as
  2316. a function of the given symbol ``x`` at the point ``a``.
  2317. This method is intended as a quick test that will return
  2318. None if no decision can be made without simplification or
  2319. more detailed analysis.
  2320. Examples
  2321. ========
  2322. >>> from sympy import zoo, log, sin, sqrt
  2323. >>> from sympy.abc import x
  2324. >>> f = 1/x**2 + 1 - 2*x**3
  2325. >>> f.is_meromorphic(x, 0)
  2326. True
  2327. >>> f.is_meromorphic(x, 1)
  2328. True
  2329. >>> f.is_meromorphic(x, zoo)
  2330. True
  2331. >>> g = x**log(3)
  2332. >>> g.is_meromorphic(x, 0)
  2333. False
  2334. >>> g.is_meromorphic(x, 1)
  2335. True
  2336. >>> g.is_meromorphic(x, zoo)
  2337. False
  2338. >>> h = sin(1/x)*x**2
  2339. >>> h.is_meromorphic(x, 0)
  2340. False
  2341. >>> h.is_meromorphic(x, 1)
  2342. True
  2343. >>> h.is_meromorphic(x, zoo)
  2344. True
  2345. Multivalued functions are considered meromorphic when their
  2346. branches are meromorphic. Thus most functions are meromorphic
  2347. everywhere except at essential singularities and branch points.
  2348. In particular, they will be meromorphic also on branch cuts
  2349. except at their endpoints.
  2350. >>> log(x).is_meromorphic(x, -1)
  2351. True
  2352. >>> log(x).is_meromorphic(x, 0)
  2353. False
  2354. >>> sqrt(x).is_meromorphic(x, -1)
  2355. True
  2356. >>> sqrt(x).is_meromorphic(x, 0)
  2357. False
  2358. """
  2359. if not x.is_symbol:
  2360. raise TypeError("{} should be of symbol type".format(x))
  2361. a = sympify(a)
  2362. return self._eval_is_meromorphic(x, a)
  2363. def _eval_is_meromorphic(self, x, a) -> bool | None:
  2364. if self == x:
  2365. return True
  2366. if not self.has_free(x):
  2367. return True
  2368. # subclasses should return True or False
  2369. return None
  2370. def is_algebraic_expr(self, *syms):
  2371. """
  2372. This tests whether a given expression is algebraic or not, in the
  2373. given symbols, syms. When syms is not given, all free symbols
  2374. will be used. The rational function does not have to be in expanded
  2375. or in any kind of canonical form.
  2376. This function returns False for expressions that are "algebraic
  2377. expressions" with symbolic exponents. This is a simple extension to the
  2378. is_rational_function, including rational exponentiation.
  2379. Examples
  2380. ========
  2381. >>> from sympy import Symbol, sqrt
  2382. >>> x = Symbol('x', real=True)
  2383. >>> sqrt(1 + x).is_rational_function()
  2384. False
  2385. >>> sqrt(1 + x).is_algebraic_expr()
  2386. True
  2387. This function does not attempt any nontrivial simplifications that may
  2388. result in an expression that does not appear to be an algebraic
  2389. expression to become one.
  2390. >>> from sympy import exp, factor
  2391. >>> a = sqrt(exp(x)**2 + 2*exp(x) + 1)/(exp(x) + 1)
  2392. >>> a.is_algebraic_expr(x)
  2393. False
  2394. >>> factor(a).is_algebraic_expr()
  2395. True
  2396. See Also
  2397. ========
  2398. is_rational_function
  2399. References
  2400. ==========
  2401. .. [1] https://en.wikipedia.org/wiki/Algebraic_expression
  2402. """
  2403. if syms:
  2404. syms = set(map(sympify, syms))
  2405. else:
  2406. syms = self.free_symbols
  2407. if not syms:
  2408. return True
  2409. return self._eval_is_algebraic_expr(syms)
  2410. def _eval_is_algebraic_expr(self, syms) -> bool | None:
  2411. if self in syms:
  2412. return True
  2413. if not self.has_free(*syms):
  2414. return True
  2415. # subclasses should return True or False
  2416. return None
  2417. ###################################################################################
  2418. ##################### SERIES, LEADING TERM, LIMIT, ORDER METHODS ##################
  2419. ###################################################################################
  2420. def series(self, x=None, x0=0, n=6, dir="+", logx=None, cdir=0):
  2421. """
  2422. Series expansion of "self" around ``x = x0`` yielding either terms of
  2423. the series one by one (the lazy series given when n=None), else
  2424. all the terms at once when n != None.
  2425. Returns the series expansion of "self" around the point ``x = x0``
  2426. with respect to ``x`` up to ``O((x - x0)**n, x, x0)`` (default n is 6).
  2427. If ``x=None`` and ``self`` is univariate, the univariate symbol will
  2428. be supplied, otherwise an error will be raised.
  2429. Parameters
  2430. ==========
  2431. expr : Expression
  2432. The expression whose series is to be expanded.
  2433. x : Symbol
  2434. It is the variable of the expression to be calculated.
  2435. x0 : Value
  2436. The value around which ``x`` is calculated. Can be any value
  2437. from ``-oo`` to ``oo``.
  2438. n : Value
  2439. The value used to represent the order in terms of ``x**n``,
  2440. up to which the series is to be expanded.
  2441. dir : String, optional
  2442. The series-expansion can be bi-directional. If ``dir="+"``,
  2443. then (x->x0+). If ``dir="-", then (x->x0-). For infinite
  2444. ``x0`` (``oo`` or ``-oo``), the ``dir`` argument is determined
  2445. from the direction of the infinity (i.e., ``dir="-"`` for
  2446. ``oo``).
  2447. logx : optional
  2448. It is used to replace any log(x) in the returned series with a
  2449. symbolic value rather than evaluating the actual value.
  2450. cdir : optional
  2451. It stands for complex direction, and indicates the direction
  2452. from which the expansion needs to be evaluated.
  2453. Examples
  2454. ========
  2455. >>> from sympy import cos, exp, tan
  2456. >>> from sympy.abc import x, y
  2457. >>> cos(x).series()
  2458. 1 - x**2/2 + x**4/24 + O(x**6)
  2459. >>> cos(x).series(n=4)
  2460. 1 - x**2/2 + O(x**4)
  2461. >>> cos(x).series(x, x0=1, n=2)
  2462. cos(1) - (x - 1)*sin(1) + O((x - 1)**2, (x, 1))
  2463. >>> e = cos(x + exp(y))
  2464. >>> e.series(y, n=2)
  2465. cos(x + 1) - y*sin(x + 1) + O(y**2)
  2466. >>> e.series(x, n=2)
  2467. cos(exp(y)) - x*sin(exp(y)) + O(x**2)
  2468. If ``n=None`` then a generator of the series terms will be returned.
  2469. >>> term=cos(x).series(n=None)
  2470. >>> [next(term) for i in range(2)]
  2471. [1, -x**2/2]
  2472. For ``dir=+`` (default) the series is calculated from the right and
  2473. for ``dir=-`` the series from the left. For smooth functions this
  2474. flag will not alter the results.
  2475. >>> abs(x).series(dir="+")
  2476. x
  2477. >>> abs(x).series(dir="-")
  2478. -x
  2479. >>> f = tan(x)
  2480. >>> f.series(x, 2, 6, "+")
  2481. tan(2) + (1 + tan(2)**2)*(x - 2) + (x - 2)**2*(tan(2)**3 + tan(2)) +
  2482. (x - 2)**3*(1/3 + 4*tan(2)**2/3 + tan(2)**4) + (x - 2)**4*(tan(2)**5 +
  2483. 5*tan(2)**3/3 + 2*tan(2)/3) + (x - 2)**5*(2/15 + 17*tan(2)**2/15 +
  2484. 2*tan(2)**4 + tan(2)**6) + O((x - 2)**6, (x, 2))
  2485. >>> f.series(x, 2, 3, "-")
  2486. tan(2) + (2 - x)*(-tan(2)**2 - 1) + (2 - x)**2*(tan(2)**3 + tan(2))
  2487. + O((x - 2)**3, (x, 2))
  2488. For rational expressions this method may return original expression without the Order term.
  2489. >>> (1/x).series(x, n=8)
  2490. 1/x
  2491. Returns
  2492. =======
  2493. Expr : Expression
  2494. Series expansion of the expression about x0
  2495. Raises
  2496. ======
  2497. TypeError
  2498. If "n" and "x0" are infinity objects
  2499. PoleError
  2500. If "x0" is an infinity object
  2501. """
  2502. if x is None:
  2503. syms = self.free_symbols
  2504. if not syms:
  2505. return self
  2506. elif len(syms) > 1:
  2507. raise ValueError('x must be given for multivariate functions.')
  2508. x = syms.pop()
  2509. from .symbol import Dummy, Symbol
  2510. if isinstance(x, Symbol):
  2511. dep = x in self.free_symbols
  2512. else:
  2513. d = Dummy()
  2514. dep = d in self.xreplace({x: d}).free_symbols
  2515. if not dep:
  2516. if n is None:
  2517. return (s for s in [self])
  2518. else:
  2519. return self
  2520. if len(dir) != 1 or dir not in '+-':
  2521. raise ValueError("Dir must be '+' or '-'")
  2522. if n is not None:
  2523. n = int(n)
  2524. if n < 0:
  2525. raise ValueError("Number of terms should be nonnegative")
  2526. x0 = sympify(x0)
  2527. cdir = sympify(cdir)
  2528. from sympy.functions.elementary.complexes import im, sign
  2529. if not cdir.is_zero:
  2530. if cdir.is_real:
  2531. dir = '+' if cdir.is_positive else '-'
  2532. else:
  2533. dir = '+' if im(cdir).is_positive else '-'
  2534. else:
  2535. if x0 and x0.is_infinite:
  2536. cdir = sign(x0).simplify()
  2537. elif str(dir) == "+":
  2538. cdir = S.One
  2539. elif str(dir) == "-":
  2540. cdir = S.NegativeOne
  2541. elif cdir == S.Zero:
  2542. cdir = S.One
  2543. cdir = cdir/abs(cdir)
  2544. if x0 and x0.is_infinite:
  2545. from .function import PoleError
  2546. try:
  2547. s = self.subs(x, cdir/x).series(x, n=n, dir='+', cdir=1)
  2548. if n is None:
  2549. return (si.subs(x, cdir/x) for si in s)
  2550. return s.subs(x, cdir/x)
  2551. except PoleError:
  2552. s = self.subs(x, cdir*x).aseries(x, n=n)
  2553. return s.subs(x, cdir*x)
  2554. # use rep to shift origin to x0 and change sign (if dir is negative)
  2555. # and undo the process with rep2
  2556. if x0 or cdir != 1:
  2557. s = self.subs({x: x0 + cdir*x}).series(x, x0=0, n=n, dir='+', logx=logx, cdir=1)
  2558. if n is None: # lseries...
  2559. return (si.subs({x: x/cdir - x0/cdir}) for si in s)
  2560. return s.subs({x: x/cdir - x0/cdir})
  2561. # from here on it's x0=0 and dir='+' handling
  2562. if x.is_positive is x.is_negative is None or x.is_Symbol is not True:
  2563. # replace x with an x that has a positive assumption
  2564. xpos = Dummy('x', positive=True)
  2565. rv = self.subs(x, xpos).series(xpos, x0, n, dir, logx=logx, cdir=cdir)
  2566. if n is None:
  2567. return (s.subs(xpos, x) for s in rv)
  2568. else:
  2569. return rv.subs(xpos, x)
  2570. from sympy.series.order import Order
  2571. if n is not None: # nseries handling
  2572. s1 = self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
  2573. o = s1.getO() or S.Zero
  2574. if o:
  2575. # make sure the requested order is returned
  2576. ngot = o.getn()
  2577. if ngot > n:
  2578. # leave o in its current form (e.g. with x*log(x)) so
  2579. # it eats terms properly, then replace it below
  2580. if n != 0:
  2581. s1 += o.subs(x, x**Rational(n, ngot))
  2582. else:
  2583. s1 += Order(1, x)
  2584. elif ngot < n:
  2585. # increase the requested number of terms to get the desired
  2586. # number keep increasing (up to 9) until the received order
  2587. # is different than the original order and then predict how
  2588. # many additional terms are needed
  2589. from sympy.functions.elementary.integers import ceiling
  2590. for more in range(1, 9):
  2591. s1 = self._eval_nseries(x, n=n + more, logx=logx, cdir=cdir)
  2592. newn = s1.getn()
  2593. if newn != ngot:
  2594. ndo = n + ceiling((n - ngot)*more/(newn - ngot))
  2595. s1 = self._eval_nseries(x, n=ndo, logx=logx, cdir=cdir)
  2596. while s1.getn() < n:
  2597. s1 = self._eval_nseries(x, n=ndo, logx=logx, cdir=cdir)
  2598. ndo += 1
  2599. break
  2600. else:
  2601. raise ValueError('Could not calculate %s terms for %s'
  2602. % (str(n), self))
  2603. s1 += Order(x**n, x)
  2604. o = s1.getO()
  2605. s1 = s1.removeO()
  2606. elif s1.has(Order):
  2607. # asymptotic expansion
  2608. return s1
  2609. else:
  2610. o = Order(x**n, x)
  2611. s1done = s1.doit()
  2612. try:
  2613. if (s1done + o).removeO() == s1done:
  2614. o = S.Zero
  2615. except NotImplementedError:
  2616. return s1
  2617. try:
  2618. from sympy.simplify.radsimp import collect
  2619. return collect(s1, x) + o
  2620. except NotImplementedError:
  2621. return s1 + o
  2622. else: # lseries handling
  2623. def yield_lseries(s):
  2624. """Return terms of lseries one at a time."""
  2625. for si in s:
  2626. if not si.is_Add:
  2627. yield si
  2628. continue
  2629. # yield terms 1 at a time if possible
  2630. # by increasing order until all the
  2631. # terms have been returned
  2632. yielded = 0
  2633. o = Order(si, x)*x
  2634. ndid = 0
  2635. ndo = len(si.args)
  2636. while 1:
  2637. do = (si - yielded + o).removeO()
  2638. o *= x
  2639. if not do or do.is_Order:
  2640. continue
  2641. if do.is_Add:
  2642. ndid += len(do.args)
  2643. else:
  2644. ndid += 1
  2645. yield do
  2646. if ndid == ndo:
  2647. break
  2648. yielded += do
  2649. return yield_lseries(self.removeO()._eval_lseries(x, logx=logx, cdir=cdir))
  2650. def aseries(self, x=None, n=6, bound=0, hir=False):
  2651. """Asymptotic Series expansion of self.
  2652. This is equivalent to ``self.series(x, oo, n)``.
  2653. Parameters
  2654. ==========
  2655. self : Expression
  2656. The expression whose series is to be expanded.
  2657. x : Symbol
  2658. It is the variable of the expression to be calculated.
  2659. n : Value
  2660. The value used to represent the order in terms of ``x**n``,
  2661. up to which the series is to be expanded.
  2662. hir : Boolean
  2663. Set this parameter to be True to produce hierarchical series.
  2664. It stops the recursion at an early level and may provide nicer
  2665. and more useful results.
  2666. bound : Value, Integer
  2667. Use the ``bound`` parameter to give limit on rewriting
  2668. coefficients in its normalised form.
  2669. Examples
  2670. ========
  2671. >>> from sympy import sin, exp
  2672. >>> from sympy.abc import x
  2673. >>> e = sin(1/x + exp(-x)) - sin(1/x)
  2674. >>> e.aseries(x)
  2675. (1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x)
  2676. >>> e.aseries(x, n=3, hir=True)
  2677. -exp(-2*x)*sin(1/x)/2 + exp(-x)*cos(1/x) + O(exp(-3*x), (x, oo))
  2678. >>> e = exp(exp(x)/(1 - 1/x))
  2679. >>> e.aseries(x)
  2680. exp(exp(x)/(1 - 1/x))
  2681. >>> e.aseries(x, bound=3) # doctest: +SKIP
  2682. exp(exp(x)/x**2)*exp(exp(x)/x)*exp(-exp(x) + exp(x)/(1 - 1/x) - exp(x)/x - exp(x)/x**2)*exp(exp(x))
  2683. For rational expressions this method may return original expression without the Order term.
  2684. >>> (1/x).aseries(x, n=8)
  2685. 1/x
  2686. Returns
  2687. =======
  2688. Expr
  2689. Asymptotic series expansion of the expression.
  2690. Notes
  2691. =====
  2692. This algorithm is directly induced from the limit computational algorithm provided by Gruntz.
  2693. It majorly uses the mrv and rewrite sub-routines. The overall idea of this algorithm is first
  2694. to look for the most rapidly varying subexpression w of a given expression f and then expands f
  2695. in a series in w. Then same thing is recursively done on the leading coefficient
  2696. till we get constant coefficients.
  2697. If the most rapidly varying subexpression of a given expression f is f itself,
  2698. the algorithm tries to find a normalised representation of the mrv set and rewrites f
  2699. using this normalised representation.
  2700. If the expansion contains an order term, it will be either ``O(x ** (-n))`` or ``O(w ** (-n))``
  2701. where ``w`` belongs to the most rapidly varying expression of ``self``.
  2702. References
  2703. ==========
  2704. .. [1] Gruntz, Dominik. A new algorithm for computing asymptotic series.
  2705. In: Proc. 1993 Int. Symp. Symbolic and Algebraic Computation. 1993.
  2706. pp. 239-244.
  2707. .. [2] Gruntz thesis - p90
  2708. .. [3] https://en.wikipedia.org/wiki/Asymptotic_expansion
  2709. See Also
  2710. ========
  2711. Expr.aseries: See the docstring of this function for complete details of this wrapper.
  2712. """
  2713. from .symbol import Dummy
  2714. if x.is_positive is x.is_negative is None:
  2715. xpos = Dummy('x', positive=True)
  2716. return self.subs(x, xpos).aseries(xpos, n, bound, hir).subs(xpos, x)
  2717. from .function import PoleError
  2718. from sympy.series.gruntz import mrv, rewrite
  2719. try:
  2720. om, exps = mrv(self, x)
  2721. except PoleError:
  2722. return self
  2723. # We move one level up by replacing `x` by `exp(x)`, and then
  2724. # computing the asymptotic series for f(exp(x)). Then asymptotic series
  2725. # can be obtained by moving one-step back, by replacing x by ln(x).
  2726. from sympy.functions.elementary.exponential import exp, log
  2727. from sympy.series.order import Order
  2728. if x in om:
  2729. s = self.subs(x, exp(x)).aseries(x, n, bound, hir).subs(x, log(x))
  2730. if s.getO():
  2731. return s + Order(1/x**n, (x, S.Infinity))
  2732. return s
  2733. k = Dummy('k', positive=True)
  2734. # f is rewritten in terms of omega
  2735. func, logw = rewrite(exps, om, x, k)
  2736. if self in om:
  2737. if bound <= 0:
  2738. return self
  2739. s = (self.exp).aseries(x, n, bound=bound)
  2740. s = s.func(*[t.removeO() for t in s.args])
  2741. try:
  2742. res = exp(s.subs(x, 1/x).as_leading_term(x).subs(x, 1/x))
  2743. except PoleError:
  2744. res = self
  2745. func = exp(self.args[0] - res.args[0]) / k
  2746. logw = log(1/res)
  2747. s = func.series(k, 0, n)
  2748. from sympy.core.function import expand_mul
  2749. s = expand_mul(s)
  2750. # Hierarchical series
  2751. if hir:
  2752. return s.subs(k, exp(logw))
  2753. o = s.getO()
  2754. terms = sorted(Add.make_args(s.removeO()), key=lambda i: int(i.as_coeff_exponent(k)[1]))
  2755. s = S.Zero
  2756. has_ord = False
  2757. # Then we recursively expand these coefficients one by one into
  2758. # their asymptotic series in terms of their most rapidly varying subexpressions.
  2759. for t in terms:
  2760. coeff, expo = t.as_coeff_exponent(k)
  2761. if coeff.has(x):
  2762. # Recursive step
  2763. snew = coeff.aseries(x, n, bound=bound-1)
  2764. if has_ord and snew.getO():
  2765. break
  2766. elif snew.getO():
  2767. has_ord = True
  2768. s += (snew * k**expo)
  2769. else:
  2770. s += t
  2771. if not o or has_ord:
  2772. return s.subs(k, exp(logw))
  2773. return (s + o).subs(k, exp(logw))
  2774. def taylor_term(self, n, x, *previous_terms):
  2775. """General method for the taylor term.
  2776. This method is slow, because it differentiates n-times. Subclasses can
  2777. redefine it to make it faster by using the "previous_terms".
  2778. """
  2779. from .symbol import Dummy
  2780. from sympy.functions.combinatorial.factorials import factorial
  2781. x = sympify(x)
  2782. _x = Dummy('x')
  2783. return self.subs(x, _x).diff(_x, n).subs(_x, x).subs(x, 0) * x**n / factorial(n)
  2784. def lseries(self, x=None, x0=0, dir='+', logx=None, cdir=0):
  2785. """
  2786. Wrapper for series yielding an iterator of the terms of the series.
  2787. Note: an infinite series will yield an infinite iterator. The following,
  2788. for exaxmple, will never terminate. It will just keep printing terms
  2789. of the sin(x) series::
  2790. for term in sin(x).lseries(x):
  2791. print term
  2792. The advantage of lseries() over nseries() is that many times you are
  2793. just interested in the next term in the series (i.e. the first term for
  2794. example), but you do not know how many you should ask for in nseries()
  2795. using the "n" parameter.
  2796. See also nseries().
  2797. """
  2798. return self.series(x, x0, n=None, dir=dir, logx=logx, cdir=cdir)
  2799. def _eval_lseries(self, x, logx=None, cdir=0):
  2800. # default implementation of lseries is using nseries(), and adaptively
  2801. # increasing the "n". As you can see, it is not very efficient, because
  2802. # we are calculating the series over and over again. Subclasses should
  2803. # override this method and implement much more efficient yielding of
  2804. # terms.
  2805. n = 0
  2806. series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
  2807. while series.is_Order:
  2808. n += 1
  2809. series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
  2810. e = series.removeO()
  2811. yield e
  2812. if e is S.Zero:
  2813. return
  2814. while 1:
  2815. while 1:
  2816. n += 1
  2817. series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir).removeO()
  2818. if e != series:
  2819. break
  2820. if (series - self).cancel() is S.Zero:
  2821. return
  2822. yield series - e
  2823. e = series
  2824. def nseries(self, x=None, x0=0, n=6, dir='+', logx=None, cdir=0):
  2825. """
  2826. Wrapper to _eval_nseries if assumptions allow, else to series.
  2827. If x is given, x0 is 0, dir='+', and self has x, then _eval_nseries is
  2828. called. This calculates "n" terms in the innermost expressions and
  2829. then builds up the final series just by "cross-multiplying" everything
  2830. out.
  2831. The optional ``logx`` parameter can be used to replace any log(x) in the
  2832. returned series with a symbolic value to avoid evaluating log(x) at 0. A
  2833. symbol to use in place of log(x) should be provided.
  2834. Advantage -- it's fast, because we do not have to determine how many
  2835. terms we need to calculate in advance.
  2836. Disadvantage -- you may end up with less terms than you may have
  2837. expected, but the O(x**n) term appended will always be correct and
  2838. so the result, though perhaps shorter, will also be correct.
  2839. If any of those assumptions is not met, this is treated like a
  2840. wrapper to series which will try harder to return the correct
  2841. number of terms.
  2842. See also lseries().
  2843. Examples
  2844. ========
  2845. >>> from sympy import sin, log, Symbol
  2846. >>> from sympy.abc import x, y
  2847. >>> sin(x).nseries(x, 0, 6)
  2848. x - x**3/6 + x**5/120 + O(x**6)
  2849. >>> log(x+1).nseries(x, 0, 5)
  2850. x - x**2/2 + x**3/3 - x**4/4 + O(x**5)
  2851. Handling of the ``logx`` parameter --- in the following example the
  2852. expansion fails since ``sin`` does not have an asymptotic expansion
  2853. at -oo (the limit of log(x) as x approaches 0):
  2854. >>> e = sin(log(x))
  2855. >>> e.nseries(x, 0, 6)
  2856. Traceback (most recent call last):
  2857. ...
  2858. PoleError: ...
  2859. ...
  2860. >>> logx = Symbol('logx')
  2861. >>> e.nseries(x, 0, 6, logx=logx)
  2862. sin(logx)
  2863. In the following example, the expansion works but only returns self
  2864. unless the ``logx`` parameter is used:
  2865. >>> e = x**y
  2866. >>> e.nseries(x, 0, 2)
  2867. x**y
  2868. >>> e.nseries(x, 0, 2, logx=logx)
  2869. exp(logx*y)
  2870. """
  2871. if x and x not in self.free_symbols:
  2872. return self
  2873. if x is None or x0 or dir != '+': # {see XPOS above} or (x.is_positive == x.is_negative == None):
  2874. return self.series(x, x0, n, dir, cdir=cdir)
  2875. else:
  2876. return self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
  2877. def _eval_nseries(self, x, n, logx, cdir):
  2878. """
  2879. Return terms of series for self up to O(x**n) at x=0
  2880. from the positive direction.
  2881. This is a method that should be overridden in subclasses. Users should
  2882. never call this method directly (use .nseries() instead), so you do not
  2883. have to write docstrings for _eval_nseries().
  2884. """
  2885. raise NotImplementedError(filldedent("""
  2886. The _eval_nseries method should be added to
  2887. %s to give terms up to O(x**n) at x=0
  2888. from the positive direction so it is available when
  2889. nseries calls it.""" % self.func)
  2890. )
  2891. def limit(self, x, xlim, dir='+'):
  2892. """ Compute limit x->xlim.
  2893. """
  2894. from sympy.series.limits import limit
  2895. return limit(self, x, xlim, dir)
  2896. @cacheit
  2897. def as_leading_term(self, *symbols, logx=None, cdir=0):
  2898. """
  2899. Returns the leading (nonzero) term of the series expansion of self.
  2900. The _eval_as_leading_term routines are used to do this, and they must
  2901. always return a non-zero value.
  2902. Examples
  2903. ========
  2904. >>> from sympy.abc import x
  2905. >>> (1 + x + x**2).as_leading_term(x)
  2906. 1
  2907. >>> (1/x**2 + x + x**2).as_leading_term(x)
  2908. x**(-2)
  2909. """
  2910. if len(symbols) > 1:
  2911. c = self
  2912. for x in symbols:
  2913. c = c.as_leading_term(x, logx=logx, cdir=cdir)
  2914. return c
  2915. elif not symbols:
  2916. return self
  2917. x = sympify(symbols[0])
  2918. cdir = sympify(cdir)
  2919. if not x.is_symbol:
  2920. raise ValueError('expecting a Symbol but got %s' % x)
  2921. if x not in self.free_symbols:
  2922. return self
  2923. obj = self._eval_as_leading_term(x, logx=logx, cdir=cdir)
  2924. if obj is not None:
  2925. from sympy.simplify.powsimp import powsimp
  2926. return powsimp(obj, deep=True, combine='exp')
  2927. raise NotImplementedError('as_leading_term(%s, %s)' % (self, x))
  2928. def _eval_as_leading_term(self, x, logx, cdir):
  2929. return self
  2930. def as_coeff_exponent(self, x) -> tuple[Expr, Expr]:
  2931. """ ``c*x**e -> c,e`` where x can be any symbolic expression.
  2932. """
  2933. from sympy.simplify.radsimp import collect
  2934. s = collect(self, x)
  2935. c, p = s.as_coeff_mul(x)
  2936. if len(p) == 1:
  2937. b, e = p[0].as_base_exp()
  2938. if b == x:
  2939. return c, e
  2940. return s, S.Zero
  2941. def leadterm(self, x, logx=None, cdir=0):
  2942. """
  2943. Returns the leading term a*x**b as a tuple (a, b).
  2944. Examples
  2945. ========
  2946. >>> from sympy.abc import x
  2947. >>> (1+x+x**2).leadterm(x)
  2948. (1, 0)
  2949. >>> (1/x**2+x+x**2).leadterm(x)
  2950. (1, -2)
  2951. """
  2952. from .symbol import Dummy
  2953. from sympy.functions.elementary.exponential import log
  2954. l = self.as_leading_term(x, logx=logx, cdir=cdir)
  2955. d = Dummy('logx')
  2956. if l.has(log(x)):
  2957. l = l.subs(log(x), d)
  2958. c, e = l.as_coeff_exponent(x)
  2959. if x in c.free_symbols:
  2960. raise ValueError(filldedent("""
  2961. cannot compute leadterm(%s, %s). The coefficient
  2962. should have been free of %s but got %s""" % (self, x, x, c)))
  2963. c = c.subs(d, log(x))
  2964. return c, e
  2965. def as_coeff_Mul(self, rational: bool = False) -> tuple['Number', Expr]:
  2966. """Efficiently extract the coefficient of a product."""
  2967. return S.One, self
  2968. def as_coeff_Add(self, rational=False) -> tuple['Number', Expr]:
  2969. """Efficiently extract the coefficient of a summation."""
  2970. return S.Zero, self
  2971. def fps(self, x=None, x0=0, dir=1, hyper=True, order=4, rational=True,
  2972. full=False):
  2973. """
  2974. Compute formal power power series of self.
  2975. See the docstring of the :func:`fps` function in sympy.series.formal for
  2976. more information.
  2977. """
  2978. from sympy.series.formal import fps
  2979. return fps(self, x, x0, dir, hyper, order, rational, full)
  2980. def fourier_series(self, limits=None):
  2981. """Compute fourier sine/cosine series of self.
  2982. See the docstring of the :func:`fourier_series` in sympy.series.fourier
  2983. for more information.
  2984. """
  2985. from sympy.series.fourier import fourier_series
  2986. return fourier_series(self, limits)
  2987. ###################################################################################
  2988. ##################### DERIVATIVE, INTEGRAL, FUNCTIONAL METHODS ####################
  2989. ###################################################################################
  2990. def diff(self, *symbols, **assumptions):
  2991. assumptions.setdefault("evaluate", True)
  2992. return _derivative_dispatch(self, *symbols, **assumptions)
  2993. ###########################################################################
  2994. ###################### EXPRESSION EXPANSION METHODS #######################
  2995. ###########################################################################
  2996. # Relevant subclasses should override _eval_expand_hint() methods. See
  2997. # the docstring of expand() for more info.
  2998. def _eval_expand_complex(self, **hints):
  2999. real, imag = self.as_real_imag(**hints)
  3000. return real + S.ImaginaryUnit*imag
  3001. @staticmethod
  3002. def _expand_hint(expr, hint, deep=True, **hints):
  3003. """
  3004. Helper for ``expand()``. Recursively calls ``expr._eval_expand_hint()``.
  3005. Returns ``(expr, hit)``, where expr is the (possibly) expanded
  3006. ``expr`` and ``hit`` is ``True`` if ``expr`` was truly expanded and
  3007. ``False`` otherwise.
  3008. """
  3009. hit = False
  3010. # XXX: Hack to support non-Basic args
  3011. # |
  3012. # V
  3013. if deep and getattr(expr, 'args', ()) and not expr.is_Atom:
  3014. sargs = []
  3015. for arg in expr.args:
  3016. arg, arghit = Expr._expand_hint(arg, hint, **hints)
  3017. hit |= arghit
  3018. sargs.append(arg)
  3019. if hit:
  3020. expr = expr.func(*sargs)
  3021. if hasattr(expr, hint):
  3022. newexpr = getattr(expr, hint)(**hints)
  3023. if newexpr != expr:
  3024. return (newexpr, True)
  3025. return (expr, hit)
  3026. @cacheit
  3027. def expand(self, deep=True, modulus=None, power_base=True, power_exp=True,
  3028. mul=True, log=True, multinomial=True, basic=True, **hints):
  3029. """
  3030. Expand an expression using hints.
  3031. See the docstring of the expand() function in sympy.core.function for
  3032. more information.
  3033. """
  3034. from sympy.simplify.radsimp import fraction
  3035. hints.update(power_base=power_base, power_exp=power_exp, mul=mul,
  3036. log=log, multinomial=multinomial, basic=basic)
  3037. expr = self
  3038. # default matches fraction's default
  3039. _fraction = lambda x: fraction(x, hints.get('exact', False))
  3040. if hints.pop('frac', False):
  3041. n, d = [a.expand(deep=deep, modulus=modulus, **hints)
  3042. for a in _fraction(self)]
  3043. return n/d
  3044. elif hints.pop('denom', False):
  3045. n, d = _fraction(self)
  3046. return n/d.expand(deep=deep, modulus=modulus, **hints)
  3047. elif hints.pop('numer', False):
  3048. n, d = _fraction(self)
  3049. return n.expand(deep=deep, modulus=modulus, **hints)/d
  3050. # Although the hints are sorted here, an earlier hint may get applied
  3051. # at a given node in the expression tree before another because of how
  3052. # the hints are applied. e.g. expand(log(x*(y + z))) -> log(x*y +
  3053. # x*z) because while applying log at the top level, log and mul are
  3054. # applied at the deeper level in the tree so that when the log at the
  3055. # upper level gets applied, the mul has already been applied at the
  3056. # lower level.
  3057. # Additionally, because hints are only applied once, the expression
  3058. # may not be expanded all the way. For example, if mul is applied
  3059. # before multinomial, x*(x + 1)**2 won't be expanded all the way. For
  3060. # now, we just use a special case to make multinomial run before mul,
  3061. # so that at least polynomials will be expanded all the way. In the
  3062. # future, smarter heuristics should be applied.
  3063. # TODO: Smarter heuristics
  3064. def _expand_hint_key(hint):
  3065. """Make multinomial come before mul"""
  3066. if hint == 'mul':
  3067. return 'mulz'
  3068. return hint
  3069. for hint in sorted(hints.keys(), key=_expand_hint_key):
  3070. use_hint = hints[hint]
  3071. if use_hint:
  3072. hint = '_eval_expand_' + hint
  3073. expr, hit = Expr._expand_hint(expr, hint, deep=deep, **hints)
  3074. while True:
  3075. was = expr
  3076. if hints.get('multinomial', False):
  3077. expr, _ = Expr._expand_hint(
  3078. expr, '_eval_expand_multinomial', deep=deep, **hints)
  3079. if hints.get('mul', False):
  3080. expr, _ = Expr._expand_hint(
  3081. expr, '_eval_expand_mul', deep=deep, **hints)
  3082. if hints.get('log', False):
  3083. expr, _ = Expr._expand_hint(
  3084. expr, '_eval_expand_log', deep=deep, **hints)
  3085. if expr == was:
  3086. break
  3087. if modulus is not None:
  3088. modulus = sympify(modulus)
  3089. if not modulus.is_Integer or modulus <= 0:
  3090. raise ValueError(
  3091. "modulus must be a positive integer, got %s" % modulus)
  3092. terms = []
  3093. for term in Add.make_args(expr):
  3094. coeff, tail = term.as_coeff_Mul(rational=True)
  3095. coeff %= modulus
  3096. if coeff:
  3097. terms.append(coeff*tail)
  3098. expr = Add(*terms)
  3099. return expr
  3100. ###########################################################################
  3101. ################### GLOBAL ACTION VERB WRAPPER METHODS ####################
  3102. ###########################################################################
  3103. def integrate(self, *args, **kwargs):
  3104. """See the integrate function in sympy.integrals"""
  3105. from sympy.integrals.integrals import integrate
  3106. return integrate(self, *args, **kwargs)
  3107. def nsimplify(self, constants=(), tolerance=None, full=False):
  3108. """See the nsimplify function in sympy.simplify"""
  3109. from sympy.simplify.simplify import nsimplify
  3110. return nsimplify(self, constants, tolerance, full)
  3111. def separate(self, deep=False, force=False):
  3112. """See the separate function in sympy.simplify"""
  3113. from .function import expand_power_base
  3114. return expand_power_base(self, deep=deep, force=force)
  3115. def collect(self, syms, func=None, evaluate=True, exact=False, distribute_order_term=True):
  3116. """See the collect function in sympy.simplify"""
  3117. from sympy.simplify.radsimp import collect
  3118. return collect(self, syms, func, evaluate, exact, distribute_order_term)
  3119. def together(self, *args, **kwargs):
  3120. """See the together function in sympy.polys"""
  3121. from sympy.polys.rationaltools import together
  3122. return together(self, *args, **kwargs)
  3123. def apart(self, x=None, **args):
  3124. """See the apart function in sympy.polys"""
  3125. from sympy.polys.partfrac import apart
  3126. return apart(self, x, **args)
  3127. def ratsimp(self):
  3128. """See the ratsimp function in sympy.simplify"""
  3129. from sympy.simplify.ratsimp import ratsimp
  3130. return ratsimp(self)
  3131. def trigsimp(self, **args):
  3132. """See the trigsimp function in sympy.simplify"""
  3133. from sympy.simplify.trigsimp import trigsimp
  3134. return trigsimp(self, **args)
  3135. def radsimp(self, **kwargs):
  3136. """See the radsimp function in sympy.simplify"""
  3137. from sympy.simplify.radsimp import radsimp
  3138. return radsimp(self, **kwargs)
  3139. def powsimp(self, *args, **kwargs):
  3140. """See the powsimp function in sympy.simplify"""
  3141. from sympy.simplify.powsimp import powsimp
  3142. return powsimp(self, *args, **kwargs)
  3143. def combsimp(self):
  3144. """See the combsimp function in sympy.simplify"""
  3145. from sympy.simplify.combsimp import combsimp
  3146. return combsimp(self)
  3147. def gammasimp(self):
  3148. """See the gammasimp function in sympy.simplify"""
  3149. from sympy.simplify.gammasimp import gammasimp
  3150. return gammasimp(self)
  3151. def factor(self, *gens, **args):
  3152. """See the factor() function in sympy.polys.polytools"""
  3153. from sympy.polys.polytools import factor
  3154. return factor(self, *gens, **args)
  3155. def cancel(self, *gens, **args):
  3156. """See the cancel function in sympy.polys"""
  3157. from sympy.polys.polytools import cancel
  3158. return cancel(self, *gens, **args)
  3159. def invert(self, g, *gens, **args):
  3160. """Return the multiplicative inverse of ``self`` mod ``g``
  3161. where ``self`` (and ``g``) may be symbolic expressions).
  3162. See Also
  3163. ========
  3164. sympy.core.intfunc.mod_inverse, sympy.polys.polytools.invert
  3165. """
  3166. if self.is_number and getattr(g, 'is_number', True):
  3167. return mod_inverse(self, g)
  3168. from sympy.polys.polytools import invert
  3169. return invert(self, g, *gens, **args)
  3170. def round(self, n=None):
  3171. """Return x rounded to the given decimal place.
  3172. If a complex number would results, apply round to the real
  3173. and imaginary components of the number.
  3174. Examples
  3175. ========
  3176. >>> from sympy import pi, E, I, S, Number
  3177. >>> pi.round()
  3178. 3
  3179. >>> pi.round(2)
  3180. 3.14
  3181. >>> (2*pi + E*I).round()
  3182. 6 + 3*I
  3183. The round method has a chopping effect:
  3184. >>> (2*pi + I/10).round()
  3185. 6
  3186. >>> (pi/10 + 2*I).round()
  3187. 2*I
  3188. >>> (pi/10 + E*I).round(2)
  3189. 0.31 + 2.72*I
  3190. Notes
  3191. =====
  3192. The Python ``round`` function uses the SymPy ``round`` method so it
  3193. will always return a SymPy number (not a Python float or int):
  3194. >>> isinstance(round(S(123), -2), Number)
  3195. True
  3196. """
  3197. x = self
  3198. if not x.is_number:
  3199. raise TypeError("Cannot round symbolic expression")
  3200. if not x.is_Atom:
  3201. if not pure_complex(x.n(2), or_real=True):
  3202. raise TypeError(
  3203. 'Expected a number but got %s:' % func_name(x))
  3204. elif x in _illegal:
  3205. return x
  3206. if not (xr := x.is_extended_real):
  3207. r, i = x.as_real_imag()
  3208. if xr is False:
  3209. return r.round(n) + S.ImaginaryUnit*i.round(n)
  3210. if i.equals(0):
  3211. return r.round(n)
  3212. if not x:
  3213. return S.Zero if n is None else x
  3214. p = as_int(n or 0)
  3215. if x.is_Integer:
  3216. return Integer(round(int(x), p))
  3217. digits_to_decimal = _mag(x) # _mag(12) = 2, _mag(.012) = -1
  3218. allow = digits_to_decimal + p
  3219. precs = [f._prec for f in x.atoms(Float)]
  3220. dps = prec_to_dps(max(precs)) if precs else None
  3221. if dps is None:
  3222. # assume everything is exact so use the Python
  3223. # float default or whatever was requested
  3224. dps = max(15, allow)
  3225. else:
  3226. allow = min(allow, dps)
  3227. # this will shift all digits to right of decimal
  3228. # and give us dps to work with as an int
  3229. shift = -digits_to_decimal + dps
  3230. extra = 1 # how far we look past known digits
  3231. # NOTE
  3232. # mpmath will calculate the binary representation to
  3233. # an arbitrary number of digits but we must base our
  3234. # answer on a finite number of those digits, e.g.
  3235. # .575 2589569785738035/2**52 in binary.
  3236. # mpmath shows us that the first 18 digits are
  3237. # >>> Float(.575).n(18)
  3238. # 0.574999999999999956
  3239. # The default precision is 15 digits and if we ask
  3240. # for 15 we get
  3241. # >>> Float(.575).n(15)
  3242. # 0.575000000000000
  3243. # mpmath handles rounding at the 15th digit. But we
  3244. # need to be careful since the user might be asking
  3245. # for rounding at the last digit and our semantics
  3246. # are to round toward the even final digit when there
  3247. # is a tie. So the extra digit will be used to make
  3248. # that decision. In this case, the value is the same
  3249. # to 15 digits:
  3250. # >>> Float(.575).n(16)
  3251. # 0.5750000000000000
  3252. # Now converting this to the 15 known digits gives
  3253. # 575000000000000.0
  3254. # which rounds to integer
  3255. # 5750000000000000
  3256. # And now we can round to the desired digt, e.g. at
  3257. # the second from the left and we get
  3258. # 5800000000000000
  3259. # and rescaling that gives
  3260. # 0.58
  3261. # as the final result.
  3262. # If the value is made slightly less than 0.575 we might
  3263. # still obtain the same value:
  3264. # >>> Float(.575-1e-16).n(16)*10**15
  3265. # 574999999999999.8
  3266. # What 15 digits best represents the known digits (which are
  3267. # to the left of the decimal? 5750000000000000, the same as
  3268. # before. The only way we will round down (in this case) is
  3269. # if we declared that we had more than 15 digits of precision.
  3270. # For example, if we use 16 digits of precision, the integer
  3271. # we deal with is
  3272. # >>> Float(.575-1e-16).n(17)*10**16
  3273. # 5749999999999998.4
  3274. # and this now rounds to 5749999999999998 and (if we round to
  3275. # the 2nd digit from the left) we get 5700000000000000.
  3276. #
  3277. xf = x.n(dps + extra)*Pow(10, shift)
  3278. if xf.is_Number and xf._prec == 1: # xf.is_Add will raise below
  3279. # is x == 0?
  3280. if x.equals(0):
  3281. return Float(0)
  3282. raise ValueError('not computing with precision')
  3283. xi = Integer(xf)
  3284. # use the last digit to select the value of xi
  3285. # nearest to x before rounding at the desired digit
  3286. sign = 1 if x > 0 else -1
  3287. dif2 = sign*(xf - xi).n(extra)
  3288. if dif2 < 0:
  3289. raise NotImplementedError(
  3290. 'not expecting int(x) to round away from 0')
  3291. if dif2 > .5:
  3292. xi += sign # round away from 0
  3293. elif dif2 == .5:
  3294. xi += sign if xi%2 else -sign # round toward even
  3295. # shift p to the new position
  3296. ip = p - shift
  3297. # let Python handle the int rounding then rescale
  3298. xr = round(xi.p, ip)
  3299. # restore scale
  3300. rv = Rational(xr, Pow(10, shift))
  3301. # return Float or Integer
  3302. if rv.is_Integer:
  3303. if n is None: # the single-arg case
  3304. return rv
  3305. # use str or else it won't be a float
  3306. return Float(str(rv), dps) # keep same precision
  3307. else:
  3308. if not allow and rv > self:
  3309. allow += 1
  3310. return Float(rv, allow)
  3311. __round__ = round
  3312. def _eval_derivative_matrix_lines(self, x):
  3313. from sympy.matrices.expressions.matexpr import _LeftRightArgs
  3314. return [_LeftRightArgs([S.One, S.One], higher=self._eval_derivative(x))]
  3315. class AtomicExpr(Atom, Expr):
  3316. """
  3317. A parent class for object which are both atoms and Exprs.
  3318. For example: Symbol, Number, Rational, Integer, ...
  3319. But not: Add, Mul, Pow, ...
  3320. """
  3321. is_number = False
  3322. is_Atom = True
  3323. __slots__ = ()
  3324. def _eval_derivative(self, s):
  3325. if self == s:
  3326. return S.One
  3327. return S.Zero
  3328. def _eval_derivative_n_times(self, s, n):
  3329. from .containers import Tuple
  3330. from sympy.matrices.expressions.matexpr import MatrixExpr
  3331. from sympy.matrices.matrixbase import MatrixBase
  3332. if isinstance(s, (MatrixBase, Tuple, Iterable, MatrixExpr)):
  3333. return super()._eval_derivative_n_times(s, n)
  3334. from .relational import Eq
  3335. from sympy.functions.elementary.piecewise import Piecewise
  3336. if self == s:
  3337. return Piecewise((self, Eq(n, 0)), (1, Eq(n, 1)), (0, True))
  3338. else:
  3339. return Piecewise((self, Eq(n, 0)), (0, True))
  3340. def _eval_is_polynomial(self, syms):
  3341. return True
  3342. def _eval_is_rational_function(self, syms):
  3343. return self not in _illegal
  3344. def _eval_is_meromorphic(self, x, a):
  3345. from sympy.calculus.accumulationbounds import AccumBounds
  3346. return (not self.is_Number or self.is_finite) and not isinstance(self, AccumBounds)
  3347. def _eval_is_algebraic_expr(self, syms):
  3348. return True
  3349. def _eval_nseries(self, x, n, logx, cdir=0):
  3350. return self
  3351. @property
  3352. def expr_free_symbols(self):
  3353. sympy_deprecation_warning("""
  3354. The expr_free_symbols property is deprecated. Use free_symbols to get
  3355. the free symbols of an expression.
  3356. """,
  3357. deprecated_since_version="1.9",
  3358. active_deprecations_target="deprecated-expr-free-symbols")
  3359. return {self}
  3360. def _mag(x):
  3361. r"""Return integer $i$ such that $0.1 \le x/10^i < 1$
  3362. Examples
  3363. ========
  3364. >>> from sympy.core.expr import _mag
  3365. >>> from sympy import Float
  3366. >>> _mag(Float(.1))
  3367. 0
  3368. >>> _mag(Float(.01))
  3369. -1
  3370. >>> _mag(Float(1234))
  3371. 4
  3372. """
  3373. from math import log10, ceil, log
  3374. xpos = abs(x.n())
  3375. if not xpos:
  3376. return S.Zero
  3377. try:
  3378. mag_first_dig = int(ceil(log10(xpos)))
  3379. except (ValueError, OverflowError):
  3380. mag_first_dig = int(ceil(Float(mpf_log(xpos._mpf_, 53))/log(10)))
  3381. # check that we aren't off by 1
  3382. if (xpos/S(10)**mag_first_dig) >= 1:
  3383. assert 1 <= (xpos/S(10)**mag_first_dig) < 10
  3384. mag_first_dig += 1
  3385. return mag_first_dig
  3386. class UnevaluatedExpr(Expr):
  3387. """
  3388. Expression that is not evaluated unless released.
  3389. Examples
  3390. ========
  3391. >>> from sympy import UnevaluatedExpr
  3392. >>> from sympy.abc import x
  3393. >>> x*(1/x)
  3394. 1
  3395. >>> x*UnevaluatedExpr(1/x)
  3396. x*1/x
  3397. """
  3398. def __new__(cls, arg, **kwargs):
  3399. arg = _sympify(arg)
  3400. obj = Expr.__new__(cls, arg, **kwargs)
  3401. return obj
  3402. def doit(self, **hints):
  3403. if hints.get("deep", True):
  3404. return self.args[0].doit(**hints)
  3405. else:
  3406. return self.args[0]
  3407. def unchanged(func, *args):
  3408. """Return True if `func` applied to the `args` is unchanged.
  3409. Can be used instead of `assert foo == foo`.
  3410. Examples
  3411. ========
  3412. >>> from sympy import Piecewise, cos, pi
  3413. >>> from sympy.core.expr import unchanged
  3414. >>> from sympy.abc import x
  3415. >>> unchanged(cos, 1) # instead of assert cos(1) == cos(1)
  3416. True
  3417. >>> unchanged(cos, pi)
  3418. False
  3419. Comparison of args uses the builtin capabilities of the object's
  3420. arguments to test for equality so args can be defined loosely. Here,
  3421. the ExprCondPair arguments of Piecewise compare as equal to the
  3422. tuples that can be used to create the Piecewise:
  3423. >>> unchanged(Piecewise, (x, x > 1), (0, True))
  3424. True
  3425. """
  3426. f = func(*args)
  3427. return f.func == func and f.args == args
  3428. class ExprBuilder:
  3429. def __init__(self, op, args=None, validator=None, check=True):
  3430. if not hasattr(op, "__call__"):
  3431. raise TypeError("op {} needs to be callable".format(op))
  3432. self.op = op
  3433. if args is None:
  3434. self.args = []
  3435. else:
  3436. self.args = args
  3437. self.validator = validator
  3438. if (validator is not None) and check:
  3439. self.validate()
  3440. @staticmethod
  3441. def _build_args(args):
  3442. return [i.build() if isinstance(i, ExprBuilder) else i for i in args]
  3443. def validate(self):
  3444. if self.validator is None:
  3445. return
  3446. args = self._build_args(self.args)
  3447. self.validator(*args)
  3448. def build(self, check=True):
  3449. args = self._build_args(self.args)
  3450. if self.validator and check:
  3451. self.validator(*args)
  3452. return self.op(*args)
  3453. def append_argument(self, arg, check=True):
  3454. self.args.append(arg)
  3455. if self.validator and check:
  3456. self.validate(*self.args)
  3457. def __getitem__(self, item):
  3458. if item == 0:
  3459. return self.op
  3460. else:
  3461. return self.args[item-1]
  3462. def __repr__(self):
  3463. return str(self.build())
  3464. def search_element(self, elem):
  3465. for i, arg in enumerate(self.args):
  3466. if isinstance(arg, ExprBuilder):
  3467. ret = arg.search_index(elem)
  3468. if ret is not None:
  3469. return (i,) + ret
  3470. elif id(arg) == id(elem):
  3471. return (i,)
  3472. return None
  3473. from .mul import Mul
  3474. from .add import Add
  3475. from .power import Pow
  3476. from .function import Function, _derivative_dispatch
  3477. from .mod import Mod
  3478. from .exprtools import factor_terms
  3479. from .numbers import Float, Integer, Rational, _illegal, int_valued