test_expr.py 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261
  1. from sympy.assumptions.refine import refine
  2. from sympy.concrete.summations import Sum
  3. from sympy.core.add import Add
  4. from sympy.core.basic import Basic
  5. from sympy.core.containers import Tuple
  6. from sympy.core.expr import (ExprBuilder, unchanged, Expr,
  7. UnevaluatedExpr)
  8. from sympy.core.function import (Function, expand, WildFunction,
  9. AppliedUndef, Derivative, diff, Subs)
  10. from sympy.core.mul import Mul
  11. from sympy.core.numbers import (NumberSymbol, E, zoo, oo, Float, I,
  12. Rational, nan, Integer, Number, pi, _illegal)
  13. from sympy.core.power import Pow
  14. from sympy.core.relational import Ge, Lt, Gt, Le
  15. from sympy.core.singleton import S
  16. from sympy.core.sorting import default_sort_key
  17. from sympy.core.symbol import Symbol, symbols, Dummy, Wild
  18. from sympy.core.sympify import sympify
  19. from sympy.functions.combinatorial.factorials import factorial
  20. from sympy.functions.elementary.exponential import exp_polar, exp, log
  21. from sympy.functions.elementary.miscellaneous import sqrt, Max
  22. from sympy.functions.elementary.piecewise import Piecewise
  23. from sympy.functions.elementary.trigonometric import tan, sin, cos
  24. from sympy.functions.special.delta_functions import (Heaviside,
  25. DiracDelta)
  26. from sympy.functions.special.error_functions import Si
  27. from sympy.functions.special.gamma_functions import gamma
  28. from sympy.integrals.integrals import integrate, Integral
  29. from sympy.physics.secondquant import FockState
  30. from sympy.polys.partfrac import apart
  31. from sympy.polys.polytools import factor, cancel, Poly
  32. from sympy.polys.rationaltools import together
  33. from sympy.series.order import O
  34. from sympy.sets.sets import FiniteSet
  35. from sympy.simplify.combsimp import combsimp
  36. from sympy.simplify.gammasimp import gammasimp
  37. from sympy.simplify.powsimp import powsimp
  38. from sympy.simplify.radsimp import collect, radsimp
  39. from sympy.simplify.ratsimp import ratsimp
  40. from sympy.simplify.simplify import simplify, nsimplify
  41. from sympy.simplify.trigsimp import trigsimp
  42. from sympy.tensor.indexed import Indexed
  43. from sympy.physics.units import meter
  44. from sympy.testing.pytest import raises, XFAIL
  45. from sympy.abc import a, b, c, n, t, u, x, y, z
  46. f, g, h = symbols('f,g,h', cls=Function)
  47. class DummyNumber:
  48. """
  49. Minimal implementation of a number that works with SymPy.
  50. If one has a Number class (e.g. Sage Integer, or some other custom class)
  51. that one wants to work well with SymPy, one has to implement at least the
  52. methods of this class DummyNumber, resp. its subclasses I5 and F1_1.
  53. Basically, one just needs to implement either __int__() or __float__() and
  54. then one needs to make sure that the class works with Python integers and
  55. with itself.
  56. """
  57. def __radd__(self, a):
  58. if isinstance(a, (int, float)):
  59. return a + self.number
  60. return NotImplemented
  61. def __add__(self, a):
  62. if isinstance(a, (int, float, DummyNumber)):
  63. return self.number + a
  64. return NotImplemented
  65. def __rsub__(self, a):
  66. if isinstance(a, (int, float)):
  67. return a - self.number
  68. return NotImplemented
  69. def __sub__(self, a):
  70. if isinstance(a, (int, float, DummyNumber)):
  71. return self.number - a
  72. return NotImplemented
  73. def __rmul__(self, a):
  74. if isinstance(a, (int, float)):
  75. return a * self.number
  76. return NotImplemented
  77. def __mul__(self, a):
  78. if isinstance(a, (int, float, DummyNumber)):
  79. return self.number * a
  80. return NotImplemented
  81. def __rtruediv__(self, a):
  82. if isinstance(a, (int, float)):
  83. return a / self.number
  84. return NotImplemented
  85. def __truediv__(self, a):
  86. if isinstance(a, (int, float, DummyNumber)):
  87. return self.number / a
  88. return NotImplemented
  89. def __rpow__(self, a):
  90. if isinstance(a, (int, float)):
  91. return a ** self.number
  92. return NotImplemented
  93. def __pow__(self, a):
  94. if isinstance(a, (int, float, DummyNumber)):
  95. return self.number ** a
  96. return NotImplemented
  97. def __pos__(self):
  98. return self.number
  99. def __neg__(self):
  100. return - self.number
  101. class I5(DummyNumber):
  102. number = 5
  103. def __int__(self):
  104. return self.number
  105. class F1_1(DummyNumber):
  106. number = 1.1
  107. def __float__(self):
  108. return self.number
  109. i5 = I5()
  110. f1_1 = F1_1()
  111. # basic SymPy objects
  112. basic_objs = [
  113. Rational(2),
  114. Float("1.3"),
  115. x,
  116. y,
  117. pow(x, y)*y,
  118. ]
  119. # all supported objects
  120. all_objs = basic_objs + [
  121. 5,
  122. 5.5,
  123. i5,
  124. f1_1
  125. ]
  126. def dotest(s):
  127. for xo in all_objs:
  128. for yo in all_objs:
  129. s(xo, yo)
  130. return True
  131. def test_basic():
  132. def j(a, b):
  133. x = a
  134. x = +a
  135. x = -a
  136. x = a + b
  137. x = a - b
  138. x = a*b
  139. x = a/b
  140. x = a**b
  141. del x
  142. assert dotest(j)
  143. def test_ibasic():
  144. def s(a, b):
  145. x = a
  146. x += b
  147. x = a
  148. x -= b
  149. x = a
  150. x *= b
  151. x = a
  152. x /= b
  153. assert dotest(s)
  154. class NonBasic:
  155. '''This class represents an object that knows how to implement binary
  156. operations like +, -, etc with Expr but is not a subclass of Basic itself.
  157. The NonExpr subclass below does subclass Basic but not Expr.
  158. For both NonBasic and NonExpr it should be possible for them to override
  159. Expr.__add__ etc because Expr.__add__ should be returning NotImplemented
  160. for non Expr classes. Otherwise Expr.__add__ would create meaningless
  161. objects like Add(Integer(1), FiniteSet(2)) and it wouldn't be possible for
  162. other classes to override these operations when interacting with Expr.
  163. '''
  164. def __add__(self, other):
  165. return SpecialOp('+', self, other)
  166. def __radd__(self, other):
  167. return SpecialOp('+', other, self)
  168. def __sub__(self, other):
  169. return SpecialOp('-', self, other)
  170. def __rsub__(self, other):
  171. return SpecialOp('-', other, self)
  172. def __mul__(self, other):
  173. return SpecialOp('*', self, other)
  174. def __rmul__(self, other):
  175. return SpecialOp('*', other, self)
  176. def __truediv__(self, other):
  177. return SpecialOp('/', self, other)
  178. def __rtruediv__(self, other):
  179. return SpecialOp('/', other, self)
  180. def __floordiv__(self, other):
  181. return SpecialOp('//', self, other)
  182. def __rfloordiv__(self, other):
  183. return SpecialOp('//', other, self)
  184. def __mod__(self, other):
  185. return SpecialOp('%', self, other)
  186. def __rmod__(self, other):
  187. return SpecialOp('%', other, self)
  188. def __divmod__(self, other):
  189. return SpecialOp('divmod', self, other)
  190. def __rdivmod__(self, other):
  191. return SpecialOp('divmod', other, self)
  192. def __pow__(self, other):
  193. return SpecialOp('**', self, other)
  194. def __rpow__(self, other):
  195. return SpecialOp('**', other, self)
  196. def __lt__(self, other):
  197. return SpecialOp('<', self, other)
  198. def __gt__(self, other):
  199. return SpecialOp('>', self, other)
  200. def __le__(self, other):
  201. return SpecialOp('<=', self, other)
  202. def __ge__(self, other):
  203. return SpecialOp('>=', self, other)
  204. class NonExpr(Basic, NonBasic):
  205. '''Like NonBasic above except this is a subclass of Basic but not Expr'''
  206. pass
  207. class SpecialOp():
  208. '''Represents the results of operations with NonBasic and NonExpr'''
  209. def __new__(cls, op, arg1, arg2):
  210. obj = object.__new__(cls)
  211. obj.args = (op, arg1, arg2)
  212. return obj
  213. class NonArithmetic(Basic):
  214. '''Represents a Basic subclass that does not support arithmetic operations'''
  215. pass
  216. def test_cooperative_operations():
  217. '''Tests that Expr uses binary operations cooperatively.
  218. In particular it should be possible for non-Expr classes to override
  219. binary operators like +, - etc when used with Expr instances. This should
  220. work for non-Expr classes whether they are Basic subclasses or not. Also
  221. non-Expr classes that do not define binary operators with Expr should give
  222. TypeError.
  223. '''
  224. # A bunch of instances of Expr subclasses
  225. exprs = [
  226. Expr(),
  227. S.Zero,
  228. S.One,
  229. S.Infinity,
  230. S.NegativeInfinity,
  231. S.ComplexInfinity,
  232. S.Half,
  233. Float(0.5),
  234. Integer(2),
  235. Symbol('x'),
  236. Mul(2, Symbol('x')),
  237. Add(2, Symbol('x')),
  238. Pow(2, Symbol('x')),
  239. ]
  240. for e in exprs:
  241. # Test that these classes can override arithmetic operations in
  242. # combination with various Expr types.
  243. for ne in [NonBasic(), NonExpr()]:
  244. results = [
  245. (ne + e, ('+', ne, e)),
  246. (e + ne, ('+', e, ne)),
  247. (ne - e, ('-', ne, e)),
  248. (e - ne, ('-', e, ne)),
  249. (ne * e, ('*', ne, e)),
  250. (e * ne, ('*', e, ne)),
  251. (ne / e, ('/', ne, e)),
  252. (e / ne, ('/', e, ne)),
  253. (ne // e, ('//', ne, e)),
  254. (e // ne, ('//', e, ne)),
  255. (ne % e, ('%', ne, e)),
  256. (e % ne, ('%', e, ne)),
  257. (divmod(ne, e), ('divmod', ne, e)),
  258. (divmod(e, ne), ('divmod', e, ne)),
  259. (ne ** e, ('**', ne, e)),
  260. (e ** ne, ('**', e, ne)),
  261. (e < ne, ('>', ne, e)),
  262. (ne < e, ('<', ne, e)),
  263. (e > ne, ('<', ne, e)),
  264. (ne > e, ('>', ne, e)),
  265. (e <= ne, ('>=', ne, e)),
  266. (ne <= e, ('<=', ne, e)),
  267. (e >= ne, ('<=', ne, e)),
  268. (ne >= e, ('>=', ne, e)),
  269. ]
  270. for res, args in results:
  271. assert type(res) is SpecialOp and res.args == args
  272. # These classes do not support binary operators with Expr. Every
  273. # operation should raise in combination with any of the Expr types.
  274. for na in [NonArithmetic(), object()]:
  275. raises(TypeError, lambda : e + na)
  276. raises(TypeError, lambda : na + e)
  277. raises(TypeError, lambda : e - na)
  278. raises(TypeError, lambda : na - e)
  279. raises(TypeError, lambda : e * na)
  280. raises(TypeError, lambda : na * e)
  281. raises(TypeError, lambda : e / na)
  282. raises(TypeError, lambda : na / e)
  283. raises(TypeError, lambda : e // na)
  284. raises(TypeError, lambda : na // e)
  285. raises(TypeError, lambda : e % na)
  286. raises(TypeError, lambda : na % e)
  287. raises(TypeError, lambda : divmod(e, na))
  288. raises(TypeError, lambda : divmod(na, e))
  289. raises(TypeError, lambda : e ** na)
  290. raises(TypeError, lambda : na ** e)
  291. raises(TypeError, lambda : e > na)
  292. raises(TypeError, lambda : na > e)
  293. raises(TypeError, lambda : e < na)
  294. raises(TypeError, lambda : na < e)
  295. raises(TypeError, lambda : e >= na)
  296. raises(TypeError, lambda : na >= e)
  297. raises(TypeError, lambda : e <= na)
  298. raises(TypeError, lambda : na <= e)
  299. def test_relational():
  300. from sympy.core.relational import Lt
  301. assert (pi < 3) is S.false
  302. assert (pi <= 3) is S.false
  303. assert (pi > 3) is S.true
  304. assert (pi >= 3) is S.true
  305. assert (-pi < 3) is S.true
  306. assert (-pi <= 3) is S.true
  307. assert (-pi > 3) is S.false
  308. assert (-pi >= 3) is S.false
  309. r = Symbol('r', real=True)
  310. assert (r - 2 < r - 3) is S.false
  311. assert Lt(x + I, x + I + 2).func == Lt # issue 8288
  312. def test_relational_assumptions():
  313. m1 = Symbol("m1", nonnegative=False)
  314. m2 = Symbol("m2", positive=False)
  315. m3 = Symbol("m3", nonpositive=False)
  316. m4 = Symbol("m4", negative=False)
  317. assert (m1 < 0) == Lt(m1, 0)
  318. assert (m2 <= 0) == Le(m2, 0)
  319. assert (m3 > 0) == Gt(m3, 0)
  320. assert (m4 >= 0) == Ge(m4, 0)
  321. m1 = Symbol("m1", nonnegative=False, real=True)
  322. m2 = Symbol("m2", positive=False, real=True)
  323. m3 = Symbol("m3", nonpositive=False, real=True)
  324. m4 = Symbol("m4", negative=False, real=True)
  325. assert (m1 < 0) is S.true
  326. assert (m2 <= 0) is S.true
  327. assert (m3 > 0) is S.true
  328. assert (m4 >= 0) is S.true
  329. m1 = Symbol("m1", negative=True)
  330. m2 = Symbol("m2", nonpositive=True)
  331. m3 = Symbol("m3", positive=True)
  332. m4 = Symbol("m4", nonnegative=True)
  333. assert (m1 < 0) is S.true
  334. assert (m2 <= 0) is S.true
  335. assert (m3 > 0) is S.true
  336. assert (m4 >= 0) is S.true
  337. m1 = Symbol("m1", negative=False, real=True)
  338. m2 = Symbol("m2", nonpositive=False, real=True)
  339. m3 = Symbol("m3", positive=False, real=True)
  340. m4 = Symbol("m4", nonnegative=False, real=True)
  341. assert (m1 < 0) is S.false
  342. assert (m2 <= 0) is S.false
  343. assert (m3 > 0) is S.false
  344. assert (m4 >= 0) is S.false
  345. # See https://github.com/sympy/sympy/issues/17708
  346. #def test_relational_noncommutative():
  347. # from sympy import Lt, Gt, Le, Ge
  348. # A, B = symbols('A,B', commutative=False)
  349. # assert (A < B) == Lt(A, B)
  350. # assert (A <= B) == Le(A, B)
  351. # assert (A > B) == Gt(A, B)
  352. # assert (A >= B) == Ge(A, B)
  353. def test_basic_nostr():
  354. for obj in basic_objs:
  355. raises(TypeError, lambda: obj + '1')
  356. raises(TypeError, lambda: obj - '1')
  357. if obj == 2:
  358. assert obj * '1' == '11'
  359. else:
  360. raises(TypeError, lambda: obj * '1')
  361. raises(TypeError, lambda: obj / '1')
  362. raises(TypeError, lambda: obj ** '1')
  363. def test_series_expansion_for_uniform_order():
  364. assert (1/x + y + x).series(x, 0, 0) == 1/x + O(1, x)
  365. assert (1/x + y + x).series(x, 0, 1) == 1/x + y + O(x)
  366. assert (1/x + 1 + x).series(x, 0, 0) == 1/x + O(1, x)
  367. assert (1/x + 1 + x).series(x, 0, 1) == 1/x + 1 + O(x)
  368. assert (1/x + x).series(x, 0, 0) == 1/x + O(1, x)
  369. assert (1/x + y + y*x + x).series(x, 0, 0) == 1/x + O(1, x)
  370. assert (1/x + y + y*x + x).series(x, 0, 1) == 1/x + y + O(x)
  371. def test_leadterm():
  372. assert (3 + 2*x**(log(3)/log(2) - 1)).leadterm(x) == (3, 0)
  373. assert (1/x**2 + 1 + x + x**2).leadterm(x)[1] == -2
  374. assert (1/x + 1 + x + x**2).leadterm(x)[1] == -1
  375. assert (x**2 + 1/x).leadterm(x)[1] == -1
  376. assert (1 + x**2).leadterm(x)[1] == 0
  377. assert (x + 1).leadterm(x)[1] == 0
  378. assert (x + x**2).leadterm(x)[1] == 1
  379. assert (x**2).leadterm(x)[1] == 2
  380. def test_as_leading_term():
  381. assert (3 + 2*x**(log(3)/log(2) - 1)).as_leading_term(x) == 3
  382. assert (1/x**2 + 1 + x + x**2).as_leading_term(x) == 1/x**2
  383. assert (1/x + 1 + x + x**2).as_leading_term(x) == 1/x
  384. assert (x**2 + 1/x).as_leading_term(x) == 1/x
  385. assert (1 + x**2).as_leading_term(x) == 1
  386. assert (x + 1).as_leading_term(x) == 1
  387. assert (x + x**2).as_leading_term(x) == x
  388. assert (x**2).as_leading_term(x) == x**2
  389. assert (x + oo).as_leading_term(x) is oo
  390. raises(ValueError, lambda: (x + 1).as_leading_term(1))
  391. # https://github.com/sympy/sympy/issues/21177
  392. e = -3*x + (x + Rational(3, 2) - sqrt(3)*S.ImaginaryUnit/2)**2\
  393. - Rational(3, 2) + 3*sqrt(3)*S.ImaginaryUnit/2
  394. assert e.as_leading_term(x) == \
  395. (12*sqrt(3)*x - 12*S.ImaginaryUnit*x)/(4*sqrt(3) + 12*S.ImaginaryUnit)
  396. # https://github.com/sympy/sympy/issues/21245
  397. e = 1 - x - x**2
  398. d = (1 + sqrt(5))/2
  399. assert e.subs(x, y + 1/d).as_leading_term(y) == \
  400. (-576*sqrt(5)*y - 1280*y)/(256*sqrt(5) + 576)
  401. def test_leadterm2():
  402. assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).leadterm(x) == \
  403. (sin(1 + sin(1)), 0)
  404. def test_leadterm3():
  405. assert (y + z + x).leadterm(x) == (y + z, 0)
  406. def test_as_leading_term2():
  407. assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).as_leading_term(x) == \
  408. sin(1 + sin(1))
  409. def test_as_leading_term3():
  410. assert (2 + pi + x).as_leading_term(x) == 2 + pi
  411. assert (2*x + pi*x + x**2).as_leading_term(x) == 2*x + pi*x
  412. def test_as_leading_term4():
  413. # see issue 6843
  414. n = Symbol('n', integer=True, positive=True)
  415. r = -n**3/(2*n**2 + 4*n + 2) - n**2/(n**2 + 2*n + 1) + \
  416. n**2/(n + 1) - n/(2*n**2 + 4*n + 2) + n/(n*x + x) + 2*n/(n + 1) - \
  417. 1 + 1/(n*x + x) + 1/(n + 1) - 1/x
  418. assert r.as_leading_term(x).cancel() == n/2
  419. def test_as_leading_term_stub():
  420. class foo(Function):
  421. pass
  422. assert foo(1/x).as_leading_term(x) == foo(1/x)
  423. assert foo(1).as_leading_term(x) == foo(1)
  424. raises(NotImplementedError, lambda: foo(x).as_leading_term(x))
  425. def test_as_leading_term_deriv_integral():
  426. # related to issue 11313
  427. assert Derivative(x ** 3, x).as_leading_term(x) == 3*x**2
  428. assert Derivative(x ** 3, y).as_leading_term(x) == 0
  429. assert Integral(x ** 3, x).as_leading_term(x) == x**4/4
  430. assert Integral(x ** 3, y).as_leading_term(x) == y*x**3
  431. assert Derivative(exp(x), x).as_leading_term(x) == 1
  432. assert Derivative(log(x), x).as_leading_term(x) == (1/x).as_leading_term(x)
  433. def test_atoms():
  434. assert x.atoms() == {x}
  435. assert (1 + x).atoms() == {x, S.One}
  436. assert (1 + 2*cos(x)).atoms(Symbol) == {x}
  437. assert (1 + 2*cos(x)).atoms(Symbol, Number) == {S.One, S(2), x}
  438. assert (2*(x**(y**x))).atoms() == {S(2), x, y}
  439. assert S.Half.atoms() == {S.Half}
  440. assert S.Half.atoms(Symbol) == set()
  441. assert sin(oo).atoms(oo) == set()
  442. assert Poly(0, x).atoms() == {S.Zero, x}
  443. assert Poly(1, x).atoms() == {S.One, x}
  444. assert Poly(x, x).atoms() == {x}
  445. assert Poly(x, x, y).atoms() == {x, y}
  446. assert Poly(x + y, x, y).atoms() == {x, y}
  447. assert Poly(x + y, x, y, z).atoms() == {x, y, z}
  448. assert Poly(x + y*t, x, y, z).atoms() == {t, x, y, z}
  449. assert (I*pi).atoms(NumberSymbol) == {pi}
  450. assert (I*pi).atoms(NumberSymbol, I) == \
  451. (I*pi).atoms(I, NumberSymbol) == {pi, I}
  452. assert exp(exp(x)).atoms(exp) == {exp(exp(x)), exp(x)}
  453. assert (1 + x*(2 + y) + exp(3 + z)).atoms(Add) == \
  454. {1 + x*(2 + y) + exp(3 + z), 2 + y, 3 + z}
  455. # issue 6132
  456. e = (f(x) + sin(x) + 2)
  457. assert e.atoms(AppliedUndef) == \
  458. {f(x)}
  459. assert e.atoms(AppliedUndef, Function) == \
  460. {f(x), sin(x)}
  461. assert e.atoms(Function) == \
  462. {f(x), sin(x)}
  463. assert e.atoms(AppliedUndef, Number) == \
  464. {f(x), S(2)}
  465. assert e.atoms(Function, Number) == \
  466. {S(2), sin(x), f(x)}
  467. def test_is_polynomial():
  468. k = Symbol('k', nonnegative=True, integer=True)
  469. assert Rational(2).is_polynomial(x, y, z) is True
  470. assert (S.Pi).is_polynomial(x, y, z) is True
  471. assert x.is_polynomial(x) is True
  472. assert x.is_polynomial(y) is True
  473. assert (x**2).is_polynomial(x) is True
  474. assert (x**2).is_polynomial(y) is True
  475. assert (x**(-2)).is_polynomial(x) is False
  476. assert (x**(-2)).is_polynomial(y) is True
  477. assert (2**x).is_polynomial(x) is False
  478. assert (2**x).is_polynomial(y) is True
  479. assert (x**k).is_polynomial(x) is False
  480. assert (x**k).is_polynomial(k) is False
  481. assert (x**x).is_polynomial(x) is False
  482. assert (k**k).is_polynomial(k) is False
  483. assert (k**x).is_polynomial(k) is False
  484. assert (x**(-k)).is_polynomial(x) is False
  485. assert ((2*x)**k).is_polynomial(x) is False
  486. assert (x**2 + 3*x - 8).is_polynomial(x) is True
  487. assert (x**2 + 3*x - 8).is_polynomial(y) is True
  488. assert (x**2 + 3*x - 8).is_polynomial() is True
  489. assert sqrt(x).is_polynomial(x) is False
  490. assert (sqrt(x)**3).is_polynomial(x) is False
  491. assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(x) is True
  492. assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(y) is False
  493. assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial() is True
  494. assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial() is False
  495. assert (
  496. (x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial(x, y) is True
  497. assert (
  498. (x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial(x, y) is False
  499. assert (1/f(x) + 1).is_polynomial(f(x)) is False
  500. def test_is_rational_function():
  501. assert Integer(1).is_rational_function() is True
  502. assert Integer(1).is_rational_function(x) is True
  503. assert Rational(17, 54).is_rational_function() is True
  504. assert Rational(17, 54).is_rational_function(x) is True
  505. assert (12/x).is_rational_function() is True
  506. assert (12/x).is_rational_function(x) is True
  507. assert (x/y).is_rational_function() is True
  508. assert (x/y).is_rational_function(x) is True
  509. assert (x/y).is_rational_function(x, y) is True
  510. assert (x**2 + 1/x/y).is_rational_function() is True
  511. assert (x**2 + 1/x/y).is_rational_function(x) is True
  512. assert (x**2 + 1/x/y).is_rational_function(x, y) is True
  513. assert (sin(y)/x).is_rational_function() is False
  514. assert (sin(y)/x).is_rational_function(y) is False
  515. assert (sin(y)/x).is_rational_function(x) is True
  516. assert (sin(y)/x).is_rational_function(x, y) is False
  517. for i in _illegal:
  518. assert not i.is_rational_function()
  519. for d in (1, x):
  520. assert not (i/d).is_rational_function()
  521. def test_is_meromorphic():
  522. f = a/x**2 + b + x + c*x**2
  523. assert f.is_meromorphic(x, 0) is True
  524. assert f.is_meromorphic(x, 1) is True
  525. assert f.is_meromorphic(x, zoo) is True
  526. g = 3 + 2*x**(log(3)/log(2) - 1)
  527. assert g.is_meromorphic(x, 0) is False
  528. assert g.is_meromorphic(x, 1) is True
  529. assert g.is_meromorphic(x, zoo) is False
  530. n = Symbol('n', integer=True)
  531. e = sin(1/x)**n*x
  532. assert e.is_meromorphic(x, 0) is False
  533. assert e.is_meromorphic(x, 1) is True
  534. assert e.is_meromorphic(x, zoo) is False
  535. e = log(x)**pi
  536. assert e.is_meromorphic(x, 0) is False
  537. assert e.is_meromorphic(x, 1) is False
  538. assert e.is_meromorphic(x, 2) is True
  539. assert e.is_meromorphic(x, zoo) is False
  540. assert (log(x)**a).is_meromorphic(x, 0) is False
  541. assert (log(x)**a).is_meromorphic(x, 1) is False
  542. assert (a**log(x)).is_meromorphic(x, 0) is None
  543. assert (3**log(x)).is_meromorphic(x, 0) is False
  544. assert (3**log(x)).is_meromorphic(x, 1) is True
  545. def test_is_algebraic_expr():
  546. assert sqrt(3).is_algebraic_expr(x) is True
  547. assert sqrt(3).is_algebraic_expr() is True
  548. eq = ((1 + x**2)/(1 - y**2))**(S.One/3)
  549. assert eq.is_algebraic_expr(x) is True
  550. assert eq.is_algebraic_expr(y) is True
  551. assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr(x) is True
  552. assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr(y) is True
  553. assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr() is True
  554. assert (cos(y)/sqrt(x)).is_algebraic_expr() is False
  555. assert (cos(y)/sqrt(x)).is_algebraic_expr(x) is True
  556. assert (cos(y)/sqrt(x)).is_algebraic_expr(y) is False
  557. assert (cos(y)/sqrt(x)).is_algebraic_expr(x, y) is False
  558. def test_SAGE1():
  559. #see https://github.com/sympy/sympy/issues/3346
  560. class MyInt:
  561. def _sympy_(self):
  562. return Integer(5)
  563. m = MyInt()
  564. e = Rational(2)*m
  565. assert e == 10
  566. raises(TypeError, lambda: Rational(2)*MyInt)
  567. def test_SAGE2():
  568. class MyInt:
  569. def __int__(self):
  570. return 5
  571. assert sympify(MyInt()) == 5
  572. e = Rational(2)*MyInt()
  573. assert e == 10
  574. raises(TypeError, lambda: Rational(2)*MyInt)
  575. def test_SAGE3():
  576. class MySymbol:
  577. def __rmul__(self, other):
  578. return ('mys', other, self)
  579. o = MySymbol()
  580. e = x*o
  581. assert e == ('mys', x, o)
  582. def test_len():
  583. e = x*y
  584. assert len(e.args) == 2
  585. e = x + y + z
  586. assert len(e.args) == 3
  587. def test_doit():
  588. a = Integral(x**2, x)
  589. assert isinstance(a.doit(), Integral) is False
  590. assert isinstance(a.doit(integrals=True), Integral) is False
  591. assert isinstance(a.doit(integrals=False), Integral) is True
  592. assert (2*Integral(x, x)).doit() == x**2
  593. def test_attribute_error():
  594. raises(AttributeError, lambda: x.cos())
  595. raises(AttributeError, lambda: x.sin())
  596. raises(AttributeError, lambda: x.exp())
  597. def test_args():
  598. assert (x*y).args in ((x, y), (y, x))
  599. assert (x + y).args in ((x, y), (y, x))
  600. assert (x*y + 1).args in ((x*y, 1), (1, x*y))
  601. assert sin(x*y).args == (x*y,)
  602. assert sin(x*y).args[0] == x*y
  603. assert (x**y).args == (x, y)
  604. assert (x**y).args[0] == x
  605. assert (x**y).args[1] == y
  606. def test_noncommutative_expand_issue_3757():
  607. A, B, C = symbols('A,B,C', commutative=False)
  608. assert A*B - B*A != 0
  609. assert (A*(A + B)*B).expand() == A**2*B + A*B**2
  610. assert (A*(A + B + C)*B).expand() == A**2*B + A*B**2 + A*C*B
  611. def test_as_numer_denom():
  612. a, b, c = symbols('a, b, c')
  613. assert nan.as_numer_denom() == (nan, 1)
  614. assert oo.as_numer_denom() == (oo, 1)
  615. assert (-oo).as_numer_denom() == (-oo, 1)
  616. assert zoo.as_numer_denom() == (zoo, 1)
  617. assert (-zoo).as_numer_denom() == (zoo, 1)
  618. assert x.as_numer_denom() == (x, 1)
  619. assert (1/x).as_numer_denom() == (1, x)
  620. assert (x/y).as_numer_denom() == (x, y)
  621. assert (x/2).as_numer_denom() == (x, 2)
  622. assert (x*y/z).as_numer_denom() == (x*y, z)
  623. assert (x/(y*z)).as_numer_denom() == (x, y*z)
  624. assert S.Half.as_numer_denom() == (1, 2)
  625. assert (1/y**2).as_numer_denom() == (1, y**2)
  626. assert (x/y**2).as_numer_denom() == (x, y**2)
  627. assert ((x**2 + 1)/y).as_numer_denom() == (x**2 + 1, y)
  628. assert (x*(y + 1)/y**7).as_numer_denom() == (x*(y + 1), y**7)
  629. assert (x**-2).as_numer_denom() == (1, x**2)
  630. assert (a/x + b/2/x + c/3/x).as_numer_denom() == \
  631. (6*a + 3*b + 2*c, 6*x)
  632. assert (a/x + b/2/x + c/3/y).as_numer_denom() == \
  633. (2*c*x + y*(6*a + 3*b), 6*x*y)
  634. assert (a/x + b/2/x + c/.5/x).as_numer_denom() == \
  635. (2*a + b + 4.0*c, 2*x)
  636. # this should take no more than a few seconds
  637. assert int(log(Add(*[Dummy()/i/x for i in range(1, 705)]
  638. ).as_numer_denom()[1]/x).n(4)) == 705
  639. for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
  640. assert (i + x/3).as_numer_denom() == \
  641. (x + i, 3)
  642. assert (S.Infinity + x/3 + y/4).as_numer_denom() == \
  643. (4*x + 3*y + S.Infinity, 12)
  644. assert (oo*x + zoo*y).as_numer_denom() == \
  645. (zoo*y + oo*x, 1)
  646. A, B, C = symbols('A,B,C', commutative=False)
  647. assert (A*B*C**-1).as_numer_denom() == (A*B*C**-1, 1)
  648. assert (A*B*C**-1/x).as_numer_denom() == (A*B*C**-1, x)
  649. assert (C**-1*A*B).as_numer_denom() == (C**-1*A*B, 1)
  650. assert (C**-1*A*B/x).as_numer_denom() == (C**-1*A*B, x)
  651. assert ((A*B*C)**-1).as_numer_denom() == ((A*B*C)**-1, 1)
  652. assert ((A*B*C)**-1/x).as_numer_denom() == ((A*B*C)**-1, x)
  653. # the following morphs from Add to Mul during processing
  654. assert Add(0, (x + y)/z/-2, evaluate=False).as_numer_denom(
  655. ) == (-x - y, 2*z)
  656. def test_trunc():
  657. import math
  658. x, y = symbols('x y')
  659. assert math.trunc(2) == 2
  660. assert math.trunc(4.57) == 4
  661. assert math.trunc(-5.79) == -5
  662. assert math.trunc(pi) == 3
  663. assert math.trunc(log(7)) == 1
  664. assert math.trunc(exp(5)) == 148
  665. assert math.trunc(cos(pi)) == -1
  666. assert math.trunc(sin(5)) == 0
  667. raises(TypeError, lambda: math.trunc(x))
  668. raises(TypeError, lambda: math.trunc(x + y**2))
  669. raises(TypeError, lambda: math.trunc(oo))
  670. def test_as_independent():
  671. assert S.Zero.as_independent(x, as_Add=True) == (0, 0)
  672. assert S.Zero.as_independent(x, as_Add=False) == (0, 0)
  673. assert (2*x*sin(x) + y + x).as_independent(x) == (y, x + 2*x*sin(x))
  674. assert (2*x*sin(x) + y + x).as_independent(y) == (x + 2*x*sin(x), y)
  675. assert (2*x*sin(x) + y + x).as_independent(x, y) == (0, y + x + 2*x*sin(x))
  676. assert (x*sin(x)*cos(y)).as_independent(x) == (cos(y), x*sin(x))
  677. assert (x*sin(x)*cos(y)).as_independent(y) == (x*sin(x), cos(y))
  678. assert (x*sin(x)*cos(y)).as_independent(x, y) == (1, x*sin(x)*cos(y))
  679. assert (sin(x)).as_independent(x) == (1, sin(x))
  680. assert (sin(x)).as_independent(y) == (sin(x), 1)
  681. assert (2*sin(x)).as_independent(x) == (2, sin(x))
  682. assert (2*sin(x)).as_independent(y) == (2*sin(x), 1)
  683. # issue 4903 = 1766b
  684. n1, n2, n3 = symbols('n1 n2 n3', commutative=False)
  685. assert (n1 + n1*n2).as_independent(n2) == (n1, n1*n2)
  686. assert (n2*n1 + n1*n2).as_independent(n2) == (0, n1*n2 + n2*n1)
  687. assert (n1*n2*n1).as_independent(n2) == (n1, n2*n1)
  688. assert (n1*n2*n1).as_independent(n1) == (1, n1*n2*n1)
  689. assert (3*x).as_independent(x, as_Add=True) == (0, 3*x)
  690. assert (3*x).as_independent(x, as_Add=False) == (3, x)
  691. assert (3 + x).as_independent(x, as_Add=True) == (3, x)
  692. assert (3 + x).as_independent(x, as_Add=False) == (1, 3 + x)
  693. # issue 5479
  694. assert (3*x).as_independent(Symbol) == (3, x)
  695. # issue 5648
  696. assert (n1*x*y).as_independent(x) == (n1*y, x)
  697. assert ((x + n1)*(x - y)).as_independent(x) == (1, (x + n1)*(x - y))
  698. assert ((x + n1)*(x - y)).as_independent(y) == (x + n1, x - y)
  699. assert (DiracDelta(x - n1)*DiracDelta(x - y)).as_independent(x) \
  700. == (1, DiracDelta(x - n1)*DiracDelta(x - y))
  701. assert (x*y*n1*n2*n3).as_independent(n2) == (x*y*n1, n2*n3)
  702. assert (x*y*n1*n2*n3).as_independent(n1) == (x*y, n1*n2*n3)
  703. assert (x*y*n1*n2*n3).as_independent(n3) == (x*y*n1*n2, n3)
  704. assert (DiracDelta(x - n1)*DiracDelta(y - n1)*DiracDelta(x - n2)).as_independent(y) == \
  705. (DiracDelta(x - n1)*DiracDelta(x - n2), DiracDelta(y - n1))
  706. # issue 5784
  707. assert (x + Integral(x, (x, 1, 2))).as_independent(x, strict=True) == \
  708. (Integral(x, (x, 1, 2)), x)
  709. eq = Add(x, -x, 2, -3, evaluate=False)
  710. assert eq.as_independent(x) == (-1, Add(x, -x, evaluate=False))
  711. eq = Mul(x, 1/x, 2, -3, evaluate=False)
  712. assert eq.as_independent(x) == (-6, Mul(x, 1/x, evaluate=False))
  713. assert (x*y).as_independent(z, as_Add=True) == (x*y, 0)
  714. @XFAIL
  715. def test_call_2():
  716. # TODO UndefinedFunction does not subclass Expr
  717. assert (2*f)(x) == 2*f(x)
  718. def test_replace():
  719. e = log(sin(x)) + tan(sin(x**2))
  720. assert e.replace(sin, cos) == log(cos(x)) + tan(cos(x**2))
  721. assert e.replace(
  722. sin, lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2))
  723. a = Wild('a')
  724. b = Wild('b')
  725. assert e.replace(sin(a), cos(a)) == log(cos(x)) + tan(cos(x**2))
  726. assert e.replace(
  727. sin(a), lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2))
  728. # test exact
  729. assert (2*x).replace(a*x + b, b - a, exact=True) == 2*x
  730. assert (2*x).replace(a*x + b, b - a) == 2*x
  731. assert (2*x).replace(a*x + b, b - a, exact=False) == 2/x
  732. assert (2*x).replace(a*x + b, lambda a, b: b - a, exact=True) == 2*x
  733. assert (2*x).replace(a*x + b, lambda a, b: b - a) == 2*x
  734. assert (2*x).replace(a*x + b, lambda a, b: b - a, exact=False) == 2/x
  735. g = 2*sin(x**3)
  736. assert g.replace(
  737. lambda expr: expr.is_Number, lambda expr: expr**2) == 4*sin(x**9)
  738. assert cos(x).replace(cos, sin, map=True) == (sin(x), {cos(x): sin(x)})
  739. assert sin(x).replace(cos, sin) == sin(x)
  740. cond, func = lambda x: x.is_Mul, lambda x: 2*x
  741. assert (x*y).replace(cond, func, map=True) == (2*x*y, {x*y: 2*x*y})
  742. assert (x*(1 + x*y)).replace(cond, func, map=True) == \
  743. (2*x*(2*x*y + 1), {x*(2*x*y + 1): 2*x*(2*x*y + 1), x*y: 2*x*y})
  744. assert (y*sin(x)).replace(sin, lambda expr: sin(expr)/y, map=True) == \
  745. (sin(x), {sin(x): sin(x)/y})
  746. # if not simultaneous then y*sin(x) -> y*sin(x)/y = sin(x) -> sin(x)/y
  747. assert (y*sin(x)).replace(sin, lambda expr: sin(expr)/y,
  748. simultaneous=False) == sin(x)/y
  749. assert (x**2 + O(x**3)).replace(Pow, lambda b, e: b**e/e
  750. ) == x**2/2 + O(x**3)
  751. assert (x**2 + O(x**3)).replace(Pow, lambda b, e: b**e/e,
  752. simultaneous=False) == x**2/2 + O(x**3)
  753. assert (x*(x*y + 3)).replace(lambda x: x.is_Mul, lambda x: 2 + x) == \
  754. x*(x*y + 5) + 2
  755. e = (x*y + 1)*(2*x*y + 1) + 1
  756. assert e.replace(cond, func, map=True) == (
  757. 2*((2*x*y + 1)*(4*x*y + 1)) + 1,
  758. {2*x*y: 4*x*y, x*y: 2*x*y, (2*x*y + 1)*(4*x*y + 1):
  759. 2*((2*x*y + 1)*(4*x*y + 1))})
  760. assert x.replace(x, y) == y
  761. assert (x + 1).replace(1, 2) == x + 2
  762. # https://groups.google.com/forum/#!topic/sympy/8wCgeC95tz0
  763. n1, n2, n3 = symbols('n1:4', commutative=False)
  764. assert (n1*f(n2)).replace(f, lambda x: x) == n1*n2
  765. assert (n3*f(n2)).replace(f, lambda x: x) == n3*n2
  766. # issue 16725
  767. assert S.Zero.replace(Wild('x'), 1) == 1
  768. # let the user override the default decision of False
  769. assert S.Zero.replace(Wild('x'), 1, exact=True) == 0
  770. def test_find():
  771. expr = (x + y + 2 + sin(3*x))
  772. assert expr.find(lambda u: u.is_Integer) == {S(2), S(3)}
  773. assert expr.find(lambda u: u.is_Symbol) == {x, y}
  774. assert expr.find(lambda u: u.is_Integer, group=True) == {S(2): 1, S(3): 1}
  775. assert expr.find(lambda u: u.is_Symbol, group=True) == {x: 2, y: 1}
  776. assert expr.find(Integer) == {S(2), S(3)}
  777. assert expr.find(Symbol) == {x, y}
  778. assert expr.find(Integer, group=True) == {S(2): 1, S(3): 1}
  779. assert expr.find(Symbol, group=True) == {x: 2, y: 1}
  780. a = Wild('a')
  781. expr = sin(sin(x)) + sin(x) + cos(x) + x
  782. assert expr.find(lambda u: type(u) is sin) == {sin(x), sin(sin(x))}
  783. assert expr.find(
  784. lambda u: type(u) is sin, group=True) == {sin(x): 2, sin(sin(x)): 1}
  785. assert expr.find(sin(a)) == {sin(x), sin(sin(x))}
  786. assert expr.find(sin(a), group=True) == {sin(x): 2, sin(sin(x)): 1}
  787. assert expr.find(sin) == {sin(x), sin(sin(x))}
  788. assert expr.find(sin, group=True) == {sin(x): 2, sin(sin(x)): 1}
  789. def test_count():
  790. expr = (x + y + 2 + sin(3*x))
  791. assert expr.count(lambda u: u.is_Integer) == 2
  792. assert expr.count(lambda u: u.is_Symbol) == 3
  793. assert expr.count(Integer) == 2
  794. assert expr.count(Symbol) == 3
  795. assert expr.count(2) == 1
  796. a = Wild('a')
  797. assert expr.count(sin) == 1
  798. assert expr.count(sin(a)) == 1
  799. assert expr.count(lambda u: type(u) is sin) == 1
  800. assert f(x).count(f(x)) == 1
  801. assert f(x).diff(x).count(f(x)) == 1
  802. assert f(x).diff(x).count(x) == 2
  803. def test_has_basics():
  804. p = Wild('p')
  805. assert sin(x).has(x)
  806. assert sin(x).has(sin)
  807. assert not sin(x).has(y)
  808. assert not sin(x).has(cos)
  809. assert f(x).has(x)
  810. assert f(x).has(f)
  811. assert not f(x).has(y)
  812. assert not f(x).has(g)
  813. assert f(x).diff(x).has(x)
  814. assert f(x).diff(x).has(f)
  815. assert f(x).diff(x).has(Derivative)
  816. assert not f(x).diff(x).has(y)
  817. assert not f(x).diff(x).has(g)
  818. assert not f(x).diff(x).has(sin)
  819. assert (x**2).has(Symbol)
  820. assert not (x**2).has(Wild)
  821. assert (2*p).has(Wild)
  822. assert not x.has()
  823. def test_has_multiple():
  824. f = x**2*y + sin(2**t + log(z))
  825. assert f.has(x)
  826. assert f.has(y)
  827. assert f.has(z)
  828. assert f.has(t)
  829. assert not f.has(u)
  830. assert f.has(x, y, z, t)
  831. assert f.has(x, y, z, t, u)
  832. i = Integer(4400)
  833. assert not i.has(x)
  834. assert (i*x**i).has(x)
  835. assert not (i*y**i).has(x)
  836. assert (i*y**i).has(x, y)
  837. assert not (i*y**i).has(x, z)
  838. def test_has_piecewise():
  839. f = (x*y + 3/y)**(3 + 2)
  840. p = Piecewise((g(x), x < -1), (1, x <= 1), (f, True))
  841. assert p.has(x)
  842. assert p.has(y)
  843. assert not p.has(z)
  844. assert p.has(1)
  845. assert p.has(3)
  846. assert not p.has(4)
  847. assert p.has(f)
  848. assert p.has(g)
  849. assert not p.has(h)
  850. def test_has_iterative():
  851. A, B, C = symbols('A,B,C', commutative=False)
  852. f = x*gamma(x)*sin(x)*exp(x*y)*A*B*C*cos(x*A*B)
  853. assert f.has(x)
  854. assert f.has(x*y)
  855. assert f.has(x*sin(x))
  856. assert not f.has(x*sin(y))
  857. assert f.has(x*A)
  858. assert f.has(x*A*B)
  859. assert not f.has(x*A*C)
  860. assert f.has(x*A*B*C)
  861. assert not f.has(x*A*C*B)
  862. assert f.has(x*sin(x)*A*B*C)
  863. assert not f.has(x*sin(x)*A*C*B)
  864. assert not f.has(x*sin(y)*A*B*C)
  865. assert f.has(x*gamma(x))
  866. assert not f.has(x + sin(x))
  867. assert (x & y & z).has(x & z)
  868. def test_has_integrals():
  869. f = Integral(x**2 + sin(x*y*z), (x, 0, x + y + z))
  870. assert f.has(x + y)
  871. assert f.has(x + z)
  872. assert f.has(y + z)
  873. assert f.has(x*y)
  874. assert f.has(x*z)
  875. assert f.has(y*z)
  876. assert not f.has(2*x + y)
  877. assert not f.has(2*x*y)
  878. def test_has_tuple():
  879. assert Tuple(x, y).has(x)
  880. assert not Tuple(x, y).has(z)
  881. assert Tuple(f(x), g(x)).has(x)
  882. assert not Tuple(f(x), g(x)).has(y)
  883. assert Tuple(f(x), g(x)).has(f)
  884. assert Tuple(f(x), g(x)).has(f(x))
  885. # XXX to be deprecated
  886. #assert not Tuple(f, g).has(x)
  887. #assert Tuple(f, g).has(f)
  888. #assert not Tuple(f, g).has(h)
  889. assert Tuple(True).has(True)
  890. assert Tuple(True).has(S.true)
  891. assert not Tuple(True).has(1)
  892. def test_has_units():
  893. from sympy.physics.units import m, s
  894. assert (x*m/s).has(x)
  895. assert (x*m/s).has(y, z) is False
  896. def test_has_polys():
  897. poly = Poly(x**2 + x*y*sin(z), x, y, t)
  898. assert poly.has(x)
  899. assert poly.has(x, y, z)
  900. assert poly.has(x, y, z, t)
  901. def test_has_physics():
  902. assert FockState((x, y)).has(x)
  903. def test_as_poly_as_expr():
  904. f = x**2 + 2*x*y
  905. assert f.as_poly().as_expr() == f
  906. assert f.as_poly(x, y).as_expr() == f
  907. assert (f + sin(x)).as_poly(x, y) is None
  908. p = Poly(f, x, y)
  909. assert p.as_poly() == p
  910. # https://github.com/sympy/sympy/issues/20610
  911. assert S(2).as_poly() is None
  912. assert sqrt(2).as_poly(extension=True) is None
  913. raises(AttributeError, lambda: Tuple(x, x).as_poly(x))
  914. raises(AttributeError, lambda: Tuple(x ** 2, x, y).as_poly(x))
  915. def test_nonzero():
  916. assert bool(S.Zero) is False
  917. assert bool(S.One) is True
  918. assert bool(x) is True
  919. assert bool(x + y) is True
  920. assert bool(x - x) is False
  921. assert bool(x*y) is True
  922. assert bool(x*1) is True
  923. assert bool(x*0) is False
  924. def test_is_number():
  925. assert Float(3.14).is_number is True
  926. assert Integer(737).is_number is True
  927. assert Rational(3, 2).is_number is True
  928. assert Rational(8).is_number is True
  929. assert x.is_number is False
  930. assert (2*x).is_number is False
  931. assert (x + y).is_number is False
  932. assert log(2).is_number is True
  933. assert log(x).is_number is False
  934. assert (2 + log(2)).is_number is True
  935. assert (8 + log(2)).is_number is True
  936. assert (2 + log(x)).is_number is False
  937. assert (8 + log(2) + x).is_number is False
  938. assert (1 + x**2/x - x).is_number is True
  939. assert Tuple(Integer(1)).is_number is False
  940. assert Add(2, x).is_number is False
  941. assert Mul(3, 4).is_number is True
  942. assert Pow(log(2), 2).is_number is True
  943. assert oo.is_number is True
  944. g = WildFunction('g')
  945. assert g.is_number is False
  946. assert (2*g).is_number is False
  947. assert (x**2).subs(x, 3).is_number is True
  948. # test extensibility of .is_number
  949. # on subinstances of Basic
  950. class A(Basic):
  951. pass
  952. a = A()
  953. assert a.is_number is False
  954. def test_as_coeff_add():
  955. assert S(2).as_coeff_add() == (2, ())
  956. assert S(3.0).as_coeff_add() == (0, (S(3.0),))
  957. assert S(-3.0).as_coeff_add() == (0, (S(-3.0),))
  958. assert x.as_coeff_add() == (0, (x,))
  959. assert (x - 1).as_coeff_add() == (-1, (x,))
  960. assert (x + 1).as_coeff_add() == (1, (x,))
  961. assert (x + 2).as_coeff_add() == (2, (x,))
  962. assert (x + y).as_coeff_add(y) == (x, (y,))
  963. assert (3*x).as_coeff_add(y) == (3*x, ())
  964. # don't do expansion
  965. e = (x + y)**2
  966. assert e.as_coeff_add(y) == (0, (e,))
  967. def test_as_coeff_mul():
  968. assert S(2).as_coeff_mul() == (2, ())
  969. assert S(3.0).as_coeff_mul() == (1, (S(3.0),))
  970. assert S(-3.0).as_coeff_mul() == (-1, (S(3.0),))
  971. assert S(-3.0).as_coeff_mul(rational=False) == (-S(3.0), ())
  972. assert x.as_coeff_mul() == (1, (x,))
  973. assert (-x).as_coeff_mul() == (-1, (x,))
  974. assert (2*x).as_coeff_mul() == (2, (x,))
  975. assert (x*y).as_coeff_mul(y) == (x, (y,))
  976. assert (3 + x).as_coeff_mul() == (1, (3 + x,))
  977. assert (3 + x).as_coeff_mul(y) == (3 + x, ())
  978. # don't do expansion
  979. e = exp(x + y)
  980. assert e.as_coeff_mul(y) == (1, (e,))
  981. e = 2**(x + y)
  982. assert e.as_coeff_mul(y) == (1, (e,))
  983. assert (1.1*x).as_coeff_mul(rational=False) == (1.1, (x,))
  984. assert (1.1*x).as_coeff_mul() == (1, (1.1, x))
  985. assert (-oo*x).as_coeff_mul(rational=True) == (-1, (oo, x))
  986. def test_as_coeff_exponent():
  987. assert (3*x**4).as_coeff_exponent(x) == (3, 4)
  988. assert (2*x**3).as_coeff_exponent(x) == (2, 3)
  989. assert (4*x**2).as_coeff_exponent(x) == (4, 2)
  990. assert (6*x**1).as_coeff_exponent(x) == (6, 1)
  991. assert (3*x**0).as_coeff_exponent(x) == (3, 0)
  992. assert (2*x**0).as_coeff_exponent(x) == (2, 0)
  993. assert (1*x**0).as_coeff_exponent(x) == (1, 0)
  994. assert (0*x**0).as_coeff_exponent(x) == (0, 0)
  995. assert (-1*x**0).as_coeff_exponent(x) == (-1, 0)
  996. assert (-2*x**0).as_coeff_exponent(x) == (-2, 0)
  997. assert (2*x**3 + pi*x**3).as_coeff_exponent(x) == (2 + pi, 3)
  998. assert (x*log(2)/(2*x + pi*x)).as_coeff_exponent(x) == \
  999. (log(2)/(2 + pi), 0)
  1000. # issue 4784
  1001. D = Derivative
  1002. fx = D(f(x), x)
  1003. assert fx.as_coeff_exponent(f(x)) == (fx, 0)
  1004. def test_extractions():
  1005. for base in (2, S.Exp1):
  1006. assert Pow(base**x, 3, evaluate=False
  1007. ).extract_multiplicatively(base**x) == base**(2*x)
  1008. assert (base**(5*x)).extract_multiplicatively(
  1009. base**(3*x)) == base**(2*x)
  1010. assert ((x*y)**3).extract_multiplicatively(x**2 * y) == x*y**2
  1011. assert ((x*y)**3).extract_multiplicatively(x**4 * y) is None
  1012. assert (2*x).extract_multiplicatively(2) == x
  1013. assert (2*x).extract_multiplicatively(3) is None
  1014. assert (2*x).extract_multiplicatively(-1) is None
  1015. assert (S.Half*x).extract_multiplicatively(3) == x/6
  1016. assert (sqrt(x)).extract_multiplicatively(x) is None
  1017. assert (sqrt(x)).extract_multiplicatively(1/x) is None
  1018. assert x.extract_multiplicatively(-x) is None
  1019. assert (-2 - 4*I).extract_multiplicatively(-2) == 1 + 2*I
  1020. assert (-2 - 4*I).extract_multiplicatively(3) is None
  1021. assert (-2*x - 4*y - 8).extract_multiplicatively(-2) == x + 2*y + 4
  1022. assert (-2*x*y - 4*x**2*y).extract_multiplicatively(-2*y) == 2*x**2 + x
  1023. assert (2*x*y + 4*x**2*y).extract_multiplicatively(2*y) == 2*x**2 + x
  1024. assert (-4*y**2*x).extract_multiplicatively(-3*y) is None
  1025. assert (2*x).extract_multiplicatively(1) == 2*x
  1026. assert (-oo).extract_multiplicatively(5) is -oo
  1027. assert (oo).extract_multiplicatively(5) is oo
  1028. assert ((x*y)**3).extract_additively(1) is None
  1029. assert (x + 1).extract_additively(x) == 1
  1030. assert (x + 1).extract_additively(2*x) is None
  1031. assert (x + 1).extract_additively(-x) is None
  1032. assert (-x + 1).extract_additively(2*x) is None
  1033. assert (2*x + 3).extract_additively(x) == x + 3
  1034. assert (2*x + 3).extract_additively(2) == 2*x + 1
  1035. assert (2*x + 3).extract_additively(3) == 2*x
  1036. assert (2*x + 3).extract_additively(-2) is None
  1037. assert (2*x + 3).extract_additively(3*x) is None
  1038. assert (2*x + 3).extract_additively(2*x) == 3
  1039. assert x.extract_additively(0) == x
  1040. assert S(2).extract_additively(x) is None
  1041. assert S(2.).extract_additively(2.) is S.Zero
  1042. assert S(2.).extract_additively(2) is S.Zero
  1043. assert S(2*x + 3).extract_additively(x + 1) == x + 2
  1044. assert S(2*x + 3).extract_additively(y + 1) is None
  1045. assert S(2*x - 3).extract_additively(x + 1) is None
  1046. assert S(2*x - 3).extract_additively(y + z) is None
  1047. assert ((a + 1)*x*4 + y).extract_additively(x).expand() == \
  1048. 4*a*x + 3*x + y
  1049. assert ((a + 1)*x*4 + 3*y).extract_additively(x + 2*y).expand() == \
  1050. 4*a*x + 3*x + y
  1051. assert (y*(x + 1)).extract_additively(x + 1) is None
  1052. assert ((y + 1)*(x + 1) + 3).extract_additively(x + 1) == \
  1053. y*(x + 1) + 3
  1054. assert ((x + y)*(x + 1) + x + y + 3).extract_additively(x + y) == \
  1055. x*(x + y) + 3
  1056. assert (x + y + 2*((x + y)*(x + 1)) + 3).extract_additively((x + y)*(x + 1)) == \
  1057. x + y + (x + 1)*(x + y) + 3
  1058. assert ((y + 1)*(x + 2*y + 1) + 3).extract_additively(y + 1) == \
  1059. (x + 2*y)*(y + 1) + 3
  1060. assert (-x - x*I).extract_additively(-x) == -I*x
  1061. # extraction does not leave artificats, now
  1062. assert (4*x*(y + 1) + y).extract_additively(x) == x*(4*y + 3) + y
  1063. n = Symbol("n", integer=True)
  1064. assert (Integer(-3)).could_extract_minus_sign() is True
  1065. assert (-n*x + x).could_extract_minus_sign() != \
  1066. (n*x - x).could_extract_minus_sign()
  1067. assert (x - y).could_extract_minus_sign() != \
  1068. (-x + y).could_extract_minus_sign()
  1069. assert (1 - x - y).could_extract_minus_sign() is True
  1070. assert (1 - x + y).could_extract_minus_sign() is False
  1071. assert ((-x - x*y)/y).could_extract_minus_sign() is False
  1072. assert ((x + x*y)/(-y)).could_extract_minus_sign() is True
  1073. assert ((x + x*y)/y).could_extract_minus_sign() is False
  1074. assert ((-x - y)/(x + y)).could_extract_minus_sign() is False
  1075. class sign_invariant(Function, Expr):
  1076. nargs = 1
  1077. def __neg__(self):
  1078. return self
  1079. foo = sign_invariant(x)
  1080. assert foo == -foo
  1081. assert foo.could_extract_minus_sign() is False
  1082. assert (x - y).could_extract_minus_sign() is False
  1083. assert (-x + y).could_extract_minus_sign() is True
  1084. assert (x - 1).could_extract_minus_sign() is False
  1085. assert (1 - x).could_extract_minus_sign() is True
  1086. assert (sqrt(2) - 1).could_extract_minus_sign() is True
  1087. assert (1 - sqrt(2)).could_extract_minus_sign() is False
  1088. # check that result is canonical
  1089. eq = (3*x + 15*y).extract_multiplicatively(3)
  1090. assert eq.args == eq.func(*eq.args).args
  1091. def test_nan_extractions():
  1092. for r in (1, 0, I, nan):
  1093. assert nan.extract_additively(r) is None
  1094. assert nan.extract_multiplicatively(r) is None
  1095. def test_coeff():
  1096. assert (x + 1).coeff(x + 1) == 1
  1097. assert (3*x).coeff(0) == 0
  1098. assert (z*(1 + x)*x**2).coeff(1 + x) == z*x**2
  1099. assert (1 + 2*x*x**(1 + x)).coeff(x*x**(1 + x)) == 2
  1100. assert (1 + 2*x**(y + z)).coeff(x**(y + z)) == 2
  1101. assert (3 + 2*x + 4*x**2).coeff(1) == 0
  1102. assert (3 + 2*x + 4*x**2).coeff(-1) == 0
  1103. assert (3 + 2*x + 4*x**2).coeff(x) == 2
  1104. assert (3 + 2*x + 4*x**2).coeff(x**2) == 4
  1105. assert (3 + 2*x + 4*x**2).coeff(x**3) == 0
  1106. assert (-x/8 + x*y).coeff(x) == Rational(-1, 8) + y
  1107. assert (-x/8 + x*y).coeff(-x) == S.One/8
  1108. assert (4*x).coeff(2*x) == 0
  1109. assert (2*x).coeff(2*x) == 1
  1110. assert (-oo*x).coeff(x*oo) == -1
  1111. assert (10*x).coeff(x, 0) == 0
  1112. assert (10*x).coeff(10*x, 0) == 0
  1113. n1, n2 = symbols('n1 n2', commutative=False)
  1114. assert (n1*n2).coeff(n1) == 1
  1115. assert (n1*n2).coeff(n2) == n1
  1116. assert (n1*n2 + x*n1).coeff(n1) == 1 # 1*n1*(n2+x)
  1117. assert (n2*n1 + x*n1).coeff(n1) == n2 + x
  1118. assert (n2*n1 + x*n1**2).coeff(n1) == n2
  1119. assert (n1**x).coeff(n1) == 0
  1120. assert (n1*n2 + n2*n1).coeff(n1) == 0
  1121. assert (2*(n1 + n2)*n2).coeff(n1 + n2, right=1) == n2
  1122. assert (2*(n1 + n2)*n2).coeff(n1 + n2, right=0) == 2
  1123. assert (2*f(x) + 3*f(x).diff(x)).coeff(f(x)) == 2
  1124. expr = z*(x + y)**2
  1125. expr2 = z*(x + y)**2 + z*(2*x + 2*y)**2
  1126. assert expr.coeff(z) == (x + y)**2
  1127. assert expr.coeff(x + y) == 0
  1128. assert expr2.coeff(z) == (x + y)**2 + (2*x + 2*y)**2
  1129. assert (x + y + 3*z).coeff(1) == x + y
  1130. assert (-x + 2*y).coeff(-1) == x
  1131. assert (x - 2*y).coeff(-1) == 2*y
  1132. assert (3 + 2*x + 4*x**2).coeff(1) == 0
  1133. assert (-x - 2*y).coeff(2) == -y
  1134. assert (x + sqrt(2)*x).coeff(sqrt(2)) == x
  1135. assert (3 + 2*x + 4*x**2).coeff(x) == 2
  1136. assert (3 + 2*x + 4*x**2).coeff(x**2) == 4
  1137. assert (3 + 2*x + 4*x**2).coeff(x**3) == 0
  1138. assert (z*(x + y)**2).coeff((x + y)**2) == z
  1139. assert (z*(x + y)**2).coeff(x + y) == 0
  1140. assert (2 + 2*x + (x + 1)*y).coeff(x + 1) == y
  1141. assert (x + 2*y + 3).coeff(1) == x
  1142. assert (x + 2*y + 3).coeff(x, 0) == 2*y + 3
  1143. assert (x**2 + 2*y + 3*x).coeff(x**2, 0) == 2*y + 3*x
  1144. assert x.coeff(0, 0) == 0
  1145. assert x.coeff(x, 0) == 0
  1146. n, m, o, l = symbols('n m o l', commutative=False)
  1147. assert n.coeff(n) == 1
  1148. assert y.coeff(n) == 0
  1149. assert (3*n).coeff(n) == 3
  1150. assert (2 + n).coeff(x*m) == 0
  1151. assert (2*x*n*m).coeff(x) == 2*n*m
  1152. assert (2 + n).coeff(x*m*n + y) == 0
  1153. assert (2*x*n*m).coeff(3*n) == 0
  1154. assert (n*m + m*n*m).coeff(n) == 1 + m
  1155. assert (n*m + m*n*m).coeff(n, right=True) == m # = (1 + m)*n*m
  1156. assert (n*m + m*n).coeff(n) == 0
  1157. assert (n*m + o*m*n).coeff(m*n) == o
  1158. assert (n*m + o*m*n).coeff(m*n, right=True) == 1
  1159. assert (n*m + n*m*n).coeff(n*m, right=True) == 1 + n # = n*m*(n + 1)
  1160. assert (x*y).coeff(z, 0) == x*y
  1161. assert (x*n + y*n + z*m).coeff(n) == x + y
  1162. assert (n*m + n*o + o*l).coeff(n, right=True) == m + o
  1163. assert (x*n*m*n + y*n*m*o + z*l).coeff(m, right=True) == x*n + y*o
  1164. assert (x*n*m*n + x*n*m*o + z*l).coeff(m, right=True) == n + o
  1165. assert (x*n*m*n + x*n*m*o + z*l).coeff(m) == x*n
  1166. def test_coeff2():
  1167. r, kappa = symbols('r, kappa')
  1168. psi = Function("psi")
  1169. g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2))
  1170. g = g.expand()
  1171. assert g.coeff(psi(r).diff(r)) == 2/r
  1172. def test_coeff2_0():
  1173. r, kappa = symbols('r, kappa')
  1174. psi = Function("psi")
  1175. g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2))
  1176. g = g.expand()
  1177. assert g.coeff(psi(r).diff(r, 2)) == 1
  1178. def test_coeff_expand():
  1179. expr = z*(x + y)**2
  1180. expr2 = z*(x + y)**2 + z*(2*x + 2*y)**2
  1181. assert expr.coeff(z) == (x + y)**2
  1182. assert expr2.coeff(z) == (x + y)**2 + (2*x + 2*y)**2
  1183. def test_integrate():
  1184. assert x.integrate(x) == x**2/2
  1185. assert x.integrate((x, 0, 1)) == S.Half
  1186. def test_as_base_exp():
  1187. assert x.as_base_exp() == (x, S.One)
  1188. assert (x*y*z).as_base_exp() == (x*y*z, S.One)
  1189. assert (x + y + z).as_base_exp() == (x + y + z, S.One)
  1190. assert ((x + y)**z).as_base_exp() == (x + y, z)
  1191. def test_issue_4963():
  1192. assert hasattr(Mul(x, y), "is_commutative")
  1193. assert hasattr(Mul(x, y, evaluate=False), "is_commutative")
  1194. assert hasattr(Pow(x, y), "is_commutative")
  1195. assert hasattr(Pow(x, y, evaluate=False), "is_commutative")
  1196. expr = Mul(Pow(2, 2, evaluate=False), 3, evaluate=False) + 1
  1197. assert hasattr(expr, "is_commutative")
  1198. def test_action_verbs():
  1199. assert nsimplify(1/(exp(3*pi*x/5) + 1)) == \
  1200. (1/(exp(3*pi*x/5) + 1)).nsimplify()
  1201. assert ratsimp(1/x + 1/y) == (1/x + 1/y).ratsimp()
  1202. assert trigsimp(log(x), deep=True) == (log(x)).trigsimp(deep=True)
  1203. assert radsimp(1/(2 + sqrt(2))) == (1/(2 + sqrt(2))).radsimp()
  1204. assert radsimp(1/(a + b*sqrt(c)), symbolic=False) == \
  1205. (1/(a + b*sqrt(c))).radsimp(symbolic=False)
  1206. assert powsimp(x**y*x**z*y**z, combine='all') == \
  1207. (x**y*x**z*y**z).powsimp(combine='all')
  1208. assert (x**t*y**t).powsimp(force=True) == (x*y)**t
  1209. assert simplify(x**y*x**z*y**z) == (x**y*x**z*y**z).simplify()
  1210. assert together(1/x + 1/y) == (1/x + 1/y).together()
  1211. assert collect(a*x**2 + b*x**2 + a*x - b*x + c, x) == \
  1212. (a*x**2 + b*x**2 + a*x - b*x + c).collect(x)
  1213. assert apart(y/(y + 2)/(y + 1), y) == (y/(y + 2)/(y + 1)).apart(y)
  1214. assert combsimp(y/(x + 2)/(x + 1)) == (y/(x + 2)/(x + 1)).combsimp()
  1215. assert gammasimp(gamma(x)/gamma(x-5)) == (gamma(x)/gamma(x-5)).gammasimp()
  1216. assert factor(x**2 + 5*x + 6) == (x**2 + 5*x + 6).factor()
  1217. assert refine(sqrt(x**2)) == sqrt(x**2).refine()
  1218. assert cancel((x**2 + 5*x + 6)/(x + 2)) == ((x**2 + 5*x + 6)/(x + 2)).cancel()
  1219. def test_as_powers_dict():
  1220. assert x.as_powers_dict() == {x: 1}
  1221. assert (x**y*z).as_powers_dict() == {x: y, z: 1}
  1222. assert Mul(2, 2, evaluate=False).as_powers_dict() == {S(2): S(2)}
  1223. assert (x*y).as_powers_dict()[z] == 0
  1224. assert (x + y).as_powers_dict()[z] == 0
  1225. def test_as_coefficients_dict():
  1226. check = [S.One, x, y, x*y, 1]
  1227. assert [Add(3*x, 2*x, y, 3).as_coefficients_dict()[i] for i in check] == \
  1228. [3, 5, 1, 0, 3]
  1229. assert [Add(3*x, 2*x, y, 3, evaluate=False).as_coefficients_dict()[i]
  1230. for i in check] == [3, 5, 1, 0, 3]
  1231. assert [(3*x*y).as_coefficients_dict()[i] for i in check] == \
  1232. [0, 0, 0, 3, 0]
  1233. assert [(3.0*x*y).as_coefficients_dict()[i] for i in check] == \
  1234. [0, 0, 0, 3.0, 0]
  1235. assert (3.0*x*y).as_coefficients_dict()[3.0*x*y] == 0
  1236. eq = x*(x + 1)*a + x*b + c/x
  1237. assert eq.as_coefficients_dict(x) == {x: b, 1/x: c,
  1238. x*(x + 1): a}
  1239. assert eq.expand().as_coefficients_dict(x) == {x**2: a, x: a + b, 1/x: c}
  1240. assert x.as_coefficients_dict() == {x: S.One}
  1241. def test_args_cnc():
  1242. A = symbols('A', commutative=False)
  1243. assert (x + A).args_cnc() == \
  1244. [[], [x + A]]
  1245. assert (x + a).args_cnc() == \
  1246. [[a + x], []]
  1247. assert (x*a).args_cnc() == \
  1248. [[a, x], []]
  1249. assert (x*y*A*(A + 1)).args_cnc(cset=True) == \
  1250. [{x, y}, [A, 1 + A]]
  1251. assert Mul(x, x, evaluate=False).args_cnc(cset=True, warn=False) == \
  1252. [{x}, []]
  1253. assert Mul(x, x**2, evaluate=False).args_cnc(cset=True, warn=False) == \
  1254. [{x, x**2}, []]
  1255. raises(ValueError, lambda: Mul(x, x, evaluate=False).args_cnc(cset=True))
  1256. assert Mul(x, y, x, evaluate=False).args_cnc() == \
  1257. [[x, y, x], []]
  1258. # always split -1 from leading number
  1259. assert (-1.*x).args_cnc() == [[-1, 1.0, x], []]
  1260. def test_new_rawargs():
  1261. n = Symbol('n', commutative=False)
  1262. a = x + n
  1263. assert a.is_commutative is False
  1264. assert a._new_rawargs(x).is_commutative
  1265. assert a._new_rawargs(x, y).is_commutative
  1266. assert a._new_rawargs(x, n).is_commutative is False
  1267. assert a._new_rawargs(x, y, n).is_commutative is False
  1268. m = x*n
  1269. assert m.is_commutative is False
  1270. assert m._new_rawargs(x).is_commutative
  1271. assert m._new_rawargs(n).is_commutative is False
  1272. assert m._new_rawargs(x, y).is_commutative
  1273. assert m._new_rawargs(x, n).is_commutative is False
  1274. assert m._new_rawargs(x, y, n).is_commutative is False
  1275. assert m._new_rawargs(x, n, reeval=False).is_commutative is False
  1276. assert m._new_rawargs(S.One) is S.One
  1277. def test_issue_5226():
  1278. assert Add(evaluate=False) == 0
  1279. assert Mul(evaluate=False) == 1
  1280. assert Mul(x + y, evaluate=False).is_Add
  1281. def test_free_symbols():
  1282. # free_symbols should return the free symbols of an object
  1283. assert S.One.free_symbols == set()
  1284. assert x.free_symbols == {x}
  1285. assert Integral(x, (x, 1, y)).free_symbols == {y}
  1286. assert (-Integral(x, (x, 1, y))).free_symbols == {y}
  1287. assert meter.free_symbols == set()
  1288. assert (meter**x).free_symbols == {x}
  1289. def test_has_free():
  1290. assert x.has_free(x)
  1291. assert not x.has_free(y)
  1292. assert (x + y).has_free(x)
  1293. assert (x + y).has_free(*(x, z))
  1294. assert f(x).has_free(x)
  1295. assert f(x).has_free(f(x))
  1296. assert Integral(f(x), (f(x), 1, y)).has_free(y)
  1297. assert not Integral(f(x), (f(x), 1, y)).has_free(x)
  1298. assert not Integral(f(x), (f(x), 1, y)).has_free(f(x))
  1299. # simple extraction
  1300. assert (x + 1 + y).has_free(x + 1)
  1301. assert not (x + 2 + y).has_free(x + 1)
  1302. assert (2 + 3*x*y).has_free(3*x)
  1303. raises(TypeError, lambda: x.has_free({x, y}))
  1304. s = FiniteSet(1, 2)
  1305. assert Piecewise((s, x > 3), (4, True)).has_free(s)
  1306. assert not Piecewise((1, x > 3), (4, True)).has_free(s)
  1307. # can't make set of these, but fallback will handle
  1308. raises(TypeError, lambda: x.has_free(y, []))
  1309. def test_has_xfree():
  1310. assert (x + 1).has_xfree({x})
  1311. assert ((x + 1)**2).has_xfree({x + 1})
  1312. assert not (x + y + 1).has_xfree({x + 1})
  1313. raises(TypeError, lambda: x.has_xfree(x))
  1314. raises(TypeError, lambda: x.has_xfree([x]))
  1315. def test_issue_5300():
  1316. x = Symbol('x', commutative=False)
  1317. assert x*sqrt(2)/sqrt(6) == x*sqrt(3)/3
  1318. def test_floordiv():
  1319. from sympy.functions.elementary.integers import floor
  1320. assert x // y == floor(x / y)
  1321. def test_as_coeff_Mul():
  1322. assert Integer(3).as_coeff_Mul() == (Integer(3), Integer(1))
  1323. assert Rational(3, 4).as_coeff_Mul() == (Rational(3, 4), Integer(1))
  1324. assert Float(5.0).as_coeff_Mul() == (Float(5.0), Integer(1))
  1325. assert (Integer(3)*x).as_coeff_Mul() == (Integer(3), x)
  1326. assert (Rational(3, 4)*x).as_coeff_Mul() == (Rational(3, 4), x)
  1327. assert (Float(5.0)*x).as_coeff_Mul() == (Float(5.0), x)
  1328. assert (Integer(3)*x*y).as_coeff_Mul() == (Integer(3), x*y)
  1329. assert (Rational(3, 4)*x*y).as_coeff_Mul() == (Rational(3, 4), x*y)
  1330. assert (Float(5.0)*x*y).as_coeff_Mul() == (Float(5.0), x*y)
  1331. assert (x).as_coeff_Mul() == (S.One, x)
  1332. assert (x*y).as_coeff_Mul() == (S.One, x*y)
  1333. assert (-oo*x).as_coeff_Mul(rational=True) == (-1, oo*x)
  1334. def test_as_coeff_Add():
  1335. assert Integer(3).as_coeff_Add() == (Integer(3), Integer(0))
  1336. assert Rational(3, 4).as_coeff_Add() == (Rational(3, 4), Integer(0))
  1337. assert Float(5.0).as_coeff_Add() == (Float(5.0), Integer(0))
  1338. assert (Integer(3) + x).as_coeff_Add() == (Integer(3), x)
  1339. assert (Rational(3, 4) + x).as_coeff_Add() == (Rational(3, 4), x)
  1340. assert (Float(5.0) + x).as_coeff_Add() == (Float(5.0), x)
  1341. assert (Float(5.0) + x).as_coeff_Add(rational=True) == (0, Float(5.0) + x)
  1342. assert (Integer(3) + x + y).as_coeff_Add() == (Integer(3), x + y)
  1343. assert (Rational(3, 4) + x + y).as_coeff_Add() == (Rational(3, 4), x + y)
  1344. assert (Float(5.0) + x + y).as_coeff_Add() == (Float(5.0), x + y)
  1345. assert (x).as_coeff_Add() == (S.Zero, x)
  1346. assert (x*y).as_coeff_Add() == (S.Zero, x*y)
  1347. def test_expr_sorting():
  1348. exprs = [1/x**2, 1/x, sqrt(sqrt(x)), sqrt(x), x, sqrt(x)**3, x**2]
  1349. assert sorted(exprs, key=default_sort_key) == exprs
  1350. exprs = [x, 2*x, 2*x**2, 2*x**3, x**n, 2*x**n, sin(x), sin(x)**n,
  1351. sin(x**2), cos(x), cos(x**2), tan(x)]
  1352. assert sorted(exprs, key=default_sort_key) == exprs
  1353. exprs = [x + 1, x**2 + x + 1, x**3 + x**2 + x + 1]
  1354. assert sorted(exprs, key=default_sort_key) == exprs
  1355. exprs = [S(4), x - 3*I/2, x + 3*I/2, x - 4*I + 1, x + 4*I + 1]
  1356. assert sorted(exprs, key=default_sort_key) == exprs
  1357. exprs = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
  1358. assert sorted(exprs, key=default_sort_key) == exprs
  1359. exprs = [f(x), g(x), exp(x), sin(x), cos(x), factorial(x)]
  1360. assert sorted(exprs, key=default_sort_key) == exprs
  1361. exprs = [Tuple(x, y), Tuple(x, z), Tuple(x, y, z)]
  1362. assert sorted(exprs, key=default_sort_key) == exprs
  1363. exprs = [[3], [1, 2]]
  1364. assert sorted(exprs, key=default_sort_key) == exprs
  1365. exprs = [[1, 2], [2, 3]]
  1366. assert sorted(exprs, key=default_sort_key) == exprs
  1367. exprs = [[1, 2], [1, 2, 3]]
  1368. assert sorted(exprs, key=default_sort_key) == exprs
  1369. exprs = [{x: -y}, {x: y}]
  1370. assert sorted(exprs, key=default_sort_key) == exprs
  1371. exprs = [{1}, {1, 2}]
  1372. assert sorted(exprs, key=default_sort_key) == exprs
  1373. a, b = exprs = [Dummy('x'), Dummy('x')]
  1374. assert sorted([b, a], key=default_sort_key) == exprs
  1375. def test_as_ordered_factors():
  1376. assert x.as_ordered_factors() == [x]
  1377. assert (2*x*x**n*sin(x)*cos(x)).as_ordered_factors() \
  1378. == [Integer(2), x, x**n, sin(x), cos(x)]
  1379. args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
  1380. expr = Mul(*args)
  1381. assert expr.as_ordered_factors() == args
  1382. A, B = symbols('A,B', commutative=False)
  1383. assert (A*B).as_ordered_factors() == [A, B]
  1384. assert (B*A).as_ordered_factors() == [B, A]
  1385. def test_as_ordered_terms():
  1386. assert x.as_ordered_terms() == [x]
  1387. assert (sin(x)**2*cos(x) + sin(x)*cos(x)**2 + 1).as_ordered_terms() \
  1388. == [sin(x)**2*cos(x), sin(x)*cos(x)**2, 1]
  1389. args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
  1390. expr = Add(*args)
  1391. assert expr.as_ordered_terms() == args
  1392. assert (1 + 4*sqrt(3)*pi*x).as_ordered_terms() == [4*pi*x*sqrt(3), 1]
  1393. assert ( 2 + 3*I).as_ordered_terms() == [2, 3*I]
  1394. assert (-2 + 3*I).as_ordered_terms() == [-2, 3*I]
  1395. assert ( 2 - 3*I).as_ordered_terms() == [2, -3*I]
  1396. assert (-2 - 3*I).as_ordered_terms() == [-2, -3*I]
  1397. assert ( 4 + 3*I).as_ordered_terms() == [4, 3*I]
  1398. assert (-4 + 3*I).as_ordered_terms() == [-4, 3*I]
  1399. assert ( 4 - 3*I).as_ordered_terms() == [4, -3*I]
  1400. assert (-4 - 3*I).as_ordered_terms() == [-4, -3*I]
  1401. e = x**2*y**2 + x*y**4 + y + 2
  1402. assert e.as_ordered_terms(order="lex") == [x**2*y**2, x*y**4, y, 2]
  1403. assert e.as_ordered_terms(order="grlex") == [x*y**4, x**2*y**2, y, 2]
  1404. assert e.as_ordered_terms(order="rev-lex") == [2, y, x*y**4, x**2*y**2]
  1405. assert e.as_ordered_terms(order="rev-grlex") == [2, y, x**2*y**2, x*y**4]
  1406. k = symbols('k')
  1407. assert k.as_ordered_terms(data=True) == ([(k, ((1.0, 0.0), (1,), ()))], [k])
  1408. def test_sort_key_atomic_expr():
  1409. from sympy.physics.units import m, s
  1410. assert sorted([-m, s], key=lambda arg: arg.sort_key()) == [-m, s]
  1411. def test_eval_interval():
  1412. assert exp(x)._eval_interval(*Tuple(x, 0, 1)) == exp(1) - exp(0)
  1413. # issue 4199
  1414. a = x/y
  1415. raises(NotImplementedError, lambda: a._eval_interval(x, S.Zero, oo)._eval_interval(y, oo, S.Zero))
  1416. raises(NotImplementedError, lambda: a._eval_interval(x, S.Zero, oo)._eval_interval(y, S.Zero, oo))
  1417. a = x - y
  1418. raises(NotImplementedError, lambda: a._eval_interval(x, S.One, oo)._eval_interval(y, oo, S.One))
  1419. raises(ValueError, lambda: x._eval_interval(x, None, None))
  1420. a = -y*Heaviside(x - y)
  1421. assert a._eval_interval(x, -oo, oo) == -y
  1422. assert a._eval_interval(x, oo, -oo) == y
  1423. def test_eval_interval_zoo():
  1424. # Test that limit is used when zoo is returned
  1425. assert Si(1/x)._eval_interval(x, S.Zero, S.One) == -pi/2 + Si(1)
  1426. def test_primitive():
  1427. assert (3*(x + 1)**2).primitive() == (3, (x + 1)**2)
  1428. assert (6*x + 2).primitive() == (2, 3*x + 1)
  1429. assert (x/2 + 3).primitive() == (S.Half, x + 6)
  1430. eq = (6*x + 2)*(x/2 + 3)
  1431. assert eq.primitive()[0] == 1
  1432. eq = (2 + 2*x)**2
  1433. assert eq.primitive()[0] == 1
  1434. assert (4.0*x).primitive() == (1, 4.0*x)
  1435. assert (4.0*x + y/2).primitive() == (S.Half, 8.0*x + y)
  1436. assert (-2*x).primitive() == (2, -x)
  1437. assert Add(5*z/7, 0.5*x, 3*y/2, evaluate=False).primitive() == \
  1438. (S.One/14, 7.0*x + 21*y + 10*z)
  1439. for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
  1440. assert (i + x/3).primitive() == \
  1441. (S.One/3, i + x)
  1442. assert (S.Infinity + 2*x/3 + 4*y/7).primitive() == \
  1443. (S.One/21, 14*x + 12*y + oo)
  1444. assert S.Zero.primitive() == (S.One, S.Zero)
  1445. def test_issue_5843():
  1446. a = 1 + x
  1447. assert (2*a).extract_multiplicatively(a) == 2
  1448. assert (4*a).extract_multiplicatively(2*a) == 2
  1449. assert ((3*a)*(2*a)).extract_multiplicatively(a) == 6*a
  1450. def test_is_constant():
  1451. from sympy.solvers.solvers import checksol
  1452. assert Sum(x, (x, 1, 10)).is_constant() is True
  1453. assert Sum(x, (x, 1, n)).is_constant() is False
  1454. assert Sum(x, (x, 1, n)).is_constant(y) is True
  1455. assert Sum(x, (x, 1, n)).is_constant(n) is False
  1456. assert Sum(x, (x, 1, n)).is_constant(x) is True
  1457. eq = a*cos(x)**2 + a*sin(x)**2 - a
  1458. assert eq.is_constant() is True
  1459. assert eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
  1460. assert x.is_constant() is False
  1461. assert x.is_constant(y) is True
  1462. assert log(x/y).is_constant() is False
  1463. assert checksol(x, x, Sum(x, (x, 1, n))) is False
  1464. assert checksol(x, x, Sum(x, (x, 1, n))) is False
  1465. assert f(1).is_constant
  1466. assert checksol(x, x, f(x)) is False
  1467. assert Pow(x, S.Zero, evaluate=False).is_constant() is True # == 1
  1468. assert Pow(S.Zero, x, evaluate=False).is_constant() is False # == 0 or 1
  1469. assert (2**x).is_constant() is False
  1470. assert Pow(S(2), S(3), evaluate=False).is_constant() is True
  1471. z1, z2 = symbols('z1 z2', zero=True)
  1472. assert (z1 + 2*z2).is_constant() is True
  1473. assert meter.is_constant() is True
  1474. assert (3*meter).is_constant() is True
  1475. assert (x*meter).is_constant() is False
  1476. def test_equals():
  1477. assert (-3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2).equals(0)
  1478. assert (x**2 - 1).equals((x + 1)*(x - 1))
  1479. assert (cos(x)**2 + sin(x)**2).equals(1)
  1480. assert (a*cos(x)**2 + a*sin(x)**2).equals(a)
  1481. r = sqrt(2)
  1482. assert (-1/(r + r*x) + 1/r/(1 + x)).equals(0)
  1483. assert factorial(x + 1).equals((x + 1)*factorial(x))
  1484. assert sqrt(3).equals(2*sqrt(3)) is False
  1485. assert (sqrt(5)*sqrt(3)).equals(sqrt(3)) is False
  1486. assert (sqrt(5) + sqrt(3)).equals(0) is False
  1487. assert (sqrt(5) + pi).equals(0) is False
  1488. assert meter.equals(0) is False
  1489. assert (3*meter**2).equals(0) is False
  1490. eq = -(-1)**(S(3)/4)*6**(S.One/4) + (-6)**(S.One/4)*I
  1491. if eq != 0: # if canonicalization makes this zero, skip the test
  1492. assert eq.equals(0)
  1493. assert sqrt(x).equals(0) is False
  1494. # from integrate(x*sqrt(1 + 2*x), x);
  1495. # diff is zero only when assumptions allow
  1496. i = 2*sqrt(2)*x**(S(5)/2)*(1 + 1/(2*x))**(S(5)/2)/5 + \
  1497. 2*sqrt(2)*x**(S(3)/2)*(1 + 1/(2*x))**(S(5)/2)/(-6 - 3/x)
  1498. ans = sqrt(2*x + 1)*(6*x**2 + x - 1)/15
  1499. diff = i - ans
  1500. assert diff.equals(0) is None # should be False, but previously this was False due to wrong intermediate result
  1501. assert diff.subs(x, Rational(-1, 2)/2) == 7*sqrt(2)/120
  1502. # there are regions for x for which the expression is True, for
  1503. # example, when x < -1/2 or x > 0 the expression is zero
  1504. p = Symbol('p', positive=True)
  1505. assert diff.subs(x, p).equals(0) is True
  1506. assert diff.subs(x, -1).equals(0) is True
  1507. # prove via minimal_polynomial or self-consistency
  1508. eq = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3))
  1509. assert eq.equals(0)
  1510. q = 3**Rational(1, 3) + 3
  1511. p = expand(q**3)**Rational(1, 3)
  1512. assert (p - q).equals(0)
  1513. # issue 6829
  1514. # eq = q*x + q/4 + x**4 + x**3 + 2*x**2 - S.One/3
  1515. # z = eq.subs(x, solve(eq, x)[0])
  1516. q = symbols('q')
  1517. z = (q*(-sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
  1518. S(13)/12)/2 - sqrt((2*q - S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 -
  1519. S(2197)/13824)**(S.One/3) - S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 -
  1520. S(2197)/13824)**(S.One/3) - S(13)/6)/2 - S.One/4) + q/4 + (-sqrt(-2*(-(q
  1521. - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q
  1522. - S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
  1523. S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
  1524. S(13)/6)/2 - S.One/4)**4 + (-sqrt(-2*(-(q - S(7)/8)**S(2)/8 -
  1525. S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q -
  1526. S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
  1527. S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
  1528. S(13)/6)/2 - S.One/4)**3 + 2*(-sqrt(-2*(-(q - S(7)/8)**S(2)/8 -
  1529. S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q -
  1530. S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
  1531. S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
  1532. S(13)/6)/2 - S.One/4)**2 - Rational(1, 3))
  1533. assert z.equals(0)
  1534. def test_random():
  1535. from sympy.functions.combinatorial.numbers import lucas
  1536. from sympy.simplify.simplify import posify
  1537. assert posify(x)[0]._random() is not None
  1538. assert lucas(n)._random(2, -2, 0, -1, 1) is None
  1539. # issue 8662
  1540. assert Piecewise((Max(x, y), z))._random() is None
  1541. def test_round():
  1542. assert str(Float('0.1249999').round(2)) == '0.12'
  1543. d20 = 12345678901234567890
  1544. ans = S(d20).round(2)
  1545. assert ans.is_Integer and ans == d20
  1546. ans = S(d20).round(-2)
  1547. assert ans.is_Integer and ans == 12345678901234567900
  1548. assert str(S('1/7').round(4)) == '0.1429'
  1549. assert str(S('.[12345]').round(4)) == '0.1235'
  1550. assert str(S('.1349').round(2)) == '0.13'
  1551. n = S(12345)
  1552. ans = n.round()
  1553. assert ans.is_Integer
  1554. assert ans == n
  1555. ans = n.round(1)
  1556. assert ans.is_Integer
  1557. assert ans == n
  1558. ans = n.round(4)
  1559. assert ans.is_Integer
  1560. assert ans == n
  1561. assert n.round(-1) == 12340
  1562. r = Float(str(n)).round(-4)
  1563. assert r == 10000.0
  1564. assert n.round(-5) == 0
  1565. assert str((pi + sqrt(2)).round(2)) == '4.56'
  1566. assert (10*(pi + sqrt(2))).round(-1) == 50.0
  1567. raises(TypeError, lambda: round(x + 2, 2))
  1568. assert str(S(2.3).round(1)) == '2.3'
  1569. # rounding in SymPy (as in Decimal) should be
  1570. # exact for the given precision; we check here
  1571. # that when a 5 follows the last digit that
  1572. # the rounded digit will be even.
  1573. for i in range(-99, 100):
  1574. # construct a decimal that ends in 5, e.g. 123 -> 0.1235
  1575. s = str(abs(i))
  1576. p = len(s) # we are going to round to the last digit of i
  1577. n = '0.%s5' % s # put a 5 after i's digits
  1578. j = p + 2 # 2 for '0.'
  1579. if i < 0: # 1 for '-'
  1580. j += 1
  1581. n = '-' + n
  1582. v = str(Float(n).round(p))[:j] # pertinent digits
  1583. if v.endswith('.'):
  1584. continue # it ends with 0 which is even
  1585. L = int(v[-1]) # last digit
  1586. assert L % 2 == 0, (n, '->', v)
  1587. assert (Float(.3, 3) + 2*pi).round() == 7
  1588. assert (Float(.3, 3) + 2*pi*100).round() == 629
  1589. assert (pi + 2*E*I).round() == 3 + 5*I
  1590. # don't let request for extra precision give more than
  1591. # what is known (in this case, only 3 digits)
  1592. assert str((Float(.03, 3) + 2*pi/100).round(5)) == '0.0928'
  1593. assert str((Float(.03, 3) + 2*pi/100).round(4)) == '0.0928'
  1594. assert S.Zero.round() == 0
  1595. a = (Add(1, Float('1.' + '9'*27, ''), evaluate=0))
  1596. assert a.round(10) == Float('3.000000000000000000000000000', '')
  1597. assert a.round(25) == Float('3.000000000000000000000000000', '')
  1598. assert a.round(26) == Float('3.000000000000000000000000000', '')
  1599. assert a.round(27) == Float('2.999999999999999999999999999', '')
  1600. assert a.round(30) == Float('2.999999999999999999999999999', '')
  1601. # XXX: Should round set the precision of the result?
  1602. # The previous version of the tests above is this but they only pass
  1603. # because Floats with unequal precision compare equal:
  1604. #
  1605. # assert a.round(10) == Float('3.0000000000', '')
  1606. # assert a.round(25) == Float('3.0000000000000000000000000', '')
  1607. # assert a.round(26) == Float('3.00000000000000000000000000', '')
  1608. # assert a.round(27) == Float('2.999999999999999999999999999', '')
  1609. # assert a.round(30) == Float('2.999999999999999999999999999', '')
  1610. raises(TypeError, lambda: x.round())
  1611. raises(TypeError, lambda: f(1).round())
  1612. # exact magnitude of 10
  1613. assert str(S.One.round()) == '1'
  1614. assert str(S(100).round()) == '100'
  1615. # applied to real and imaginary portions
  1616. assert (2*pi + E*I).round() == 6 + 3*I
  1617. assert (2*pi + I/10).round() == 6
  1618. assert (pi/10 + 2*I).round() == 2*I
  1619. # the lhs re and im parts are Float with dps of 2
  1620. # and those on the right have dps of 15 so they won't compare
  1621. # equal unless we use string or compare components (which will
  1622. # then coerce the floats to the same precision) or re-create
  1623. # the floats
  1624. assert str((pi/10 + E*I).round(2)) == '0.31 + 2.72*I'
  1625. assert str((pi/10 + E*I).round(2).as_real_imag()) == '(0.31, 2.72)'
  1626. assert str((pi/10 + E*I).round(2)) == '0.31 + 2.72*I'
  1627. # issue 6914
  1628. assert (I**(I + 3)).round(3) == Float('-0.208', '')*I
  1629. # issue 8720
  1630. assert S(-123.6).round() == -124
  1631. assert S(-1.5).round() == -2
  1632. assert S(-100.5).round() == -100
  1633. assert S(-1.5 - 10.5*I).round() == -2 - 10*I
  1634. # issue 7961
  1635. assert str(S(0.006).round(2)) == '0.01'
  1636. assert str(S(0.00106).round(4)) == '0.0011'
  1637. # issue 8147
  1638. assert S.NaN.round() is S.NaN
  1639. assert S.Infinity.round() is S.Infinity
  1640. assert S.NegativeInfinity.round() is S.NegativeInfinity
  1641. assert S.ComplexInfinity.round() is S.ComplexInfinity
  1642. # check that types match
  1643. for i in range(2):
  1644. fi = float(i)
  1645. # 2 args
  1646. assert all(type(round(i, p)) is int for p in (-1, 0, 1))
  1647. assert all(S(i).round(p).is_Integer for p in (-1, 0, 1))
  1648. assert all(type(round(fi, p)) is float for p in (-1, 0, 1))
  1649. assert all(S(fi).round(p).is_Float for p in (-1, 0, 1))
  1650. # 1 arg (p is None)
  1651. assert type(round(i)) is int
  1652. assert S(i).round().is_Integer
  1653. assert type(round(fi)) is int
  1654. assert S(fi).round().is_Integer
  1655. def test_held_expression_UnevaluatedExpr():
  1656. x = symbols("x")
  1657. he = UnevaluatedExpr(1/x)
  1658. e1 = x*he
  1659. assert isinstance(e1, Mul)
  1660. assert e1.args == (x, he)
  1661. assert e1.doit() == 1
  1662. assert UnevaluatedExpr(Derivative(x, x)).doit(deep=False
  1663. ) == Derivative(x, x)
  1664. assert UnevaluatedExpr(Derivative(x, x)).doit() == 1
  1665. xx = Mul(x, x, evaluate=False)
  1666. assert xx != x**2
  1667. ue2 = UnevaluatedExpr(xx)
  1668. assert isinstance(ue2, UnevaluatedExpr)
  1669. assert ue2.args == (xx,)
  1670. assert ue2.doit() == x**2
  1671. assert ue2.doit(deep=False) == xx
  1672. x2 = UnevaluatedExpr(2)*2
  1673. assert type(x2) is Mul
  1674. assert x2.args == (2, UnevaluatedExpr(2))
  1675. def test_round_exception_nostr():
  1676. # Don't use the string form of the expression in the round exception, as
  1677. # it's too slow
  1678. s = Symbol('bad')
  1679. try:
  1680. s.round()
  1681. except TypeError as e:
  1682. assert 'bad' not in str(e)
  1683. else:
  1684. # Did not raise
  1685. raise AssertionError("Did not raise")
  1686. def test_extract_branch_factor():
  1687. assert exp_polar(2.0*I*pi).extract_branch_factor() == (1, 1)
  1688. def test_identity_removal():
  1689. assert Add.make_args(x + 0) == (x,)
  1690. assert Mul.make_args(x*1) == (x,)
  1691. def test_float_0():
  1692. assert Float(0.0) + 1 == Float(1.0)
  1693. @XFAIL
  1694. def test_float_0_fail():
  1695. assert Float(0.0)*x == Float(0.0)
  1696. assert (x + Float(0.0)).is_Add
  1697. def test_issue_6325():
  1698. ans = (b**2 + z**2 - (b*(a + b*t) + z*(c + t*z))**2/(
  1699. (a + b*t)**2 + (c + t*z)**2))/sqrt((a + b*t)**2 + (c + t*z)**2)
  1700. e = sqrt((a + b*t)**2 + (c + z*t)**2)
  1701. assert diff(e, t, 2) == ans
  1702. assert e.diff(t, 2) == ans
  1703. assert diff(e, t, 2, simplify=False) != ans
  1704. def test_issue_7426():
  1705. f1 = a % c
  1706. f2 = x % z
  1707. assert f1.equals(f2) is None
  1708. def test_issue_11122():
  1709. x = Symbol('x', extended_positive=False)
  1710. assert unchanged(Gt, x, 0) # (x > 0)
  1711. # (x > 0) should remain unevaluated after PR #16956
  1712. x = Symbol('x', positive=False, real=True)
  1713. assert (x > 0) is S.false
  1714. def test_issue_10651():
  1715. x = Symbol('x', real=True)
  1716. e1 = (-1 + x)/(1 - x)
  1717. e3 = (4*x**2 - 4)/((1 - x)*(1 + x))
  1718. e4 = 1/(cos(x)**2) - (tan(x))**2
  1719. x = Symbol('x', positive=True)
  1720. e5 = (1 + x)/x
  1721. assert e1.is_constant() is None
  1722. assert e3.is_constant() is None
  1723. assert e4.is_constant() is None
  1724. assert e5.is_constant() is False
  1725. def test_issue_10161():
  1726. x = symbols('x', real=True)
  1727. assert x*abs(x)*abs(x) == x**3
  1728. def test_issue_10755():
  1729. x = symbols('x')
  1730. raises(TypeError, lambda: int(log(x)))
  1731. raises(TypeError, lambda: log(x).round(2))
  1732. def test_issue_11877():
  1733. x = symbols('x')
  1734. assert integrate(log(S.Half - x), (x, 0, S.Half)) == Rational(-1, 2) -log(2)/2
  1735. def test_normal():
  1736. x = symbols('x')
  1737. e = Mul(S.Half, 1 + x, evaluate=False)
  1738. assert e.normal() == e
  1739. def test_expr():
  1740. x = symbols('x')
  1741. raises(TypeError, lambda: tan(x).series(x, 2, oo, "+"))
  1742. def test_ExprBuilder():
  1743. eb = ExprBuilder(Mul)
  1744. eb.args.extend([x, x])
  1745. assert eb.build() == x**2
  1746. def test_issue_22020():
  1747. from sympy.parsing.sympy_parser import parse_expr
  1748. x = parse_expr("log((2*V/3-V)/C)/-(R+r)*C")
  1749. y = parse_expr("log((2*V/3-V)/C)/-(R+r)*2")
  1750. assert x.equals(y) is False
  1751. def test_non_string_equality():
  1752. # Expressions should not compare equal to strings
  1753. x = symbols('x')
  1754. one = sympify(1)
  1755. assert (x == 'x') is False
  1756. assert (x != 'x') is True
  1757. assert (one == '1') is False
  1758. assert (one != '1') is True
  1759. assert (x + 1 == 'x + 1') is False
  1760. assert (x + 1 != 'x + 1') is True
  1761. # Make sure == doesn't try to convert the resulting expression to a string
  1762. # (e.g., by calling sympify() instead of _sympify())
  1763. class BadRepr:
  1764. def __repr__(self):
  1765. raise RuntimeError
  1766. assert (x == BadRepr()) is False
  1767. assert (x != BadRepr()) is True
  1768. def test_21494():
  1769. from sympy.testing.pytest import warns_deprecated_sympy
  1770. with warns_deprecated_sympy():
  1771. assert x.expr_free_symbols == {x}
  1772. with warns_deprecated_sympy():
  1773. assert Basic().expr_free_symbols == set()
  1774. with warns_deprecated_sympy():
  1775. assert S(2).expr_free_symbols == {S(2)}
  1776. with warns_deprecated_sympy():
  1777. assert Indexed("A", x).expr_free_symbols == {Indexed("A", x)}
  1778. with warns_deprecated_sympy():
  1779. assert Subs(x, x, 0).expr_free_symbols == set()
  1780. def test_Expr__eq__iterable_handling():
  1781. assert x != range(3)
  1782. def test_format():
  1783. assert '{:1.2f}'.format(S.Zero) == '0.00'
  1784. assert '{:+3.0f}'.format(S(3)) == ' +3'
  1785. assert '{:23.20f}'.format(pi) == ' 3.14159265358979323846'
  1786. assert '{:50.48f}'.format(exp(sin(1))) == '2.319776824715853173956590377503266813254904772376'