-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
tutorial.txt
867 lines (631 loc) · 19.1 KB
/
tutorial.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
.. _tutorial:
========
Tutorial
========
.. role:: input(strong)
Introduction
============
SymPy is a Python library for symbolic mathematics. It aims to become a
full-featured computer algebra system (CAS) while keeping the code as simple as
possible in order to be comprehensible and easily extensible. SymPy is written
entirely in Python and does not require any external libraries.
This tutorial gives an overview and introduction to SymPy.
Read this to have an idea what SymPy can do for you (and how) and if you want
to know more, read the
:ref:`SymPy User's Guide <guide>`,
:ref:`SymPy Modules Reference <module-docs>`.
or the `sources
<https://github.com/sympy/sympy/>`_ directly.
First Steps with SymPy
======================
The easiest way to download it is to go to
http://code.google.com/p/sympy/ and
download the latest tarball from the Featured Downloads:
.. image:: figures/featured-downloads.png
Unpack it:
.. parsed-literal::
$ :input:`tar xzf sympy-0.5.12.tar.gz`
and try it from a Python intepreter:
.. parsed-literal::
$ cd sympy-0.5.12
$ python
Python 2.4.4 (#2, Jan 3 2008, 13:36:28)
[GCC 4.2.3 20071123 (prerelease) (Debian 4.2.2-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from sympy import Symbol, cos
>>> x = Symbol("x")
>>> (1/cos(x)).series(x, 0, 10)
1 + x**2/2 + 5*x**4/24 + 61*x**6/720 + 277*x**8/8064 + O(x**10)
You can use SymPy as shown above and this is indeed the recommended way if you
use it in your program. You can also install it using ``./setup.py install`` as
any other Python module, or just install a package in your favourite Linux
distribution, e.g.:
.. topic:: Installing SymPy in Debian
.. parsed-literal::
$ :input:`sudo apt-get install python-sympy`
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
python-sympy
0 upgraded, 1 newly installed, 0 to remove and 18 not upgraded.
Need to get 991kB of archives.
After this operation, 5976kB of additional disk space will be used.
Get:1 http://ftp.cz.debian.org unstable/main python-sympy 0.5.12-1 [991kB]
Fetched 991kB in 2s (361kB/s)
Selecting previously deselected package python-sympy.
(Reading database ... 232619 files and directories currently installed.)
Unpacking python-sympy (from .../python-sympy_0.5.12-1_all.deb) ...
Setting up python-sympy (0.5.12-1) ...
For other means how to install SymPy, consult the Downloads_ tab on the
SymPy's webpage.
.. _Downloads: http://code.google.com/p/sympy/wiki/DownloadInstallation?tm=2
isympy Console
--------------
For experimenting with new features, or when figuring out how to do things, you
can use our special wrapper around IPython called ``isympy`` (located in
``bin/isympy`` if you are running from the source directory) which is just a
standard python shell that has already imported the relevant sympy modules and
defined the symbols x, y, z and some other things:
.. parsed-literal::
$ :input:`cd sympy`
$ :input:`./bin/isympy`
IPython console for SymPy 0.6.7-git (Python 2.7.1) (ground types: gmpy)
These commands were executed:
>>> 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)
Documentation can be found at http://www.sympy.org
In [1]: input:`(1/cos(x)).series(x, 0, 10)`
Out[1]:
2 4 6 8
x 5*x 61*x 277*x
1 + ── + ──── + ───── + ────── + O(x**10)
2 24 720 8064
.. note::
Commands entered by you are bold. Thus what we did in 3 lines in a regular
Python interpeter can be done in 1 line in isympy.
Using SymPy as a calculator
---------------------------
Sympy has three built-in numeric types: Float, Rational and Integer.
The Rational class represents a rational number as a pair of two Integers: the numerator and the denominator, so Rational(1,2) represents 1/2, Rational(5,2) 5/2 and so on.
::
>>> from sympy import *
>>> a = Rational(1,2)
>>> a
1/2
>>> a*2
1
>>> Rational(2)**50/Rational(10)**50
1/88817841970012523233890533447265625
proceed with caution while working with python int's since they truncate
integer division, and that's why::
>>> 1/2
0
>>> 1.0/2
0.5
You can however do::
>>> from __future__ import division
>>> 1/2 #doctest: +SKIP
0.5
True division is going to be standard in python3k and ``isympy`` does that too.
We also have some special constants, like e and pi, that are treated as symbols
(1+pi won't evaluate to something numeric, rather it will remain as 1+pi), and
have arbitrary precission::
>>> pi**2
pi**2
>>> pi.evalf()
3.14159265358979
>>> (pi+exp(1)).evalf()
5.85987448204884
as you see, evalf evaluates the expression to a floating-point number
There is also a class representing mathematical infinity, called ``oo``::
>>> oo > 99999
True
>>> oo + 1
oo
Symbols
-------
In contrast to other Computer Algebra Systems, in SymPy you have to declare
symbolic variables explicitly::
>>> from sympy import *
>>> x = Symbol('x')
>>> y = Symbol('y')
Then you can play with them::
>>> x+y+x-y
2*x
>>> (x+y)**2
(x + y)**2
>>> ((x+y)**2).expand()
x**2 + 2*x*y + y**2
And substitute them for other symbols or numbers using ``subs(old, new)``::
>>> ((x+y)**2).subs(x, 1)
(y + 1)**2
>>> ((x+y)**2).subs(x, y)
4*y**2
For the remainder of the tutorial, we assume that we have run::
>>> import sys
>>> oldhook = sys.displayhook
>>> sys.displayhook = pprint
So that things pretty print. See the :ref:`printing-tutorial` section below. If you have a unicode font installed, your output may look a litte different (it will look slightly nicer).
Algebra
=======
For partial fraction decomposition, use ``apart(expr, x)``::
>>> 1/( (x+2)*(x+1) )
1
---------------
(x + 1)*(x + 2)
>>> apart(1/( (x+2)*(x+1) ), x)
1 1
- ----- + -----
x + 2 x + 1
>>> (x+1)/(x-1)
x + 1
-----
x - 1
>>> apart((x+1)/(x-1), x)
2
1 + -----
x - 1
To combine things back together, use ``together(expr, x)``::
>>> together(1/x + 1/y + 1/z)
x*y + x*z + y*z
---------------
x*y*z
>>> together(apart((x+1)/(x-1), x), x)
x + 1
-----
x - 1
>>> together(apart(1/( (x+2)*(x+1) ), x), x)
1
---------------
(x + 1)*(x + 2)
.. index:: calculus
Calculus
========
.. index:: limits
Limits
------
Limits are easy to use in sympy, they follow the syntax limit(function,
variable, point), so to compute the limit of f(x) as x -> 0, you would issue
limit(f, x, 0)::
>>> from sympy import *
>>> x=Symbol("x")
>>> limit(sin(x)/x, x, 0)
1
you can also calculate the limit at infinity::
>>> limit(x, x, oo)
oo
>>> limit(1/x, x, oo)
0
>>> limit(x**x, x, 0)
1
for some non-trivial examples on limits, you can read the test file
`test_demidovich.py
<https://github.com/sympy/sympy/blob/master/sympy/series/tests/test_demidovich.py>`_
.. index:: differentiation, diff
Differentiation
---------------
You can differentiate any SymPy expression using ``diff(func, var)``. Examples::
>>> from sympy import *
>>> x = Symbol('x')
>>> diff(sin(x), x)
cos(x)
>>> diff(sin(2*x), x)
2*cos(2*x)
>>> diff(tan(x), x)
2
tan (x) + 1
You can check, that it is correct by::
>>> limit((tan(x+y)-tan(x))/y, y, 0)
2
tan (x) + 1
Higher derivatives can be calculated using the ``diff(func, var, n)`` method::
>>> diff(sin(2*x), x, 1)
2*cos(2*x)
>>> diff(sin(2*x), x, 2)
-4*sin(2*x)
>>> diff(sin(2*x), x, 3)
-8*cos(2*x)
.. index::
single: series expansion
single: expansion; series
Series expansion
----------------
Use ``.series(var, point, order)``::
>>> from sympy import *
>>> x = Symbol('x')
>>> cos(x).series(x, 0, 10)
2 4 6 8
x x x x
1 - -- + -- - --- + ----- + O(x**10)
2 24 720 40320
>>> (1/cos(x)).series(x, 0, 10)
2 4 6 8
x 5*x 61*x 277*x
1 + -- + ---- + ----- + ------ + O(x**10)
2 24 720 8064
Another simple example::
from sympy import Integral, Symbol, pprint
x = Symbol("x")
y = Symbol("y")
e = 1/(x + y)
s = e.series(x, 0, 5)
print(s)
pprint(s)
That should print the following after the execution::
1/y + x**2*y**(-3) + x**4*y**(-5) - x*y**(-2) - x**3*y**(-4) + O(x**5)
2 4 3
1 x x x x
─ + ── + ── - ── - ── + O(x**5)
y 3 5 2 4
y y y y
.. index:: integration
Integration
-----------
SymPy has support for indefinite and definite integration of transcendental
elementary and special functions via `integrate()` facility, which uses
powerful extended Risch-Norman algorithm and some heuristics and pattern
matching::
>>> from sympy import *
>>> x, y = symbols('x,y')
You can integrate elementary functions::
>>> integrate(6*x**5, x)
6
x
>>> integrate(sin(x), x)
-cos(x)
>>> integrate(log(x), x)
x*log(x) - x
>>> integrate(2*x + sinh(x), x)
2
x + cosh(x)
Also special functions are handled easily::
>>> integrate(exp(-x**2)*erf(x), x)
____ 2
\/ pi *erf (x)
--------------
4
It is possible to compute definite integral::
>>> integrate(x**3, (x, -1, 1))
0
>>> integrate(sin(x), (x, 0, pi/2))
1
>>> integrate(cos(x), (x, -pi/2, pi/2))
2
Also improper integrals are supported as well::
>>> integrate(exp(-x), (x, 0, oo))
1
>>> integrate(log(x), (x, 0, 1))
-1
.. index::
single: complex numbers
single: expansion; complex
Complex numbers
---------------
::
>>> from sympy import Symbol, exp, I
>>> x = Symbol("x")
>>> exp(I*x).expand()
I*x
e
>>> exp(I*x).expand(complex=True)
-im(x) -im(x)
I*e *sin(re(x)) + e *cos(re(x))
>>> x = Symbol("x", real=True)
>>> exp(I*x).expand(complex=True)
I*sin(x) + cos(x)
Functions
---------
**trigonometric**::
>>> sin(x+y).expand(trig=True)
sin(x)*cos(y) + sin(y)*cos(x)
>>> cos(x+y).expand(trig=True)
-sin(x)*sin(y) + cos(x)*cos(y)
>>> sin(I*x)
I*sinh(x)
>>> sinh(I*x)
I*sin(x)
>>> asinh(I)
I*pi
----
2
>>> asinh(I*x)
I*asin(x)
>>> sin(x).series(x, 0, 10)
3 5 7 9
x x x x
x - -- + --- - ---- + ------ + O(x**10)
6 120 5040 362880
>>> sinh(x).series(x, 0, 10)
3 5 7 9
x x x x
x + -- + --- + ---- + ------ + O(x**10)
6 120 5040 362880
>>> asin(x).series(x, 0, 10)
3 5 7 9
x 3*x 5*x 35*x
x + -- + ---- + ---- + ----- + O(x**10)
6 40 112 1152
>>> asinh(x).series(x, 0, 10)
3 5 7 9
x 3*x 5*x 35*x
x - -- + ---- - ---- + ----- + O(x**10)
6 40 112 1152
**spherical harmonics**::
>>> from sympy.abc import theta, phi
>>> Ylm(1, 0, theta, phi)
___
\/ 3 *cos(theta)
----------------
____
2*\/ pi
>>> Ylm(1, 1, theta, phi)
___ I*phi
-\/ 6 *e *sin(theta)
------------------------
____
4*\/ pi
>>> Ylm(2, 1, theta, phi)
____ I*phi
-\/ 30 *e *sin(theta)*cos(theta)
------------------------------------
____
4*\/ pi
**factorials and gamma function**::
>>> x = Symbol("x")
>>> y = Symbol("y", integer=True)
>>> factorial(x)
x!
>>> factorial(y)
y!
>>> gamma(x + 1).series(x, 0, 3) # i.e. factorial(x)
2 2 2 2
pi *x EulerGamma *x
1 - EulerGamma*x + ------ + -------------- + O(x**3)
12 2
**zeta function**::
>>> zeta(4, x)
zeta(4, x)
>>> zeta(4, 1)
4
pi
---
90
>>> zeta(4, 2)
4
pi
-1 + ---
90
>>> zeta(4, 3)
4
17 pi
- -- + ---
16 90
**polynomials**::
>>> chebyshevt(2, x)
2
2*x - 1
>>> chebyshevt(4, x)
4 2
8*x - 8*x + 1
>>> legendre(2, x)
2
3*x 1
---- - -
2 2
>>> legendre(8, x)
8 6 4 2
6435*x 3003*x 3465*x 315*x 35
------- - ------- + ------- - ------ + ---
128 32 64 32 128
>>> assoc_legendre(2, 1, x)
__________
/ 2
-3*x*\/ - x + 1
>>> assoc_legendre(2, 2, x)
2
- 3*x + 3
>>> hermite(3, x)
3
8*x - 12*x
.. index:: equations; differential, diff, dsolve
Differential Equations
----------------------
In ``isympy``::
>>> f(x).diff(x, x) + f(x)
2
d
f(x) + -----(f(x))
dx dx
>>> dsolve(f(x).diff(x, x) + f(x), f(x))
f(x) = C1*cos(x) + C2*sin(x)
.. index:: equations; algebraic, solve
Algebraic equations
-------------------
In ``isympy``::
>>> solve(x**4 - 1, x)
[1, -1, -I, I]
>>> solve([x + 5*y - 2, -3*x + 6*y - 15], [x, y])
{x: -3, y: 1}
.. index:: linear algebra
Linear Algebra
==============
.. index:: Matrix
Matrices
--------
Matrices are created as instances from the Matrix class::
>>> from sympy import Matrix
>>> Matrix([[1,0], [0,1]])
[1 0]
[ ]
[0 1]
you can also put Symbols in it::
>>> x = Symbol('x')
>>> y = Symbol('y')
>>> A = Matrix([[1,x], [y,1]])
>>> A
[1 x]
[ ]
[y 1]
>>> A**2
[x*y + 1 2*x ]
[ ]
[ 2*y x*y + 1]
For more information an examples with Matrices, see the LinearAlgebraTutorial.
.. index:: pattern matching, match, Wild, WildFunction
Pattern matching
================
Use the ``.match()`` method, along with the ``Wild`` class, to perform pattern
matching on expressions. The method will return a dictionary with the required
substitutions, as follows::
>>> from sympy import *
>>> x = Symbol('x')
>>> p = Wild('p')
>>> (5*x**2).match(p*x**2)
{p: 5}
>>> q = Wild('q')
>>> (x**2).match(p*x**q)
{p: 1, q: 2}
If the match is unsuccessful, it returns ``None``::
>>> print (x+1).match(p**x)
None
One can also use the exclude parameter of the ``Wild`` class to ensure that
certain things do not show up in the result::
>>> x = Symbol('x')
>>> p = Wild('p', exclude=[1,x])
>>> print (x+1).match(x+p) # 1 is excluded
None
>>> print (x+1).match(p+1) # x is excluded
None
>>> print (x+1).match(x+2+p) # -1 is not excluded
{p_: -1}
.. _printing-tutorial:
Printing
========
There are many ways how expressions can be printed.
**Standard**
This is what ``str(expression)`` returns and it looks like this:
>>> from sympy import Integral
>>> from sympy.abc import x
>>> print x**2
x**2
>>> print 1/x
1/x
>>> print Integral(x**2, x)
Integral(x**2, x)
>>>
**Pretty printing**
This is a nice ascii-art printing produced by a ``pprint`` function:
>>> sys.displayhook = oldhook
>>> from sympy import Integral, pprint
>>> from sympy.abc import x
>>> pprint(x**2)
2
x
>>> pprint(1/x)
1
-
x
>>> pprint(Integral(x**2, x))
/
|
| 2
| x dx
|
/
If you have a unicode font installed, it should use unicode pretty printing by default. You can override this using the `use_unicode` option.:
>>> pprint(Integral(x**2, x), use_unicode=True)
⌠
⎮ 2
⎮ x dx
⌡
See also the wiki `Pretty Printing
<https://github.com/sympy/sympy/wiki/Pretty-Printing>`_ for more examples of a nice
unicode printing.
Tip: To make the pretty printing default in the python interpreter, use::
$ python
Python 2.5.2 (r252:60911, Jun 25 2008, 17:58:32)
[GCC 4.3.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from sympy import *
>>> import sys
>>> sys.displayhook = pprint
>>> var("x")
x
>>> x**3/3
3
x
--
3
>>> Integral(x**2, x) #doctest: +NORMALIZE_WHITESPACE
/
|
| 2
| x dx
|
/
**Python printing**
>>> from sympy.printing.python import python
>>> from sympy import Integral
>>> from sympy.abc import x
>>> print python(x**2)
x = Symbol('x')
e = x**2
>>> print python(1/x)
x = Symbol('x')
e = 1/x
>>> print python(Integral(x**2, x))
x = Symbol('x')
e = Integral(x**2, x)
**LaTeX printing**
>>> from sympy import Integral, latex
>>> from sympy.abc import x
>>> latex(x**2)
x^{2}
>>> latex(x**2, mode='inline')
$x^{2}$
>>> latex(x**2, mode='equation')
\begin{equation}x^{2}\end{equation}
>>> latex(x**2, mode='equation*')
\begin{equation*}x^{2}\end{equation*}
>>> latex(1/x)
\frac{1}{x}
>>> latex(Integral(x**2, x))
\int x^{2}\,dx
>>>
**MathML**
::
>>> from sympy.printing.mathml import mathml
>>> from sympy import Integral, latex
>>> from sympy.abc import x
>>> print mathml(x**2)
<apply><power/><ci>x</ci><cn>2</cn></apply>
>>> print mathml(1/x)
<apply><power/><ci>x</ci><cn>-1</cn></apply>
**Pyglet**
>>> from sympy import Integral, preview
>>> from sympy.abc import x
>>> preview(Integral(x**2, x)) #doctest:+SKIP
And a pyglet window with the LaTeX rendered expression will popup:
.. image:: pics/pngview1.png
Notes
-----
``isympy`` calls ``pprint`` automatically, so that's why you see pretty
printing by default.
Note that there is also a printing module available, ``sympy.printing``. Other
printing methods available trough this module are:
* ``pretty(expr)``, ``pretty_print(expr)``, ``pprint(expr)``: Return or print, respectively, a pretty representation of ``expr``. This is the same as the second level of representation described above.
* ``latex(expr)``, ``print_latex(expr)``: Return or print, respectively, a `LaTeX <http://www.latex-project.org/>`_ representation of ``expr``
* ``mathml(expr)``, ``print_mathml(expr)``: Return or print, respectively, a `MathML <http://www.w3.org/Math/>`_ representation of ``expr``.
* ``print_gtk(expr)``: Print ``expr`` to `Gtkmathview <http://helm.cs.unibo.it/mml-widget/>`_, a GTK widget that displays MathML code. The `Gtkmathview <http://helm.cs.unibo.it/mml-widget/>`_ program is required.
Further documentation
=====================
Now it's time to learn more about SymPy. Go through the
:ref:`SymPy User's Guide <guide>` and
:ref:`SymPy Modules Reference <module-docs>`.
Be sure to also browse our public `wiki.sympy.org <http://wiki.sympy.org/>`_,
that contains a lot of useful examples, tutorials, cookbooks that we and our
users contributed and we encourage you to edit it.