Play around area¶
from sympy import *
x, y, z = symbols("x y z")
expr = cos(x) + 1
expr.subs(x, y)
\[\displaystyle \cos{\left(y \right)} + 1\]
expr.subs(x, 0)
\[\displaystyle 2\]
expr = x**y
expr
\[\displaystyle x^{y}\]
expr = expr.subs(y, x**y)
expr
\[\displaystyle x^{x^{y}}\]
expr = expr.subs(y, x**x)
expr
\[\displaystyle x^{x^{x^{x}}}\]
expr = sin(2*x) + cos(2*x)
expand_trig(expr)
\[\displaystyle 2 \sin{\left(x \right)} \cos{\left(x \right)} + 2 \cos^{2}{\left(x \right)} - 1\]
expr.subs(sin(2*x), 2*sin(x)*cos(x))
\[\displaystyle 2 \sin{\left(x \right)} \cos{\left(x \right)} + \cos{\left(2 x \right)}\]
expr = cos(x)
expr.subs(x, 0)
expr
x
\[\displaystyle x\]
expr = x**4 - 4*x**3 + 4*x**2 - 2*x + 3
replacements = [(x**i, y**i) for i in range(5) if i % 2 == 0]
expr.subs(replacements)
\[\displaystyle - 4 x^{3} - 2 x + y^{4} + 4 y^{2} + 3\]
To evaluate a numerical expression into a floating point number, use evalf
.
expr = sqrt(8)
expr.evalf()
\[\displaystyle 2.82842712474619\]
pi.evalf(100)
\[\displaystyle 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068\]
pi.evalf(10000)
\[\displaystyle 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420198938095257201065485863278865936153381827968230301952035301852968995773622599413891249721775283479131515574857242454150695950829533116861727855889075098381754637464939319255060400927701671139009848824012858361603563707660104710181942955596198946767837449448255379774726847104047534646208046684259069491293313677028989152104752162056966024058038150193511253382430035587640247496473263914199272604269922796782354781636009341721641219924586315030286182974555706749838505494588586926995690927210797509302955321165344987202755960236480665499119881834797753566369807426542527862551818417574672890977772793800081647060016145249192173217214772350141441973568548161361157352552133475741849468438523323907394143334547762416862518983569485562099219222184272550254256887671790494601653466804988627232791786085784383827967976681454100953883786360950680064225125205117392984896084128488626945604241965285022210661186306744278622039194945047123713786960956364371917287467764657573962413890865832645995813390478027590099465764078951269468398352595709825822620522489407726719478268482601476990902640136394437455305068203496252451749399651431429809190659250937221696461515709858387410597885959772975498930161753928468138268683868942774155991855925245953959431049972524680845987273644695848653836736222626099124608051243884390451244136549762780797715691435997700129616089441694868555848406353422072225828488648158456028506016842739452267467678895252138522549954666727823986456596116354886230577456498035593634568174324112515076069479451096596094025228879710893145669136867228748940560101503308617928680920874760917824938589009714909675985261365549781893129784821682998948722658804857564014270477555132379641451523746234364542858444795265867821051141354735739523113427166102135969536231442952484937187110145765403590279934403742007310578539062198387447808478489683321445713868751943506430218453191048481005370614680674919278191197939952061419663428754440643745123718192179998391015919561814675142691239748940907186494231961567945208095146550225231603881930142093762137855956638937787083039069792077346722182562599661501421503068038447734549202605414665925201497442850732518666002132434088190710486331734649651453905796268561005508106658796998163574736384052571459102897064140110971206280439039759515677157700420337869936007230558763176359421873125147120532928191826186125867321579198414848829164470609575270695722091756711672291098169091528017350671274858322287183520935396572512108357915136988209144421006751033467110314126711136990865851639831501970165151168517143765761835155650884909989859982387345528331635507647918535893226185489632132933089857064204675259070915481416549859461637180270981994309924488957571282890592323326097299712084433573265489382391193259746366730583604142813883032038249037589852437441702913276561809377344403070746921120191302033038019762110110044929321516084244485963766983895228684783123552658213144957685726243344189303968642624341077322697802807318915441101044682325271620105265227211166039666557309254711055785376346682065310989652691862056476931257058635662018558100729360659876486117910453348850346113657686753249441668039626579787718556084552965412665408530614344431858676975145661406800700237877659134401712749470420562230538994561314071127000407854733269939081454664645880797270826683063432858785698305235808933065757406795457163775254202114955761581400250126228594130216471550979259230990796547376125517656751357517829666454779174501129961489030463994713296210734043751895735961458901938971311179042978285647503203198691514028708085990480109412147221317947647772622414254854540332157185306142288137585043063321751829798662237172159160771669254748738986654949450114654062843366393790039769265672146385306736096571209180763832716641627488880078692560290228472104031721186082041900042296617119637792133757511495950156604963186294726547364252308177036751590673502350728354056704038674351362222477158915049530984448933309634087807693259939780541934144737744184263129860809988868741326047215695162396586457302163159819319516735381297416772947867242292465436680098067692823828068996400482435403701416314965897940924323789690706977942236250822168895738379862300159377647165122893578601588161755782973523344604281512627203734314653197777416031990665541876397929334419521541341899485444734567383162499341913181480927777103863877343177207545654532207770921201905166096280490926360197598828161332316663652861932668633606273567630354477628035045077723554710585954870279081435624014517180624643626794561275318134078330336254232783944975382437205835311477119926063813346776879695970309833913077109870408591337464144282277263465947047458784778720192771528073176790770715721344473060570073349243693113835049316312840425121925651798069411352801314701304781643788518529092854520116583934196562134914341595625865865570552690496520985803385072242648293972858478316305777756068887644624824685792603953527734803048029005876075825104747091643961362676044925627420420832085661190625454337213153595845068772460290161876679524061634252257719542916299193064553779914037340432875262888963995879475729174642635745525407909145135711136941091193932519107602082520261879853188770584297259167781314969900901921169717372784768472686084900337702424291651300500516832336435038951702989392233451722013812806965011784408745196012122859937162313017114448464090389064495444006198690754851602632750529834918740786680881833851022833450850486082503930213321971551843063545500766828294930413776552793975175461395398468339363830474611996653858153842056853386218672523340283087112328278921250771262946322956398989893582116745627010218356462201349671518819097303811980049734072396103685406643193950979019069963955245300545058068550195673022921913933918568034490398205955100226353536192041994745538593810234395544959778377902374216172711172364343543947822181852862408514006660443325888569867054315470696574745855033232334210730154594051655379068662733379958511562578432298827372319898757141595781119635833005940873068121602876496286744604774649159950549737425626901049037781986835938146574126804925648798556145372347867330390468838343634655379498641927056387293174872332083760112302991136793862708943879936201629515413371424892830722012690147546684765357616477379467520049075715552781965362132392640616013635815590742202020318727760527721900556148425551879253034351398442532234157623361064250639049750086562710953591946589751413103482276930624743536325691607815478181152843667957061108615331504452127473924544945423682886061340841486377670096120715124914043027253860764823634143346235189757664521641376796903149501910857598442391986291642193994907236234646844117394032659184044378051333894525742399508296591228508555821572503107125701266830240292952522011872676756220415420516184163484756516999811614101002996078386909291603028840026910414079288621507842451670908700069928212066041837180653556725253256753286129104248776182582976515795984703562226293486003415872298053498965022629174878820273420922224533985626476691490556284250391275771028402799806636582548892648802545661017296702664076559042909945681506526530537182941270336931378517860904070866711496558343434769338578171138645587367812301458768712660348913909562009939361031029161615288138437909904231747336394804575931493140529763475748119356709110137751721008031559024853090669203767192203322909433467685142214477379393751703443661991040337511173547191855046449026365512816228824462575916333039107225383742182140883508657391771509682887478265699599574490661758344137522397096834080053559849175417381883999446974867626551658276584835884531427756879002909517028352971634456212964043523117600665101241200659755851276178583829204197484423608007193045761893234922927965019875187212726750798125547095890455635792122103334669749923563025494780249011419521238281530911407907386025152274299581807247162591668545133312394804947079119153267343028244186041426363954800044800267049624820179289647669758318327131425170296923488962766844032326092752496035799646925650493681836090032380929345958897069536534940603402166544375589004563288225054525564056448246515187547119621844396582533754388569094113031509526179378002974120766514793942590298969594699556576121865619673378623625612521632086286922210327488921865436480229678070576561514463204692790682120738837781423356282360896320806822246801224826117718589638140918390367367222088832151375560037279839400415297002878307667094447456013455641725437090697939612257142989467154357846878861444581231459357198492252847160504922124247014121478057345510500801908699603302763478708108175450119307141223390866393833952942578690507643100638351983438934159613185434754649556978103829309716465143840700707360411237359984345225161050702705623526601276484830840761183013052793205427462865403603674532865105706587488225698157936789766974220575059683440869735020141020672358502007245225632651341055924019027421624843914035998953539459094407046912091409387001264560016237428802109276457931065792295524988727584610126483699989225695968815920560010165525637568\]
expr = cos(2*x)
expr.evalf(subs={x: 2.4})
\[\displaystyle 0.0874989834394464\]
one = cos(1)**2 + sin(1)**2
(one - 1).evalf()
\[\displaystyle -4.0 \cdot 10^{-124}\]
(one - 1).evalf(chop=True)
\[\displaystyle 0\]
import numpy
a = numpy.arange(10)
expr = sin(x)
f = lambdify(x, expr, "numpy")
f(a)
array([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 ,
-0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849])
f = lambdify(x, expr, "math")
f(0.1)
0.09983341664682815
def mysin(x):
"""
My sine. Note that this is only accurate for small x.
"""
return x
f = lambdify(x, expr, {"sin":mysin})
f(0.1)
0.1
from sympy import init_printing
init_printing()
from sympy import init_session
init_session()
IPython console for SymPy 1.12 (Python 3.11.8-64-bit) (ground types: python)
These commands were executed:
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
>>> init_printing()
Documentation can be found at https://docs.sympy.org/1.12/
from __future__ import division
from sympy import *
x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)
init_printing() # doctest: +SKIP
Integral(sqrt(1/x),x)
\[\displaystyle \int \sqrt{\frac{1}{x}}\, dx\]
simplify(sin(x)**2 + cos(x)**2)
simplify((x**3 + x**2 - x - 1)/(x**2 + 2*x + 1))
simplify(gamma(x)/gamma(x - 2))
\[\displaystyle \left(x - 2\right) \left(x - 1\right)\]
simplify(x**2 + 2*x + 1)
\[\displaystyle x^{2} + 2 x + 1\]
expand((x + 1)**2)
expand((x + 2)*(x - 3))
\[\displaystyle x^{2} - x - 6\]
expand((x + 1)*(x - 2) - (x - 1)*x)
\[\displaystyle -2\]
factor(x**3 - x**2 + x - 1)
factor(x**2*z + 4*x*y*z + 4*y**2*z)
\[\displaystyle z \left(x + 2 y\right)^{2}\]
factor_list(x**2*z + 4*x*y*z + 4*y**2*z)
\[\displaystyle \left( 1, \ \left[ \left( z, \ 1\right), \ \left( x + 2 y, \ 2\right)\right]\right)\]
expand((cos(x) + sin(x))**2)
factor(cos(x)**2 + 2*cos(x)*sin(x) + sin(x)**2)
\[\displaystyle \left(\sin{\left(x \right)} + \cos{\left(x \right)}\right)^{2}\]
expr = x*y + x - 3 + 2*x**2 - z*x**2 + x**3
expr
collected_expr = collect(expr, x)
collected_expr
\[\displaystyle x^{3} + x^{2} \cdot \left(2 - z\right) + x \left(y + 1\right) - 3\]
collected_expr.coeff(x, 2)
\[\displaystyle 2 - z\]
cancel((x**2 + 2*x + 1)/(x**2 + x))
\[\displaystyle \frac{x + 1}{x}\]
expr = 1/x + (3*x/2 - 2)/(x - 4)
expr
cancel(expr)
\[\displaystyle \frac{3 x^{2} - 2 x - 8}{2 x^{2} - 8 x}\]
expr = (x*y**2 - 2*x*y*z + x*z**2 + y**2 - 2*y*z + z**2)/(x**2 - 1)
expr
cancel(expr)
\[\displaystyle \frac{y^{2} - 2 y z + z^{2}}{x - 1}\]
factor(expr)
\[\displaystyle \frac{\left(y - z\right)^{2}}{x - 1}\]
expr = (4*x**3 + 21*x**2 + 10*x + 12)/(x**4 + 5*x**3 + 5*x**2 + 4*x)
expr
apart(expr)
\[\displaystyle \frac{2 x - 1}{x^{2} + x + 1} - \frac{1}{x + 4} + \frac{3}{x}\]
acos(x)
cos(acos(x))
asin(1)
\[\displaystyle \frac{\pi}{2}\]
trigsimp(sin(x)**2 + cos(x)**2)
trigsimp(sin(x)**4 - 2*cos(x)**2*sin(x)**2 + cos(x)**4)
trigsimp(sin(x)*tan(x)/sec(x))
\[\displaystyle \sin^{2}{\left(x \right)}\]
trigsimp(cosh(x)**2 + sinh(x)**2)
trigsimp(sinh(x)/tanh(x))
\[\displaystyle \cosh{\left(x \right)}\]
expand_trig(sin(x + y))
expand_trig(tan(2*x))
\[\displaystyle \frac{2 \tan{\left(x \right)}}{1 - \tan^{2}{\left(x \right)}}\]
trigsimp(sin(x)*cos(y) + sin(y)*cos(x))
\[\displaystyle \sin{\left(x + y \right)}\]
x, y = symbols('x y', positive=True)
a, b = symbols('a b', real=True)
z, t, c = symbols('z t c')
sqrt(x) == x**Rational(1, 2)
True
Power¶
powsimp(x**a*x**b)
powsimp(x**a*y**a)
\[\displaystyle \left(x y\right)^{a}\]
powsimp(t**c*z**c)
\[\displaystyle t^{c} z^{c}\]
powsimp(t**c*z**c, force=True)
\[\displaystyle \left(t z\right)^{c}\]
(z*t)**2
sqrt(x*y)
\[\displaystyle \sqrt{x} \sqrt{y}\]
powsimp(z**2*t**2)
powsimp(sqrt(x)*sqrt(y))
\[\displaystyle \sqrt{x} \sqrt{y}\]
expand_power_exp(x**(a + b))
\[\displaystyle x^{a} x^{b}\]
expand_power_base((x*y)**a)
\[\displaystyle x^{a} y^{a}\]
Derivative¶
diff(cos(x), x)
diff(exp(x**2), x)
\[\displaystyle 2 x e^{x^{2}}\]
diff(x**4, x, x, x)
\[\displaystyle 24 x\]
diff(x**4, x, 3)
\[\displaystyle 24 x\]
expr = exp(x*y*z)
diff(expr, x, y, y, z, z, z, z)
\[\displaystyle x^{3} y^{2} \left(x^{3} y^{3} z^{3} + 14 x^{2} y^{2} z^{2} + 52 x y z + 48\right) e^{x y z}\]
diff(expr, x, y, 2, z, 4)
\[\displaystyle x^{3} y^{2} \left(x^{3} y^{3} z^{3} + 14 x^{2} y^{2} z^{2} + 52 x y z + 48\right) e^{x y z}\]
diff(expr, x, y, y, z, 4)
\[\displaystyle x^{3} y^{2} \left(x^{3} y^{3} z^{3} + 14 x^{2} y^{2} z^{2} + 52 x y z + 48\right) e^{x y z}\]
expr.diff(x, y, y, z, 4)
\[\displaystyle x^{3} y^{2} \left(x^{3} y^{3} z^{3} + 14 x^{2} y^{2} z^{2} + 52 x y z + 48\right) e^{x y z}\]
unevaluated derivative¶
These unevaluated objects are useful for delaying the evaluation of the derivative, or for printing purposes.
deriv = Derivative(expr, x, y, y, z, 4)
deriv
\[\displaystyle \frac{\partial^{7}}{\partial z^{4}\partial y^{2}\partial x} e^{x y z}\]
deriv.doit()
\[\displaystyle x^{3} y^{2} \left(x^{3} y^{3} z^{3} + 14 x^{2} y^{2} z^{2} + 52 x y z + 48\right) e^{x y z}\]
m, n, a, b = symbols('m n a b')
expr = (a*x + b)**m
expr.diff((x, n))
\[\displaystyle \frac{\partial^{n}}{\partial x^{n}} \left(a x + b\right)^{m}\]
Integral
integrate(cos(x), x)
\[\displaystyle \sin{\left(x \right)}\]
Note that SymPy does not include the constant of integration. If you want it, you can add one yourself, or rephrase your problem as a differential equation and use dsolve to solve it, which does add the constant (see Solving Differential Equations).
integrate(exp(-x), (x, 0, oo))
\[\displaystyle 1\]
integrate(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
\[\displaystyle \pi\]
expr = integrate(x**x, x)
print(expr)
expr
Integral(x**x, x)
\[\displaystyle \int x^{x}\, dx\]
expr = Integral(log(x)**2, x)
expr
\[\displaystyle \int \log{\left(x \right)}^{2}\, dx\]
expr.doit()
\[\displaystyle x \log{\left(x \right)}^{2} - 2 x \log{\left(x \right)} + 2 x\]
integ = Integral((x**4 + x**2*exp(x) - x**2 - 2*x*exp(x) - 2*x -
exp(x))*exp(x)/((x - 1)**2*(x + 1)**2*(exp(x) + 1)), x)
integ
integ.doit()
\[\displaystyle \log{\left(e^{x} + 1 \right)} + \frac{e^{x}}{x^{2} - 1}\]
integ = Integral(sin(x**2), x)
integ
integ.doit()
\[\displaystyle \frac{3 \sqrt{2} \sqrt{\pi} S\left(\frac{\sqrt{2} x}{\sqrt{\pi}}\right) \Gamma\left(\frac{3}{4}\right)}{8 \Gamma\left(\frac{7}{4}\right)}\]
integ = Integral(x**y*exp(-x), (x, 0, oo))
integ
integ.doit()
\[\displaystyle \Gamma\left(y + 1\right)\]
Limit¶
limit(sin(x)/x, x, 0)
\[\displaystyle 1\]
expr = x**2/exp(x)
expr.subs(x, oo)
limit(expr, x, oo)
\[\displaystyle 0\]
expr = Limit((cos(x) - 1)/x, x, 0)
expr
\[\displaystyle \lim_{x \to 0^+}\left(\frac{\cos{\left(x \right)} - 1}{x}\right)\]
expr.doit()
\[\displaystyle 0\]
limit(1/x, x, 0, '+')
\[\displaystyle \infty\]
limit(1/x, x, 0, '-')
\[\displaystyle -\infty\]
Series expansion¶
expr = exp(sin(x))
expr.series(x, 0, 4)
\[\displaystyle 1 + x + \frac{x^{2}}{2} + O\left(x^{4}\right)\]
x + x**3 + x**6 + O(x**4)
\[\displaystyle x + x^{3} + O\left(x^{4}\right)\]
x*O(1)
\[\displaystyle O\left(x\right)\]
expr.series(x, 0, 4).removeO()
\[\displaystyle \frac{x^{2}}{2} + x + 1\]
exp(x - 6).series(x, x0=6)
\[\displaystyle -5 + \frac{\left(x - 6\right)^{2}}{2} + \frac{\left(x - 6\right)^{3}}{6} + \frac{\left(x - 6\right)^{4}}{24} + \frac{\left(x - 6\right)^{5}}{120} + x + O\left(\left(x - 6\right)^{6}; x\rightarrow 6\right)\]
f, g = symbols('f g', cls=Function)
differentiate_finite(f(x)*g(x))
\[\displaystyle - f{\left(x - \frac{1}{2} \right)} g{\left(x - \frac{1}{2} \right)} + f{\left(x + \frac{1}{2} \right)} g{\left(x + \frac{1}{2} \right)}\]
Eqaution¶
Eq(x, y)
\[\displaystyle x = y\]
solveset(Eq(x**2, 1), x)
solveset(Eq(x**2 - 1, 0), x)
solveset(x**2 - 1, x)
\[\displaystyle \left\{-1, 1\right\}\]
solveset(x**2 - x, x)
\[\displaystyle \left\{0, 1\right\}\]
solveset(x - x, x, domain=S.Reals)
\[\displaystyle \mathbb{R}\]
solveset(sin(x) - 1, x, domain=S.Reals)
\[\displaystyle \left\{2 n \pi + \frac{\pi}{2}\; \middle|\; n \in \mathbb{Z}\right\}\]
solveset(exp(x), x) # No solution exists
\[\displaystyle \emptyset\]
solveset(cos(x) - x, x) # Not able to find solution
\[\displaystyle \left\{x\; \middle|\; x \in \mathbb{C} \wedge - x + \cos{\left(x \right)} = 0 \right\}\]
linsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z))
\[\displaystyle \left\{\left( - y - 1, \ y, \ 2\right)\right\}\]
linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))
\[\displaystyle \left\{\left( - y - 1, \ y, \ 2\right)\right\}\]
M = Matrix(((1, 1, 1, 1), (1, 1, 2, 3)))
system = A, b = M[:, :-1], M[:, -1]
linsolve(system, x, y, z)
\[\displaystyle \left\{\left( - y - 1, \ y, \ 2\right)\right\}\]
Solving differential equation¶
f, g = symbols('f g', cls=Function)
f(x)
\[\displaystyle f{\left(x \right)}\]
f(x).diff(x)
\[\displaystyle \frac{d}{d x} f{\left(x \right)}\]
diffeq = Eq(f(x).diff(x, x) - 2*f(x).diff(x) + f(x), sin(x))
diffeq
\[\displaystyle f{\left(x \right)} - 2 \frac{d}{d x} f{\left(x \right)} + \frac{d^{2}}{d x^{2}} f{\left(x \right)} = \sin{\left(x \right)}\]
dsolve(diffeq, f(x))
\[\displaystyle f{\left(x \right)} = \left(C_{1} + C_{2} x\right) e^{x} + \frac{\cos{\left(x \right)}}{2}\]
dsolve(f(x).diff(x)*(1 - sin(f(x))) - 1, f(x))
\[\displaystyle x - f{\left(x \right)} - \cos{\left(f{\left(x \right)} \right)} = C_{1}\]
Matrices¶
init_printing(use_unicode=True)
Matrix([[1, -1], [3, 4], [0, 2]])
\[\begin{split}\displaystyle \left[\begin{matrix}1 & -1\\3 & 4\\0 & 2\end{matrix}\right]\end{split}\]
Matrix([1, 2, 3])
\[\begin{split}\displaystyle \left[\begin{matrix}1\\2\\3\end{matrix}\right]\end{split}\]
Matrix([[1], [2], [3]])
\[\begin{split}\displaystyle \left[\begin{matrix}1\\2\\3\end{matrix}\right]\end{split}\]
Matrix([[1, 2, 3]])
\[\displaystyle \left[\begin{matrix}1 & 2 & 3\end{matrix}\right]\]
Matrix([[1, 2, 3],[4,5,6]])
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 2 & 3\\4 & 5 & 6\end{matrix}\right]\end{split}\]
M = Matrix([[1, 2, 3], [3, 2, 1]])
N = Matrix([0, 1, 1])
M*N
\[\begin{split}\displaystyle \left[\begin{matrix}5\\3\end{matrix}\right]\end{split}\]
from sympy import shape
M = Matrix([[1, 2, 3], [-2, 0, 4]])
M
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 2 & 3\\-2 & 0 & 4\end{matrix}\right]\end{split}\]
shape(M)
\[\displaystyle \left( 2, \ 3\right)\]
M.row(0)
\[\displaystyle \left[\begin{matrix}1 & 2 & 3\end{matrix}\right]\]
M.col(-1)
\[\begin{split}\displaystyle \left[\begin{matrix}3\\4\end{matrix}\right]\end{split}\]
M.col_del(0)
M
\[\begin{split}\displaystyle \left[\begin{matrix}2 & 3\\0 & 4\end{matrix}\right]\end{split}\]
M.row_del(1)
M
\[\displaystyle \left[\begin{matrix}2 & 3\end{matrix}\right]\]
M = M.row_insert(1, Matrix([[0, 4]]))
M
\[\begin{split}\displaystyle \left[\begin{matrix}2 & 3\\0 & 4\end{matrix}\right]\end{split}\]
M = M.col_insert(0, Matrix([1, -2]))
M
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 2 & 3\\-2 & 0 & 4\end{matrix}\right]\end{split}\]
M = Matrix([[1, 3], [-2, 3]])
N = Matrix([[0, 3], [0, 7]])
M + N
M*N
3*M
M**2
M**-1
N**-1
---------------------------------------------------------------------------
NonInvertibleMatrixError Traceback (most recent call last)
Cell In[115], line 8
6 M**2
7 M**-1
----> 8 N**-1
File ~/work/sympy-playground/sympy-playground/.pixi/envs/default/lib/python3.11/site-packages/sympy/core/decorators.py:106, in call_highest_priority.<locals>.priority_decorator.<locals>.binary_op_wrapper(self, other)
104 if f is not None:
105 return f(self)
--> 106 return func(self, other)
File ~/work/sympy-playground/sympy-playground/.pixi/envs/default/lib/python3.11/site-packages/sympy/matrices/common.py:2780, in MatrixArithmetic.__pow__(self, exp)
2776 @call_highest_priority('__rpow__')
2777 def __pow__(self, exp):
2778 """Return self**exp a scalar or symbol."""
-> 2780 return self.pow(exp)
File ~/work/sympy-playground/sympy-playground/.pixi/envs/default/lib/python3.11/site-packages/sympy/matrices/common.py:2824, in MatrixArithmetic.pow(self, exp, method)
2822 if exp < 0:
2823 exp = -exp
-> 2824 a = a.inv()
2825 # When certain conditions are met,
2826 # Jordan block algorithm is faster than
2827 # computation by recursion.
2828 if method == 'jordan':
File ~/work/sympy-playground/sympy-playground/.pixi/envs/default/lib/python3.11/site-packages/sympy/matrices/matrices.py:2177, in MatrixBase.inv(self, method, iszerofunc, try_block_diag)
2176 def inv(self, method=None, iszerofunc=_iszero, try_block_diag=False):
-> 2177 return _inv(self, method=method, iszerofunc=iszerofunc,
2178 try_block_diag=try_block_diag)
File ~/work/sympy-playground/sympy-playground/.pixi/envs/default/lib/python3.11/site-packages/sympy/matrices/inverse.py:459, in _inv(M, method, iszerofunc, try_block_diag)
456 return diag(*r)
458 if method == "GE":
--> 459 rv = M.inverse_GE(iszerofunc=iszerofunc)
460 elif method == "LU":
461 rv = M.inverse_LU(iszerofunc=iszerofunc)
File ~/work/sympy-playground/sympy-playground/.pixi/envs/default/lib/python3.11/site-packages/sympy/matrices/matrices.py:2162, in MatrixBase.inverse_GE(self, iszerofunc)
2161 def inverse_GE(self, iszerofunc=_iszero):
-> 2162 return _inv_GE(self, iszerofunc=iszerofunc)
File ~/work/sympy-playground/sympy-playground/.pixi/envs/default/lib/python3.11/site-packages/sympy/matrices/inverse.py:245, in _inv_GE(M, iszerofunc)
242 red = big.rref(iszerofunc=iszerofunc, simplify=True)[0]
244 if any(iszerofunc(red[j, j]) for j in range(red.rows)):
--> 245 raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
247 return M._new(red[:, big.rows:])
NonInvertibleMatrixError: Matrix det == 0; not invertible.
eye(3)
eye(4)
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 0 & 0 & 0\\0 & 1 & 0 & 0\\0 & 0 & 1 & 0\\0 & 0 & 0 & 1\end{matrix}\right]\end{split}\]
ones(3, 2)
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 1\\1 & 1\\1 & 1\end{matrix}\right]\end{split}\]
diag(1, 2, 3)
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 2 & 0\\0 & 0 & 3\end{matrix}\right]\end{split}\]
diag(-1, ones(2, 2), Matrix([5, 7, 5]))
\[\begin{split}\displaystyle \left[\begin{matrix}-1 & 0 & 0 & 0\\0 & 1 & 1 & 0\\0 & 1 & 1 & 0\\0 & 0 & 0 & 5\\0 & 0 & 0 & 7\\0 & 0 & 0 & 5\end{matrix}\right]\end{split}\]
M = Matrix([[1, 0, 1], [2, -1, 3], [4, 3, 2]])
M
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 0 & 1\\2 & -1 & 3\\4 & 3 & 2\end{matrix}\right]\end{split}\]
M.det()
\[\displaystyle -1\]
M = Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]])
M
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 0 & 1 & 3\\2 & 3 & 4 & 7\\-1 & -3 & -3 & -4\end{matrix}\right]\end{split}\]
M.rref()
\[\begin{split}\displaystyle \left( \left[\begin{matrix}1 & 0 & 1 & 3\\0 & 1 & \frac{2}{3} & \frac{1}{3}\\0 & 0 & 0 & 0\end{matrix}\right], \ \left( 0, \ 1\right)\right)\end{split}\]
M = Matrix([[1, 2, 3, 0, 0], [4, 10, 0, 0, 1]])
M
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 2 & 3 & 0 & 0\\4 & 10 & 0 & 0 & 1\end{matrix}\right]\end{split}\]
M.nullspace()
\[\begin{split}\displaystyle \left[ \left[\begin{matrix}-15\\6\\1\\0\\0\end{matrix}\right], \ \left[\begin{matrix}0\\0\\0\\1\\0\end{matrix}\right], \ \left[\begin{matrix}1\\- \frac{1}{2}\\0\\0\\1\end{matrix}\right]\right]\end{split}\]
M = Matrix([[1, 1, 2], [2 ,1 , 3], [3 , 1, 4]])
M
M.columnspace()
\[\begin{split}\displaystyle \left[ \left[\begin{matrix}1\\2\\3\end{matrix}\right], \ \left[\begin{matrix}1\\1\\1\end{matrix}\right]\right]\end{split}\]
M = Matrix([[3, -2, 4, -2], [5, 3, -3, -2], [5, -2, 2, -2], [5, -2, -3, 3]])
M
\[\begin{split}\displaystyle \left[\begin{matrix}3 & -2 & 4 & -2\\5 & 3 & -3 & -2\\5 & -2 & 2 & -2\\5 & -2 & -3 & 3\end{matrix}\right]\end{split}\]
M.eigenvals()
\[\displaystyle \left\{ -2 : 1, \ 3 : 1, \ 5 : 2\right\}\]
M.eigenvects()
\[\begin{split}\displaystyle \left[ \left( -2, \ 1, \ \left[ \left[\begin{matrix}0\\1\\1\\1\end{matrix}\right]\right]\right), \ \left( 3, \ 1, \ \left[ \left[\begin{matrix}1\\1\\1\\1\end{matrix}\right]\right]\right), \ \left( 5, \ 2, \ \left[ \left[\begin{matrix}1\\1\\1\\0\end{matrix}\right], \ \left[\begin{matrix}0\\-1\\0\\1\end{matrix}\right]\right]\right)\right]\end{split}\]
P, D = M.diagonalize()
P
D
P*D*P**-1
P*D*P**-1 == M
True
lamda = symbols('lamda')
p = M.charpoly(lamda)
factor(p.as_expr())
\[\displaystyle \left(\lambda - 5\right)^{2} \left(\lambda - 3\right) \left(\lambda + 2\right)\]
q = Symbol("q", positive = True)
m = Matrix([
[-2*cosh(q/3), exp(-q), 1],
[ exp(q), -2*cosh(q/3), 1],
[ 1, 1, -2*cosh(q/3)]])
m.nullspace()
\[\begin{split}\displaystyle \left[ \left[\begin{matrix}- \frac{- 2 e^{q} \cosh{\left(\frac{q}{3} \right)} - 4 \cosh^{2}{\left(\frac{q}{3} \right)} - 1 - 2 e^{- q} \cosh{\left(\frac{q}{3} \right)}}{4 e^{q} \cosh^{2}{\left(\frac{q}{3} \right)} + 4 \cosh{\left(\frac{q}{3} \right)} + e^{- q}}\\- \frac{1 - 4 \cosh^{2}{\left(\frac{q}{3} \right)}}{2 \cosh{\left(\frac{q}{3} \right)} + e^{- q}}\\1\end{matrix}\right]\right]\end{split}\]
import warnings
def my_iszero(x):
try:
result = x.is_zero
except AttributeError:
result = None
# Warnings if evaluated into None
if result is None:
warnings.warn("Zero testing of {} evaluated into None".format(x))
return result
m.nullspace(iszerofunc=my_iszero)
/tmp/ipykernel_1958/341185985.py:9: UserWarning: Zero testing of 4*cosh(q/3)**2 - 1 evaluated into None
warnings.warn("Zero testing of {} evaluated into None".format(x))
/tmp/ipykernel_1958/341185985.py:9: UserWarning: Zero testing of 2*exp(q)*cosh(q/3) - 16*cosh(q/3)**4 + 12*cosh(q/3)**2 + 2*exp(-q)*cosh(q/3) evaluated into None
warnings.warn("Zero testing of {} evaluated into None".format(x))
\[\begin{split}\displaystyle \left[ \left[\begin{matrix}- \frac{- 2 e^{q} \cosh{\left(\frac{q}{3} \right)} - 4 \cosh^{2}{\left(\frac{q}{3} \right)} - 1 - 2 e^{- q} \cosh{\left(\frac{q}{3} \right)}}{4 e^{q} \cosh^{2}{\left(\frac{q}{3} \right)} + 4 \cosh{\left(\frac{q}{3} \right)} + e^{- q}}\\- \frac{1 - 4 \cosh^{2}{\left(\frac{q}{3} \right)}}{2 \cosh{\left(\frac{q}{3} \right)} + e^{- q}}\\1\end{matrix}\right]\right]\end{split}\]
def my_iszero(x):
try:
result = x.rewrite(exp).simplify().is_zero
except AttributeError:
result = None
# Warnings if evaluated into None
if result is None:
warnings.warn("Zero testing of {} evaluated into None".format(x))
return result
m.nullspace(iszerofunc=my_iszero)
/tmp/ipykernel_1958/339700269.py:8: UserWarning: Zero testing of -2*cosh(q/3) - exp(-q) evaluated into None
warnings.warn("Zero testing of {} evaluated into None".format(x))
\[\begin{split}\displaystyle \left[ \left[\begin{matrix}- \frac{- 2 e^{q} \cosh{\left(\frac{q}{3} \right)} - 1}{4 e^{q} \cosh^{2}{\left(\frac{q}{3} \right)} - e^{q}}\\- \frac{- e^{q} - 2 \cosh{\left(\frac{q}{3} \right)}}{4 \cosh^{2}{\left(\frac{q}{3} \right)} - 1}\\1\end{matrix}\right]\right]\end{split}\]
Expression Trees¶
x, y, z = symbols('x y z')
expr = x**2 + x*y
srepr(expr)
"Add(Pow(Symbol('x'), Integer(2)), Mul(Symbol('x'), Symbol('y')))"
x = symbols('x')
x = Symbol('x')
srepr(x**2)
"Pow(Symbol('x'), Integer(2))"
Pow(x, 2)
\[\displaystyle x^{2}\]
expr = sin(x*y)/2 - x**2 + 1/y
srepr(expr)
"Add(Mul(Integer(-1), Pow(Symbol('x'), Integer(2))), Mul(Rational(1, 2), sin(Mul(Symbol('x'), Symbol('y')))), Pow(Symbol('y'), Integer(-1)))"
srepr(x - y)
"Add(Symbol('x'), Mul(Integer(-1), Symbol('y')))"
expr = x/y
srepr(expr)
"Mul(Symbol('x'), Pow(Symbol('y'), Integer(-1)))"
import graphviz
import graphviz
# Create a new Digraph object
dot = graphviz.Digraph(comment='The Visualization of x**2 + xy')
# Adding nodes
dot.node('A', 'Add')
dot.node('B', 'Pow')
dot.node('C', 'x', shape='ellipse')
dot.node('D', '2', shape='ellipse')
dot.node('E', 'Mul')
dot.node('F', 'x', shape='ellipse') # Reused label 'x', but it's a different node in the graph context
dot.node('G', 'y', shape='ellipse')
# Adding edges
dot.edges(['AB', 'AE'])
dot.edge('B', 'C', label='0,0')
dot.edge('B', 'D', label='0,1')
dot.edges(['EC', 'EG'])
# Generate the diagram
dot_path = '/mnt/data/expr_graphviz.svg'
dot.render(dot_path, format='svg', view=False)
dot_path
---------------------------------------------------------------------------
PermissionError Traceback (most recent call last)
Cell In[145], line 23
21 # Generate the diagram
22 dot_path = '/mnt/data/expr_graphviz.svg'
---> 23 dot.render(dot_path, format='svg', view=False)
26 dot_path
File ~/work/sympy-playground/sympy-playground/.pixi/envs/default/lib/python3.11/site-packages/graphviz/_tools.py:171, in deprecate_positional_args.<locals>.decorator.<locals>.wrapper(*args, **kwargs)
162 wanted = ', '.join(f'{name}={value!r}'
163 for name, value in deprecated.items())
164 warnings.warn(f'The signature of {func.__name__} will be reduced'
165 f' to {supported_number} positional args'
166 f' {list(supported)}: pass {wanted}'
167 ' as keyword arg(s)',
168 stacklevel=stacklevel,
169 category=category)
--> 171 return func(*args, **kwargs)
File ~/work/sympy-playground/sympy-playground/.pixi/envs/default/lib/python3.11/site-packages/graphviz/rendering.py:118, in Render.render(self, filename, directory, view, cleanup, format, renderer, formatter, neato_no_op, quiet, quiet_view, outfile, engine, raise_if_result_exists, overwrite_source)
115 if outfile is not None and filename is None:
116 filename = self._get_filepath(outfile)
--> 118 filepath = self.save(filename, directory=directory, skip_existing=None)
120 args.append(filepath)
122 rendered = self._render(*args, **kwargs)
File ~/work/sympy-playground/sympy-playground/.pixi/envs/default/lib/python3.11/site-packages/graphviz/_tools.py:171, in deprecate_positional_args.<locals>.decorator.<locals>.wrapper(*args, **kwargs)
162 wanted = ', '.join(f'{name}={value!r}'
163 for name, value in deprecated.items())
164 warnings.warn(f'The signature of {func.__name__} will be reduced'
165 f' to {supported_number} positional args'
166 f' {list(supported)}: pass {wanted}'
167 ' as keyword arg(s)',
168 stacklevel=stacklevel,
169 category=category)
--> 171 return func(*args, **kwargs)
File ~/work/sympy-playground/sympy-playground/.pixi/envs/default/lib/python3.11/site-packages/graphviz/saving.py:76, in Save.save(self, filename, directory, skip_existing)
73 if skip_existing and os.path.exists(filepath):
74 return filepath
---> 76 self._mkdirs(filepath)
78 log.debug('write lines to %r', filepath)
79 with open(filepath, 'w', encoding=self.encoding) as fd:
File ~/work/sympy-playground/sympy-playground/.pixi/envs/default/lib/python3.11/site-packages/graphviz/_tools.py:49, in mkdirs(filename, mode)
47 return
48 log.debug('os.makedirs(%r)', dirname)
---> 49 os.makedirs(dirname, mode=mode, exist_ok=True)
File <frozen os>:225, in makedirs(name, mode, exist_ok)
PermissionError: [Errno 13] Permission denied: '/mnt/data'