expr.py 139 KB

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