├── .gitignore ├── 99.LA_sympy_tutorial.tex ├── 99.hyperbolic_functions_sympy_tutorial.tex ├── 99.quadratic_eqn_subsitution_example.tex ├── 99.simle_ode_example.tex ├── 99.sympy_tutorial.tex ├── 99.vectors_projectsions_FORLA.tex ├── AUTHORS.txt ├── LICENSE.txt ├── README.md ├── figures └── cover_v40_noline_lite.png ├── notebook ├── cover_v40_noline_lite.png └── sympy_tutorial.ipynb ├── sympy_tutorial.pdf └── sympy_tutorial.tex /.gitignore: -------------------------------------------------------------------------------- 1 | ## Core latex/pdflatex auxiliary files: 2 | *.aux 3 | *.lof 4 | *.log 5 | *.lot 6 | *.fls 7 | *.out 8 | *.toc 9 | 10 | ## Intermediate documents: 11 | *.dvi 12 | *-converted-to.* 13 | # these rules might exclude image files for figures etc. 14 | # *.ps 15 | # *.eps 16 | # *.pdf 17 | 18 | ## Bibliography auxiliary files (bibtex/biblatex/biber): 19 | *.bbl 20 | *.bcf 21 | *.blg 22 | *-blx.aux 23 | *-blx.bib 24 | *.brf 25 | *.run.xml 26 | 27 | ## Build tool auxiliary files: 28 | *.fdb_latexmk 29 | *.synctex.gz 30 | *.synctex.gz(busy) 31 | *.pdfsync 32 | 33 | ## Auxiliary and intermediate files from other packages: 34 | 35 | # algorithms 36 | *.alg 37 | *.loa 38 | 39 | # amsthm 40 | *.thm 41 | 42 | # beamer 43 | *.nav 44 | *.snm 45 | *.vrb 46 | 47 | #(e)ledmac/(e)ledpar 48 | *.end 49 | *.[1-9] 50 | *.[1-9][0-9] 51 | *.[1-9][0-9][0-9] 52 | *.[1-9]R 53 | *.[1-9][0-9]R 54 | *.[1-9][0-9][0-9]R 55 | *.eledsec[1-9] 56 | *.eledsec[1-9]R 57 | *.eledsec[1-9][0-9] 58 | *.eledsec[1-9][0-9]R 59 | *.eledsec[1-9][0-9][0-9] 60 | *.eledsec[1-9][0-9][0-9]R 61 | 62 | # glossaries 63 | *.acn 64 | *.acr 65 | *.glg 66 | *.glo 67 | *.gls 68 | 69 | # hyperref 70 | *.brf 71 | 72 | # listings 73 | *.lol 74 | 75 | # makeidx 76 | *.idx 77 | *.ilg 78 | *.ind 79 | *.ist 80 | 81 | # minitoc 82 | *.maf 83 | *.mtc 84 | *.mtc0 85 | 86 | # minted 87 | *.pyg 88 | 89 | # morewrites 90 | *.mw 91 | 92 | # nomencl 93 | *.nlo 94 | 95 | # sagetex 96 | *.sagetex.sage 97 | *.sagetex.py 98 | *.sagetex.scmd 99 | 100 | # sympy 101 | *.sout 102 | *.sympy 103 | sympy-plots-for-*.tex/ 104 | 105 | # todonotes 106 | *.tdo 107 | 108 | # xindy 109 | *.xdy 110 | -------------------------------------------------------------------------------- /99.LA_sympy_tutorial.tex: -------------------------------------------------------------------------------- 1 | %!TEX root = sympy_tutorial.tex 2 | 3 | 4 | 5 | 6 | %======================================================================= matrices 7 | \section{Linear algebra} 8 | \label{sec:linear_algebra} 9 | 10 | %\ifthenelse{\boolean{FORLA}}{ 11 | 12 | 13 | \small 14 | \begin{verbatimtab} 15 | from sympy import Matrix 16 | \end{verbatimtab} 17 | \normalsize 18 | 19 | \noindent 20 | A matrix $A \in \mathbb{R}^{m\times n}$ is a rectangular array of real numbers with $m$ rows and $n$ columns. 21 | To specify a matrix $A$, we specify the values for its $mn$ components $a_{11}, a_{12}, \ldots, a_{mn}$ 22 | as a list of lists: 23 | 24 | \small 25 | \begin{verbatimtab} 26 | >>> A = Matrix( [[ 2,-3,-8, 7], 27 | [-2,-1, 2,-7], 28 | [ 1, 0,-3, 6]] ) 29 | \end{verbatimtab} 30 | \normalsize 31 | 32 | \noindent 33 | Use the square brackets to access the matrix elements or to obtain a submatrix: 34 | 35 | 36 | 37 | \small 38 | \begin{verbatimtab} 39 | >>> A[0,1] # row 0, col 1of A 40 | -3 41 | >>> A[0:2,0:3] # top-left 2x3 submatrix of A 42 | [ 2, -3, -8] 43 | [-2, -1, 2] 44 | \end{verbatimtab} 45 | \normalsize 46 | 47 | \noindent 48 | Some commonly used matrices can be created with shortcut methods: 49 | 50 | 51 | 52 | \small 53 | \begin{verbatimtab} 54 | >>> eye(2) # 2x2 identity matrix 55 | [1, 0] 56 | [0, 1] 57 | >>> zeros((2, 3)) 58 | [0, 0, 0] 59 | [0, 0, 0] 60 | \end{verbatimtab} 61 | \normalsize 62 | 63 | %TODO explain matrix concatenation operations: 64 | %>>> M1.row_join(M2) 65 | %[1 0 0 0 0 0 0] 66 | %[ ] 67 | %[0 1 0 0 0 0 0] 68 | %[ ] 69 | %[0 0 1 0 0 0 0] 70 | %>>> M3 = zeros((4, 3)) 71 | %>>> M1.col_join(M3) 72 | 73 | 74 | \noindent 75 | Standard algebraic operations like 76 | addition \texttt{+}, subtraction \texttt{-}, multiplication \texttt{*}, 77 | and exponentiation \texttt{**} work as expected for \texttt{Matrix} objects. 78 | % 79 | The \texttt{transpose} operation flips the matrix through its diagonal: 80 | 81 | \small 82 | \begin{verbatimtab} 83 | >>> A.transpose() # the same as A.T 84 | [ 2, -2, 1] 85 | [-3, -1, 0] 86 | [-8, 2, -3] 87 | [ 7, -7, 6] 88 | \end{verbatimtab} 89 | \normalsize 90 | 91 | \noindent 92 | Recall that the transpose is also used to convert row vectors into column vectors and vice versa. 93 | 94 | 95 | \subsection{Row operations} 96 | \label{matrices:row_operations} 97 | 98 | \small 99 | \begin{verbatimtab} 100 | >>> M = eye(3) 101 | >>> M[1,:] = M[1,:] + 3*M[0,:] 102 | >>> M 103 | [1, 0, 0] 104 | [3, 1, 0] 105 | [0, 0, 1] \end{verbatimtab} 106 | \normalsize 107 | 108 | The notation \texttt{M[i,:]} refers to entire rows of the matrix. 109 | The first argument specifies the $0$-based row index, 110 | for example the first row of~\texttt{M} is \texttt{M[0,:]}. 111 | The code example above implements the row operation $R_2 \gets R_2 + 3R_1$. 112 | To scale a row \texttt{i} by constant \texttt{c}, use the command \texttt{ M[i,:] = c*M[i,:]}. 113 | To swap rows \texttt{i} and \texttt{j}, use can use the \texttt{Python} tuple-assignment syntax \texttt{ M[i,:], M[j,:] = M[j,:], M[i,:]}. 114 | %The method \texttt{row\_op} takes two arguments as inputs: 115 | %the first argument specifies the $0$-based index of the row you want to act on, 116 | %while the second argument is a function of the form \texttt{f(val,j)} 117 | %that describes how you want the value \texttt{val=M[i,j]} to be transformed. 118 | % The above call to \texttt{row\_op} implements the row operation $R_2 \gets R_2 + 3R_1$. 119 | %The expression \texttt{lambda a,b: a+b} is the \texttt{Python} syntax for creating an anonymous function with arguments 120 | %\texttt{a} and \texttt{b}, which computes their sum \texttt{a+b}. 121 | 122 | \vspace{-2mm} 123 | 124 | \subsection{Reduced row echelon form} 125 | \label{matrices:reduced_row_echelon_form} 126 | 127 | The Gauss--Jordan elimination procedure is a sequence of row operations you can perform 128 | on any matrix to bring it to its \emph{reduced row echelon form} (RREF). 129 | In \texttt{SymPy}, matrices have a \texttt{rref} method that computes their RREF: 130 | 131 | \small 132 | \begin{verbatimtab} 133 | >>> A = Matrix( [[2,-3,-8, 7], 134 | [-2,-1,2,-7], 135 | [1 ,0,-3, 6]]) 136 | >>> A.rref() 137 | ([1, 0, 0, 0] # RREF of A 138 | [0, 1, 0, 3] # locations of pivots 139 | [0, 0, 1, -2], [0, 1, 2] ) 140 | \end{verbatimtab} 141 | \normalsize 142 | 143 | \noindent 144 | Note the \texttt{rref} method returns a tuple of values: 145 | the first value is the RREF of $A$, 146 | while the second tells you the indices of the leading ones (also known as pivots) in the RREF of $A$. 147 | To get just the RREF of $A$, select the $0$\textsuperscript{th} entry form the tuple: \texttt{A.rref()[0]}. 148 | 149 | % 150 | %\small 151 | %\begin{verbatimtab} 152 | %>>> Arref = A.rref()[0] 153 | %>>> Arref 154 | %[1, 0, 0, 0] 155 | %[0, 1, 0, 3] 156 | %[0, 0, 1, -2] 157 | %\end{verbatimtab} 158 | %\normalsize 159 | 160 | \vspace{-2mm} 161 | 162 | 163 | \subsection{Matrix fundamental spaces} 164 | \label{matrices:matrix_fundamental_spaces} 165 | 166 | Consider the matrix $A \in \mathbb{R}^{m\times n}$. 167 | The fundamental spaces of a matrix are its column space $\mathcal{C}(A)$, 168 | its null space $\mathcal{N}(A)$, 169 | and its row space $\mathcal{R}(A)$. 170 | These vector spaces are important when you consider the matrix product 171 | $A\vec{x}=\vec{y}$ as ``applying'' the linear transformation $T_A:\mathbb{R}^n \to \mathbb{R}^m$ 172 | to an input vector $\vec{x} \in \mathbb{R}^n$ to produce the output vector $\vec{y} \in \mathbb{R}^m$. 173 | 174 | \textbf{Linear transformations} $T_A:\mathbb{R}^n \to \mathbb{R}^m$ (vector functions) 175 | \textbf{are equivalent to $m\times n$ matrices}. 176 | This is one of the fundamental ideas in linear algebra. 177 | You can think of $T_A$ as the abstract description of the transformation 178 | and $A \in \mathbb{R}^{m\times n}$ as a concrete implementation of $T_A$. 179 | By this equivalence, 180 | the fundamental spaces of a matrix $A$ 181 | tell us facts about the domain and image of the linear transformation $T_A$. 182 | The columns space $\mathcal{C}(A)$ is the same as the image space space $\textrm{Im}(T_A)$ (the set of all possible outputs). 183 | The null space $\mathcal{N}(A)$ is the same as the kernel $\textrm{Ker}(T_A)$ (the set of inputs that $T_A$ maps to the zero vector). 184 | The row space $\mathcal{R}(A)$ is the orthogonal complement of the null space. 185 | Input vectors in the row space of $A$ are in one-to-one correspondence with the output vectors in the column space of $A$. 186 | 187 | Okay, enough theory! Let's see how to compute the fundamental spaces of the matrix $A$ defined above. 188 | The non-zero rows in the reduced row echelon form of $A$ are a basis for its row space: 189 | 190 | \small 191 | \begin{verbatimtab} 192 | >>> [ A.rref()[0][r,:] for r in A.rref()[1] ] # R(A) 193 | [ [1, 0, 0, 0], [0, 1, 0, 3], [0, 0, 1, -2] ] 194 | \end{verbatimtab} 195 | \normalsize 196 | 197 | \noindent 198 | The column space of $A$ is the span of the columns of $A$ that contain the pivots 199 | in the reduced row echelon form of $A$: 200 | 201 | 202 | 203 | \small 204 | \begin{verbatimtab} 205 | >>> [ A[:,c] for c in A.rref()[1] ] # C(A) 206 | [ [ 2] [-3] [-8] 207 | [-2], [-1], [ 2] 208 | [ 1] [ 0] [-3] ] 209 | \end{verbatimtab} 210 | \normalsize 211 | 212 | \noindent 213 | Note we took columns from the original matrix $A$ and not its RREF. 214 | 215 | 216 | To find the null space of $A$, call its \texttt{nullspace} method: 217 | 218 | \small 219 | \begin{verbatimtab} 220 | >>> A.nullspace() # N(A) 221 | [ [0, -3, 2, 1] ] 222 | \end{verbatimtab} 223 | \normalsize 224 | \subsection{Determinants} 225 | \label{matrices:determinants} 226 | 227 | The determinant of a matrix, 228 | denoted $\det(A)$ or $|A|$, 229 | is a particular way to multiply the entries of the matrix to produce a single number. 230 | 231 | 232 | 233 | \small 234 | \begin{verbatimtab} 235 | >>> M = Matrix( [[1, 2, 3], 236 | [2,-2, 4], 237 | [2, 2, 5]] ) 238 | >>> M.det() 239 | 2 240 | \end{verbatimtab} 241 | \normalsize 242 | 243 | \noindent 244 | Determinants are used for all kinds of tasks: 245 | to compute areas and volumes, 246 | to solve systems of equations, 247 | and to check whether a matrix is invertible or not. 248 | 249 | \subsection{Matrix inverse} 250 | \label{matrices:matrix_inverse} 251 | 252 | For every invertible matrix $A$, 253 | there exists an inverse matrix $A^{-1}$ which \emph{undoes} the effect of $A$. 254 | The cumulative effect of the product of $A$ and $A^{-1}$ (in any order) 255 | is the identity matrix: $AA^{-1}= A^{-1}A=\mathbbm{1}$. 256 | 257 | 258 | 259 | \small 260 | \begin{verbatimtab} 261 | >>> A = Matrix( [[1,2], 262 | [3,9]] ) 263 | >>> A.inv() 264 | [ 3, -2/3] 265 | [-1, 1/3] 266 | >>> A.inv()*A 267 | [1, 0] 268 | [0, 1] 269 | >>> A*A.inv() 270 | [1, 0] 271 | [0, 1] 272 | \end{verbatimtab} 273 | \normalsize 274 | 275 | \noindent 276 | The matrix inverse $A^{-1}$ plays the role of division by $A$. 277 | 278 | 279 | \vspace{-3mm} 280 | 281 | \subsection{Eigenvectors and eigenvalues} 282 | \label{matrices:eigenvectors_and_eigenvalues} 283 | 284 | \vspace{-1mm} 285 | 286 | When a matrix is multiplied by one of its eigenvectors the output 287 | is the same eigenvector multiplied by a constant $A\vec{e}_\lambda =\lambda\vec{e}_\lambda$. 288 | The constant $\lambda$ (the Greek letter \emph{lambda}) is called an \emph{eigenvalue} of $A$. 289 | % and the vector is called an \emph{eigenvector}. 290 | % \[ 291 | % \Rightarrow 292 | % \quad 293 | % \left( A-\lambda \mathbbm{1}\right) \vec{e}_\lambda = \vec{0}. 294 | % \] 295 | %Thinking of matrices in term of their eigenvalues and eigenvectors is 296 | %a very powerful technique for describing their properties. 297 | %In particular 298 | 299 | To find the eigenvalues of a matrix, start from the definition $A\vec{e}_\lambda =\lambda\vec{e}_\lambda$, 300 | insert the identity $\mathbbm{1}$, 301 | and rewrite it as a null-space problem: 302 | \[ 303 | A\vec{e}_\lambda =\lambda\mathbbm{1}\vec{e}_\lambda 304 | \qquad 305 | \Rightarrow 306 | \qquad 307 | \left(A - \lambda\mathbbm{1}\right)\vec{e}_\lambda = \vec{0}. 308 | \] 309 | This equation will have a solution whenever $|A - \lambda\mathbbm{1}|=0$.\footnote{The invertible matrix theorem states 310 | that a matrix has a non-empty null space if and only if its determinant is zero.} 311 | % 312 | The eigenvalues of $A \in \mathbb{R}^{n \times n}$, 313 | denoted $\{ \lambda_1, \lambda_2, \ldots, \lambda_n \}$, 314 | are the roots of the \emph{characteristic polynomial} $p(\lambda)=|A - \lambda \mathbbm{1}|$. 315 | 316 | 317 | 318 | \small 319 | \begin{verbatimtab} 320 | >>> A = Matrix( [[ 9, -2], 321 | [-2, 6]] ) 322 | >>> A.eigenvals() # same as solve( det(A-eye(2)*x), x) 323 | {5: 1, 10: 1} # eigenvalues 5 and 10 with multiplicity 1 324 | >>> A.eigenvects() 325 | [(5, 1, [ 1] 326 | [ 2] ), (10, 1, [-2] 327 | [ 1] )] 328 | \end{verbatimtab} 329 | \normalsize 330 | 331 | \noindent 332 | 333 | 334 | Certain matrices can be written entirely in terms of their eigenvectors and their eigenvalues. 335 | Consider the matrix $\Lambda$ (capital Greek \emph{L}) that has the eigenvalues of the matrix $A$ on the diagonal, 336 | and the matrix $Q$ constructed from the eigenvectors of~$A$ as columns: 337 | \[ 338 | \Lambda = 339 | \scriptscriptstyle 340 | \begin{bmatrix} 341 | \lambda_1 & \cdots & 0 \\ 342 | \vdots & \ddots & 0 \\ 343 | 0 & 0 & \lambda_n 344 | \end{bmatrix}\!, 345 | \ \ 346 | {\textstyle Q} \: 347 | = 348 | \begin{bmatrix} 349 | \big| & &\Huge| \\[1.2mm] 350 | \vec{e}_{\lambda_1} & \! \cdots \! & \large\vec{e}_{\lambda_n} \\[1.2mm] 351 | \big| & & \Huge| 352 | \end{bmatrix}\!, 353 | \ \ 354 | {\textstyle 355 | \textrm{then} 356 | \ \ 357 | A = Q\Lambda Q^{-1}. 358 | } 359 | \] 360 | 361 | Matrices that can be written this way are called \emph{diagonalizable}. 362 | %The matrix $A$ can be written as the product of three matrices 363 | %$A=Q\Lambda Q^{-1}$. 364 | %This is called the \emph{eigendecomposition} of $A$. 365 | %The matrix $Q$ contains the eigenvectors of $A$ as columns. 366 | %The matrix $\Lambda$ contains the eigenvalues of $A$ on its diagonal. 367 | To \emph{diagonalize} a matrix $A$ is to find its $Q$ and $\Lambda$ matrices: 368 | 369 | \small 370 | \begin{verbatimtab} 371 | >>> Q, L = A.diagonalize() 372 | >>> Q # the matrix of eigenvectors 373 | [1, -2] # as columns 374 | [2, 1] 375 | >>> Q.inv() 376 | [ 1/5, 2/5] 377 | [-2/5, 1/5] 378 | >>> L # the matrix of eigenvalues 379 | [5, 0] 380 | [0, 10] 381 | >>> Q*L*Q.inv() # eigendecomposition of A 382 | [ 9, -2] 383 | [-2, 6] 384 | >>> Q.inv()*A*Q # obtain L from A and Q 385 | [5, 0] 386 | [0, 10] 387 | \end{verbatimtab} 388 | \normalsize 389 | 390 | 391 | Not all matrices are diagonalizable. 392 | You can check if a matrix is diagonalizable by calling its \texttt{is\_diagonalizable} method: 393 | 394 | \small 395 | \begin{verbatimtab} 396 | >>> A.is_diagonalizable() 397 | True 398 | >>> B = Matrix( [[1, 3], 399 | [0, 1]] ) 400 | >>> B.is_diagonalizable() 401 | False 402 | >>> B.eigenvals() 403 | {1: 2} # eigenvalue 1 with multiplicity 2 404 | >>> B.eigenvects() 405 | [(1, 2, [1] 406 | [0] )] 407 | \end{verbatimtab} 408 | \normalsize 409 | 410 | \noindent 411 | The matrix $B$ is not diagonalizable because it doesn't have a full set of eigenvectors. 412 | To diagonalize a $2\times 2$ matrix, we need two orthogonal eigenvectors but $B$ has only a single eigenvector. 413 | Therefore, we can't construct the matrix of eigenvectors $Q$ (we're missing a column!) 414 | and so $B$ is not diagonalizable. 415 | 416 | Non-square matrices don't have eigenvectors and therefore don't have an eigendecomposition. 417 | Instead, we can use the \emph{singular value decomposition} to break up a non-square matrix $A$ into 418 | left singular vectors, 419 | right singular vectors, 420 | and a diagonal matrix of singular values. 421 | Use the \texttt{singular\_values} method on any matrix to find its singular values. 422 | 423 | %\subsection{QR decomposition} 424 | %\label{matrices:qr_decomposition} 425 | 426 | %It is possible to write a matrix $A$ as the product of an orthogonal matrix $Q$ 427 | %and an upper triangular matrix $R$. 428 | %This is known as the QR-decomposition. 429 | 430 | %\small 431 | %\begin{verbatimtab} 432 | %>>> A=Matrix( [[12,-51,4], 433 | % [6,167,-68], 434 | % [-4,24,-41]] ) 435 | %>>> Q,R = A.QRdecomposition() 436 | %>>> Q 437 | %[ 6/7, -69/175, -58/175] 438 | %[ 3/7, 158/175, 6/175] 439 | %[-2/7, 6/35, -33/35] 440 | %>>> Q*Q.T # verify Q is orthogonal 441 | %[1, 0, 0] 442 | %[0, 1, 0] 443 | %[0, 0, 1] 444 | %>>> R # and R is upper triangular 445 | %[14, 21, -14] 446 | %[ 0, 175, -70] 447 | %[ 0, 0, 35] 448 | %>>> Q*R # verify QR = A 449 | %[12, -51, 4] 450 | %[ 6, 167, -68] 451 | %[-4, 24, -41] 452 | %\end{verbatimtab} 453 | %\normalsize 454 | % 455 | %\noindent 456 | %Each \texttt{sympy} matrix is also equipped with 457 | %\href{https://en.wikipedia.org/wiki/LU_decomposition}{\texttt{LUdecomposition}} 458 | %and \href{https://en.wikipedia.org/wiki/Cholesky_decomposition}{\texttt{cholesky}} decomposition methods. 459 | 460 | 461 | -------------------------------------------------------------------------------- /99.hyperbolic_functions_sympy_tutorial.tex: -------------------------------------------------------------------------------- 1 | %!TEX root = sympy_tutorial.tex 2 | 3 | \subsection{Hyperbolic trigonometric functions} 4 | \label{basics:hyperbolic_trigonometric_functions} 5 | 6 | The hyperbolic sine and cosine in \texttt{SymPy} are denoted \texttt{sinh} and \texttt{cosh} respectively 7 | and \texttt{SymPy} is smart enough to recognize them when simplifying expressions: 8 | 9 | \small 10 | \begin{verbatimtab} 11 | >>> simplify( (exp(x)+exp(-x))/2 ) 12 | cosh(x) 13 | >>> simplify( (exp(x)-exp(-x))/2 ) 14 | sinh(x) 15 | \end{verbatimtab} 16 | \normalsize 17 | Recall that $x=\cosh(\mu)$ and $y=\sinh(\mu)$ are defined as $x$ and $y$ coordinates of a point on the 18 | the hyperbola with equation $x^2 - y^2 = 1$ and therefore satisfy the identity $\cosh^2 x - \sinh^2 x =1$: 19 | 20 | 21 | 22 | \small 23 | \begin{verbatimtab} 24 | >>> simplify( cosh(x)**2 - sinh(x)**2 ) 25 | 1 26 | \end{verbatimtab} 27 | \normalsize -------------------------------------------------------------------------------- /99.quadratic_eqn_subsitution_example.tex: -------------------------------------------------------------------------------- 1 | %!TEX root = sympy_tutorial.tex 2 | 3 | To solve a specific equation like $x^2+2x-8=0$, 4 | we can substitute the coefficients $a=1$, $b=2$, and $c=-8$ into 5 | the general solution to obtain the same result: 6 | 7 | \small 8 | \begin{verbatimtab} 9 | >>> gen_sol = solve( a*x**2 + b*x + c, x) 10 | >>> [ gen_sol[0].subs({'a':1,'b':2,'c':-8}), 11 | gen_sol[1].subs({'a':1,'b':2,'c':-8}) ] 12 | [2, -4] 13 | \end{verbatimtab} 14 | \normalsize 15 | 16 | -------------------------------------------------------------------------------- /99.simle_ode_example.tex: -------------------------------------------------------------------------------- 1 | %!TEX root = sympy_tutorial.tex 2 | 3 | \noindent 4 | The exponential function $f(x)=e^x$ is equal to its own derivative: 5 | 6 | \small 7 | \begin{verbatimtab} 8 | >>> diff( exp(x), x) # same as diff( E**x, x) 9 | exp(x) # same as E**x 10 | \end{verbatimtab} 11 | \normalsize 12 | 13 | \noindent 14 | A differential equation is an equation that relates some unknown function $f(x)$ to its derivative. 15 | An example of a differential equation is $f'(x)=f(x)$. 16 | What is the function $f(x)$ which is equal to its derivative? 17 | You can either try to guess what $f(x)$ is or use the \texttt{dsolve} function: 18 | 19 | \small 20 | \begin{verbatimtab} 21 | >>> x = symbols('x') 22 | >>> f = symbols('f', cls=Function) # can now use f(x) 23 | >>> dsolve( f(x) - diff(f(x),x), f(x) ) 24 | f(x) == C1*exp(x) 25 | \end{verbatimtab} 26 | \normalsize 27 | 28 | \noindent 29 | We'll discuss \texttt{dsolve} again in the section on mechanics. 30 | -------------------------------------------------------------------------------- /99.sympy_tutorial.tex: -------------------------------------------------------------------------------- 1 | %!TEX root = sympy_tutorial.tex 2 | 3 | %\input{99.sympy_tutorial.tex} 4 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 5 | 6 | 7 | 8 | 9 | \ifthenelse{\boolean{TUTORIAL}}{}{ 10 | 11 | \vspace*{-5mm} 12 | 13 | Computers can be very useful for dealing with complicated math expressions 14 | or when slogging through tedious calculations. 15 | Throughout this book we used \texttt{SymPy} to illustrate several concepts from math and physics. 16 | % to illustrate how computers can help us manipulate math and physics objects 17 | We'll now review all the math and physics tools available through the \texttt{SymPy} command line. 18 | Don't worry if you're not a computer person; 19 | we'll only discuss concepts we covered in the book, 20 | and the computer commands we'll learn are very similar to the math operations you're already familiar with. 21 | This section also serves as a final review of the material covered in the book. 22 | } 23 | 24 | 25 | %======================================================================= introduction 26 | \section*{Introduction} 27 | % \label{sec:sympytut_introduction} 28 | 29 | You can use a computer algebra system (CAS) to compute complicated math expressions, 30 | solve equations, 31 | perform calculus procedures, 32 | and simulate physics systems. 33 | 34 | All computer algebra systems offer essentially the same functionality, 35 | so it doesn't matter which system you use: 36 | there are free systems like \texttt{SymPy}, \texttt{Magma}, or \texttt{Octave}, 37 | and commercial systems like \texttt{Maple}, \texttt{MATLAB}, and \texttt{Mathematica}. 38 | This tutorial is an introduction to \texttt{SymPy}, 39 | which is a \emph{symbolic} computer algebra system written in the programming language Python. 40 | In a symbolic CAS, 41 | numbers and operations are represented symbolically, so the answers obtained are exact. 42 | For example, the number $\sqrt{2}$ is represented in \texttt{SymPy} as the object \texttt{Pow(2,1/2)}, 43 | whereas in \emph{numerical} computer algebra systems like \texttt{Octave}, the number $\sqrt{2}$ is 44 | represented as the approximation $1.41421356237310$ (a \texttt{float}). 45 | For most purposes the approximation is okay, 46 | but sometimes approximations can lead to problems: 47 | \texttt{float(sqrt(2))*float(sqrt(2)) = 2.00000000000000044} $\neq 2$. 48 | Because \texttt{SymPy} uses exact representations, 49 | you'll never run into such problems: \texttt{Pow(2,1/2)*Pow(2,1/2)}$ = 2$. 50 | 51 | 52 | \ifthenelse{\boolean{TUTORIAL}}{ 53 | This tutorial is organized as follows. 54 | We'll begin by introducing the \texttt{SymPy} basics and the bread-and-butter functions 55 | used for manipulating expressions and solving equations. 56 | Afterward, we'll discuss the \texttt{SymPy} functions that implement calculus operations like differentiation and integration. 57 | We'll also introduce the functions used to deal with vectors and complex numbers. 58 | Later we'll see how to use vectors and integrals to understand Newtonian mechanics. 59 | \ifthenelse{\boolean{FORLA}} 60 | {In the last section, we'll introduce the linear algebra functions available in \texttt{SymPy}.} 61 | {} 62 | }{} 63 | 64 | 65 | This tutorial presents many explanations as code snippets. 66 | Be sure to try the code examples on your own by typing the commands into \texttt{SymPy}. 67 | It's always important to verify for yourself! 68 | %Don't be a passive reader: 69 | %type out the commands presented. 70 | 71 | 72 | %\vspace{1cm} % to push REPL at top of col2 73 | 74 | %======================================================================= using_sympy 75 | \section*{Using SymPy} 76 | % \label{sec:sympytut_using_sympy} 77 | 78 | The easiest way to use \texttt{SymPy}, 79 | provided you're connected to the internet, 80 | is to visit \href{http://live.sympy.org}{\texttt{http://live.sympy.org}}. 81 | You'll be presented with an interactive prompt into which 82 | you can enter your commands---right in your browser. 83 | 84 | If you want to use \texttt{SymPy} on your own computer, 85 | you must first install Python and the Python package \texttt{sympy}. 86 | You can then open a command prompt and start a Python session using: 87 | 88 | 89 | 90 | \small 91 | \begin{verbatimtab} 92 | you@host> python 93 | Python X.Y.Z 94 | [GCC a.b.c (Build Info)] on platform 95 | Type "help", "copyright", or "license" for more information. 96 | >>> 97 | \end{verbatimtab} 98 | \normalsize 99 | 100 | \noindent 101 | The \texttt{>{}>{}>} prompt indicates you're in the Python shell which accepts Python commands. 102 | Type the following in the Python shell: 103 | 104 | \small 105 | \begin{verbatimtab} 106 | >>> from sympy import * 107 | >>> 108 | \end{verbatimtab} 109 | \normalsize 110 | 111 | \noindent 112 | The command \texttt{from sympy import *}$\;$ imports all the \texttt{SymPy} functions into the current namespace. 113 | All \texttt{SymPy} functions are now available to you. 114 | To exit the python shell press \texttt{CTRL+D}. 115 | 116 | For an even better experience, 117 | you can try \texttt{JupyterLab}, 118 | which is a web interface for accessing the Python shell. 119 | Click \href{https://github.com/jupyterlab/jupyterlab-desktop#jupyterlab-desktop}{here} 120 | to download the JupyterLab Desktop application. 121 | 122 | 123 | Each section \ifthenelse{\boolean{TUTORIAL}}{of this tutorial}{in this appendix} begins with a python \texttt{import} statement 124 | for the functions used in that section. 125 | If you use the statement \texttt{from sympy import *}\,\, in the beginning of your code, 126 | you don't need to run these individual import statements, 127 | but I've included them so you'll know which 128 | \texttt{SymPy} vocabulary is covered in each section. 129 | 130 | 131 | 132 | 133 | 134 | % 135 | \ifthenelse{\boolean{TUTORIAL}}{ 136 | \def\lesection{\section} 137 | }{ 138 | \def\lesection{\section*} 139 | } 140 | 141 | %======================================================================= basics 142 | \lesection{Fundamentals of mathematics} 143 | \label{sec:sympytut_fundamentals_of_mathematics} 144 | 145 | Let's begin by learning about the basic \texttt{SymPy} objects and the operations we can carry out on them. 146 | We'll learn the \texttt{SymPy} equivalents of 147 | \ifthenelse{\boolean{TUTORIAL}}{many math verbs like}{the math verbs we used in Chapter~1:} 148 | ``to solve'' (an equation), 149 | %``to simplify'' (an expression), 150 | ``to expand'' (an expression), 151 | ``to factor'' (a polynomial). 152 | 153 | \subsection{Numbers} 154 | \label{basics:numbers} 155 | 156 | \small 157 | \begin{verbatimtab} 158 | >>> from sympy import sympify, S, evalf, N 159 | \end{verbatimtab} 160 | \normalsize 161 | 162 | \noindent 163 | In Python, there are two types of number objects: \texttt{int}s and \texttt{float}s. 164 | 165 | \small 166 | \begin{verbatimtab} 167 | >>> 3 168 | 3 # an int 169 | >>> 3.0 170 | 3.0 # a float 171 | \end{verbatimtab} 172 | \normalsize 173 | 174 | \noindent 175 | Integer objects in Python are a faithful representation of the set of integers $\mathbb{Z}=\{\ldots,-2,-1,0,1,2,\ldots\}$. 176 | Floating point numbers are approximate representations of the reals $\mathbb{R}$. 177 | %The name ``floating point'' comes from the fact that \texttt{float}s can represent very small numbers 178 | %and very large numbers (by moving the decimal point). 179 | A floating point number has 16 decimals of precision. 180 | % you can think of floats as rational numbers of the form $\frac{m}{10^n}$ where $m<10^{16}$ and $< n <$. 181 | 182 | %We won't go any further into the implementation details of how numbers are represented; 183 | %I just wanted to point out the difference between \texttt{int}s, \texttt{float}s, 184 | %and the set of real numbers $\mathbb{R}$. 185 | %Sandy said: these lines could be more fitting for a teacher's guide, but I think for students it is TMI, since the differences are explained concisely and neatly above. 186 | 187 | 188 | % Floats are only approximations, but if you want to do calculations with floats you can use the GPU 189 | 190 | Special care is required when specifying rational numbers 191 | if you want to get exact answers. 192 | If you try to divide two numbers, 193 | Python will produce a floating point number approximation: 194 | \small 195 | \begin{verbatimtab} 196 | >>> 1/7 197 | 0.14285714285714285 # a float 198 | \end{verbatimtab} 199 | \normalsize 200 | 201 | \noindent 202 | The floating point number $0.14285714285714285$ is an approximation of the exact number $\frac{1}{7} \in \mathbb{Q}$. \index{fraction} 203 | The \texttt{float} approximation has 16 decimals 204 | while the decimal expansion of $\frac{1}{7}$ is infinitely long. 205 | To obtain an \emph{exact} representation of $\frac{1}{7}$, 206 | you need to create a \texttt{SymPy} expression. 207 | You can \texttt{sympify} any expression using the shortcut function \texttt{S()}: 208 | 209 | \small 210 | \begin{verbatimtab} 211 | >>> S('1/7') # = sympify('1/7') 212 | 1/7 # = Rational(1,7) 213 | \end{verbatimtab} 214 | \normalsize 215 | 216 | \noindent 217 | Note the input to \texttt{S()} is specified as a text string delimited by quotes. 218 | We could have achieved the same result using \texttt{S('1')/7} since 219 | a \texttt{SymPy} object divided by an \texttt{int} is a \texttt{SymPy} object. 220 | 221 | Except for the tricky Python division operator, 222 | other math operators like addition \texttt{+}, subtraction \texttt{-}, 223 | and multiplication \texttt{*} work as you would expect. 224 | The syntax \texttt{**} is used to denote exponentiation: \index{exponent} 225 | \small 226 | \begin{verbatimtab} 227 | >>> 2**10 # same as S('2^10') 228 | 1024 229 | \end{verbatimtab} 230 | \normalsize 231 | 232 | \noindent 233 | When solving math problems, 234 | it's best to work with \texttt{SymPy} objects, 235 | and wait to compute the numeric answer in the end. 236 | To obtain a numeric approximation of a \texttt{SymPy} object as a \texttt{float}, 237 | call its \texttt{.evalf()} method: %Sandy said: what do you mean by 'call'? 238 | 239 | \small 240 | \begin{verbatimtab} 241 | >>> pi 242 | pi 243 | >>> pi.evalf() # = pi.n() = N(pi) 244 | 3.14159265358979 245 | \end{verbatimtab} 246 | \normalsize 247 | 248 | \noindent 249 | The method \texttt{.n()} is equivalent to \texttt{.evalf()}. 250 | The global \texttt{SymPy} function \texttt{N()} can also be used to to compute numerical values. 251 | % 252 | You can easily change the number of digits of precision of the approximation. \index{precision} 253 | Enter \texttt{pi.n(400)} to obtain an approximation of $\pi$ to 400 decimals. 254 | 255 | \subsection{Symbols} 256 | \label{basics:symbols} 257 | 258 | \small 259 | \begin{verbatimtab} 260 | >>> from sympy import Symbol, symbols 261 | \end{verbatimtab} 262 | \normalsize 263 | 264 | \noindent 265 | Python is a civilized language so there's no need to define variables before assigning values to them. 266 | When you write \texttt{a = 3}, you define a new name \texttt{a} and set it to the value \texttt{3}. 267 | You can now use the name \texttt{a} in subsequent calculations. 268 | 269 | Most interesting \texttt{SymPy} calculations require us to define \texttt{symbols}, 270 | which are the \texttt{SymPy} objects for representing variables and unknowns. 271 | For your convenience, when \href{http://live.sympy.org}{\texttt{live.sympy.org}} starts, 272 | it runs the following commands automatically: 273 | 274 | \small 275 | \begin{verbatimtab} 276 | >>> from sympy import * 277 | >>> x, y, z, t = symbols('x y z t') 278 | >>> k, m, n = symbols('k m n', integer=True) 279 | >>> f, g, h = symbols('f g h', cls=Function) 280 | \end{verbatimtab} 281 | \normalsize 282 | 283 | \noindent 284 | The first statement imports all the \texttt{SymPy} functions. 285 | The other three statements define some generic symbols \texttt{x}, \texttt{y}, \texttt{z}, and \texttt{t}, 286 | and several other symbols with special properties. 287 | 288 | Note the difference between the following two statements: 289 | 290 | \small 291 | \begin{verbatimtab} 292 | >>> x + 2 293 | x + 2 # an Add expression 294 | >>> p + 2 295 | NameError: name 'p' is not defined 296 | \end{verbatimtab} 297 | \normalsize 298 | 299 | \noindent 300 | The name \texttt{x} is defined as a symbol, so \texttt{SymPy} knows that \texttt{x + 2} is an expression; 301 | but the variable \texttt{p} is not defined, so \texttt{SymPy} doesn't know what to make of \texttt{p + 2}. 302 | To use \texttt{p} in expressions, 303 | you must first define it as a symbol: 304 | 305 | \small 306 | \begin{verbatimtab} 307 | >>> p = Symbol('p') # the same as p = symbols('p') 308 | >>> p + 2 309 | p + 2 # = Add(Symbol('p'), Integer(2)) 310 | \end{verbatimtab} 311 | \normalsize 312 | 313 | 314 | \printcp 315 | 316 | \noindent 317 | You can define a sequence of variables using the following notation: 318 | \small 319 | \begin{verbatimtab} 320 | >>> a0, a1, a2, a3 = symbols('a0:4') 321 | \end{verbatimtab} 322 | \normalsize 323 | 324 | \noindent 325 | You can use any name you want for a variable, 326 | but it's best if you avoid the letters \texttt{Q,C,O,S,I,N} and \texttt{E} because they have special uses in \texttt{SymPy}: 327 | \texttt{I} is the unit imaginary number $i\eqdef\sqrt{-1}$, 328 | \texttt{E} is the base of the natural logarithm, 329 | \texttt{S()} is the \texttt{sympify} function, 330 | \texttt{N()} is used to obtain numeric approximations, and 331 | \texttt{O} is used for big-\texttt{O} notation. 332 | 333 | 334 | \subsection{Expressions} 335 | \label{basics:expressions} 336 | 337 | \small 338 | \begin{verbatimtab} 339 | >>> from sympy import simplify, factor, expand, collect 340 | \end{verbatimtab} 341 | \normalsize 342 | 343 | \noindent 344 | You define \texttt{SymPy} expressions by combining symbols with basic math operations and other functions: 345 | 346 | \small 347 | \begin{verbatimtab} 348 | >>> expr = 2*x + 3*x - sin(x) - 3*x + 42 349 | >>> simplify(expr) # simplify the expression 350 | 2*x - sin(x) + 42 351 | \end{verbatimtab} 352 | \normalsize 353 | 354 | \noindent 355 | The function \texttt{simplify} can be used on any expression to simplify it. 356 | The examples below illustrate other useful \texttt{SymPy} functions 357 | that correspond to common mathematical operations on expressions: 358 | 359 | \index{factoring} \index{expand} \index{collect} 360 | 361 | \small 362 | \begin{verbatimtab} 363 | >>> factor( x**2-2*x-8 ) # factor a polynomial 364 | (x - 4)*(x + 2) 365 | >>> expand( (x-4)*(x+2) ) # expand and expression 366 | x**2 - 2*x - 8 367 | >>> collect(x**2 + x*b + a*x + a*b, x) # collect like terms 368 | x**2 + (a+b)*x + a*b 369 | \end{verbatimtab} 370 | \normalsize 371 | 372 | \noindent 373 | To substitute a given value into an expression, \index{substitution} 374 | call the \texttt{.subs()} method, passing in a python dictionary object \texttt{\{ key:val, ... \}} 375 | with the symbol--value substitutions you want to make: 376 | 377 | \small 378 | \begin{verbatimtab} 379 | >>> expr = sin(x) + cos(y) # define an expression 380 | >>> expr 381 | sin(x) + cos(y) 382 | >>> expr.subs({x:1, y:2}) # subs. x=1,y=1 in expr 383 | sin(1) + cos(2) 384 | >>> expr.subs({x:1, y:2}).n() # compute numeric value 385 | 0.425324148260754 386 | \end{verbatimtab} 387 | \normalsize 388 | 389 | \noindent 390 | Note how we used \texttt{.n()} to obtain the expression's numeric value. 391 | 392 | \subsection{Solving equations} 393 | \label{basics:solving_equations} 394 | 395 | \small 396 | \begin{verbatimtab} 397 | >>> from sympy import solve 398 | \end{verbatimtab} 399 | \normalsize 400 | 401 | \noindent 402 | The function \texttt{solve} is the main workhorse in \texttt{SymPy}. 403 | This incredibly powerful function knows how to solve all kinds of equations. 404 | In fact \texttt{solve} can solve pretty much \emph{any} equation! 405 | When high school students learn about this function, they get really angry---why 406 | did they spend five years of their life learning to solve various equations by hand, 407 | when all along there was this \texttt{solve} thing that could do all the math for them? 408 | %Computers are nice like that. 409 | Don't worry, learning math is \emph{never} a waste of time. 410 | 411 | 412 | The function \texttt{solve} takes two arguments. 413 | Use \texttt{solve(expr,var)} to solve the equation \texttt{expr==0} for the variable \texttt{var}. 414 | %you want to solve assuming the form 415 | %The first argument specifies an expression which is equal to zero, 416 | You can rewrite any equation in the form \texttt{expr==0} by moving all the terms to one side of the equation; 417 | the solutions to $A(x)=B(x)$ are the same as the solutions to $A(x)-B(x)=0$. 418 | 419 | For example, 420 | to solve the quadratic equation $x^2+2x-8=0$, use 421 | 422 | \small 423 | \begin{verbatimtab} 424 | >>> solve( x**2 + 2*x - 8, x) 425 | [2, -4] 426 | \end{verbatimtab} 427 | \normalsize 428 | 429 | \noindent 430 | In this case the equation has two solutions so \texttt{solve} returns a list. 431 | Check that $x=2$ and $x=-4$ satisfy the equation $x^2+2x-8=0$. 432 | 433 | The best part about \texttt{solve} and \texttt{SymPy} is that you can obtain symbolic answers when solving equations. 434 | Instead of solving one specific quadratic equation, 435 | we can solve all possible equations of the form $ax^2 + bx+c=0$ using the following steps: 436 | 437 | \small 438 | \begin{verbatimtab} 439 | >>> a, b, c = symbols('a b c') 440 | >>> solve( a*x**2 + b*x + c, x) 441 | [(-b + sqrt(b**2 - 4*a*c))/(2*a), (-b-sqrt(b**2-4*a*c))/(2*a)] 442 | \end{verbatimtab} 443 | \normalsize 444 | 445 | \noindent 446 | In this case \texttt{solve} calculated the solution in terms of the symbols \texttt{a}, \texttt{b}, and \texttt{c}. 447 | You should be able to recognize the expressions in the solution---it's the quadratic formula $x_{1,2} = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$. \index{quadratic!formula} 448 | 449 | \ifthenelse{\boolean{TUTORIAL}}{ 450 | \input{99.quadratic_eqn_subsitution_example.tex} 451 | }{} 452 | 453 | 454 | \bigskip 455 | 456 | \noindent 457 | To solve a \emph{system of equations}, 458 | you can feed \texttt{solve} with the list of equations as the first argument, and specify the list of unknowns you want to solve for as the second argument. 459 | For example, to solve for $x$ and $y$ in the system of equations $x+y=3$ and $3x-2y=0$, use 460 | 461 | \small 462 | \begin{verbatimtab} 463 | >>> solve([x + y - 3, 3*x - 2*y], [x, y]) 464 | {x: 6/5, y: 9/5} 465 | \end{verbatimtab} 466 | \normalsize 467 | 468 | \bigskip 469 | 470 | \noindent 471 | The function \texttt{solve} is like a Swiss Army knife you can use to solve all kind of problems. 472 | Suppose you want to \emph{complete the square} in the expression $x^2-4x+7$, \index{completing the square} 473 | that is, you want to find constants $h$ and $k$ such that $x^2-4x+7 = (x-h)^2 +k$. 474 | There is no special ``complete the square'' function in \texttt{SymPy}, 475 | but you can call \texttt{solve} on the equation $(x-h)^2 +k \; - \; (x^2-4x+7) = 0$ 476 | to find the unknowns $h$ and $k$: 477 | 478 | \small 479 | \begin{verbatimtab} 480 | >>> h, k = symbols('h k') 481 | >>> solve( (x-h)**2 + k - (x**2-4*x+7), [h,k] ) 482 | [(2, 3)] # so h = 2 and k = 3 483 | >>> expand((x-2)**2+3) # verify... 484 | x**2 - 4*x + 7 485 | \end{verbatimtab} 486 | \normalsize 487 | 488 | \noindent 489 | Learn the basic \texttt{SymPy} commands 490 | and you'll never need to suffer another tedious arithmetic calculation painstakingly performed by hand again! 491 | 492 | 493 | 494 | \subsection{Rational functions} 495 | \label{basics:rational_functions} 496 | 497 | \small 498 | \begin{verbatimtab} 499 | >>> from sympy import together, apart 500 | \end{verbatimtab} 501 | \normalsize 502 | 503 | \noindent 504 | By default, \texttt{SymPy} will not combine or split rational expressions. 505 | You need to use \texttt{together} to symbolically calculate the addition of fractions: 506 | 507 | \small 508 | \begin{verbatimtab} 509 | >>> a, b, c, d = symbols('a b c d') 510 | >>> a/b + c/d 511 | a/b + c/d 512 | >>> together(a/b + c/d) 513 | (a*d + b*c)/(b*d) 514 | \end{verbatimtab} 515 | \normalsize 516 | 517 | \noindent 518 | Alternately, if you have a rational expression and want to divide the numerator by the denominator, 519 | use the \texttt{apart} function: 520 | 521 | \small 522 | \begin{verbatimtab} 523 | >>> apart( (x**2+x+4)/(x+2) ) 524 | x - 1 + 6/(x + 2) 525 | \end{verbatimtab} 526 | \normalsize 527 | 528 | 529 | \subsection{Exponentials and logarithms} 530 | \label{basics:exponentials_and_logarithms} 531 | 532 | \index{logarithm} 533 | Euler's number $e=2.71828\ldots$ is defined one of several ways, \index{Euler's!number} 534 | \[ 535 | e = \lim_{n\to \infty} \left( 1 + \frac{1}{n}\right)^{n} 536 | = \lim_{\epsilon \to 0} \left( 1 + \epsilon\right)^{1/\epsilon} 537 | = \sum_{n=0}^\infty \frac{1}{n!}, 538 | \] 539 | and is denoted \texttt{E} in \texttt{SymPy}. 540 | Using \texttt{exp(x)} is equivalent to \texttt{E**x}. 541 | 542 | The functions \texttt{log} and \texttt{ln} both compute the logarithm base $e$: 543 | 544 | \small 545 | \begin{verbatimtab} 546 | >>> log(E**3) # same as ln(E**3) 547 | 3 548 | \end{verbatimtab} 549 | \normalsize 550 | 551 | \noindent 552 | By default, \texttt{SymPy} assumes the inputs to functions like \texttt{exp} and \texttt{log} are complex numbers, 553 | so it will not expand certain logarithmic expressions. 554 | However, indicating to \texttt{SymPy} that the inputs are positive real numbers will make the expansions work: 555 | 556 | \small 557 | \begin{verbatimtab} 558 | >>> x, y = symbols('x y') 559 | >>> expand(log(x*y)) 560 | log(x*y) 561 | >>> a, b = symbols('a b', positive=True) 562 | >>> expand(log(a*b)) 563 | log(a) + log(b) 564 | \end{verbatimtab} 565 | \normalsize 566 | \subsection{Polynomials} 567 | \label{basics:polynomials} 568 | 569 | Let's define a polynomial $P$ with roots at $x=1$, $x=2$, and $x=3$: \index{polynomial} 570 | 571 | \small 572 | \begin{verbatimtab} 573 | >>> P = (x-1)*(x-2)*(x-3) 574 | >>> P 575 | (x - 1)*(x - 2)*(x - 3) 576 | \end{verbatimtab} 577 | \normalsize 578 | 579 | \noindent 580 | To see the expanded version of the polynomial, 581 | call its \texttt{expand} method: \index{expand} 582 | 583 | \small 584 | \begin{verbatimtab} 585 | >>> expand(P) 586 | x**3 - 6*x**2 + 11*x - 6 587 | \end{verbatimtab} 588 | \normalsize 589 | 590 | \noindent 591 | When the polynomial is expressed in it's expanded form $P(x)=x^3-6^2 + 11x - 6$, 592 | we can't immediately identify its roots. 593 | This is why the factored form $P(x)=(x-1)(x-2)(x-3)$ is preferable. 594 | To factor a polynomial, 595 | call its \texttt{factor} method or \texttt{simplify} it: \index{factoring} 596 | 597 | \small 598 | \begin{verbatimtab} 599 | >>> factor(P) 600 | (x - 1)*(x - 2)*(x - 3) 601 | >>> simplify(P) 602 | (x - 1)*(x - 2)*(x - 3) 603 | \end{verbatimtab} 604 | \normalsize 605 | 606 | \noindent 607 | Recall that the roots of the polynomial $P(x)$ are defined as the solutions to the equation $P(x)=0$. 608 | We can use the \texttt{solve} function to find the roots of the polynomial: 609 | 610 | \small 611 | \begin{verbatimtab} 612 | >>> roots = solve(P,x) 613 | >>> roots 614 | [1, 2, 3] 615 | # let's check if P equals (x-1)(x-2)(x-3) 616 | >>> simplify( P - (x-roots[0])*(x-roots[1])*(x-roots[2]) ) 617 | 0 618 | \end{verbatimtab} 619 | \normalsize 620 | 621 | 622 | \subsection{Equality checking} 623 | \label{basics:equality_checking} 624 | 625 | In the last example, 626 | we used the \texttt{simplify} function on the difference of two expressions to check whether they were equal. 627 | This way of checking equality works because $P=Q$ if and only if $P-Q=0$. 628 | To know whether $P=Q$, we can calculate \texttt{simplify(P-Q)} and see if the result equals $0$. 629 | This is the best way to check whether two expressions are equal in \texttt{SymPy} 630 | because it attempts all possible simplifications when comparing the expressions. 631 | Below is a list of other ways to check whether two quantities are equal 632 | with example cases where equality fails to be detected: 633 | 634 | \small 635 | \begin{verbatimtab} 636 | >>> P = (x-5)*(x+5) 637 | >>> Q = x**2 - 25 638 | >>> P == Q # fails 639 | False 640 | >>> P - Q == 0 # fails 641 | False 642 | >>> simplify(P - Q) # works 643 | 0 644 | >>> sin(x)**2 + cos(x)**2 == 1 # fails 645 | False 646 | >>> simplify( sin(x)**2 + cos(x)**2 - 1 ) # works 647 | 0 648 | \end{verbatimtab} 649 | \normalsize 650 | 651 | 652 | \subsection{Trigonometry} 653 | \label{basics:trigonometry} 654 | 655 | \small 656 | \begin{verbatimtab} 657 | from sympy import sin, cos, tan, trigsimp, expand_trig 658 | \end{verbatimtab} 659 | \normalsize 660 | 661 | \noindent 662 | The trigonometric functions \texttt{sin} and \texttt{cos} take inputs in radians: \index{radian} \index{sine} \index{cosine} 663 | 664 | \small 665 | \begin{verbatimtab} 666 | >>> sin(pi/6) 667 | 1/2 668 | >>> cos(pi/6) 669 | sqrt(3)/2 670 | \end{verbatimtab} 671 | \normalsize 672 | 673 | \noindent 674 | For angles in degrees, 675 | you need a conversion factor of $\frac{\pi}{180}$[rad/$^\circ$]: 676 | 677 | \small 678 | \begin{verbatimtab} 679 | >>> sin(30*pi/180) # 30 deg = pi/6 rads 680 | 1/2 681 | \end{verbatimtab} 682 | \normalsize 683 | 684 | \noindent 685 | The inverse trigonometric functions $\sin^{-1}(x) = \arcsin(x)$ 686 | and $\cos^{-1}(x) = \arccos(x)$ are used as follows: 687 | 688 | \small 689 | \begin{verbatimtab} 690 | >>> asin(1/2) 691 | pi/6 692 | >>> acos(sqrt(3)/2) 693 | pi/6 694 | \end{verbatimtab} 695 | \normalsize 696 | Recall that $\tan(x) = \frac{\sin(x)}{\cos(x)}$, 697 | while the inverse function of $\tan(x)$ is $\tan^{-1}(x) = \arctan(x) =$ \texttt{atan(x)} 698 | 699 | 700 | 701 | \small 702 | \begin{verbatimtab} 703 | >>> tan(pi/6) 704 | 1/sqrt(3) # = ( 1/2 )/( sqrt(3)/2 ) 705 | >>> atan( 1/sqrt(3) ) 706 | pi/6 707 | \end{verbatimtab} 708 | \normalsize 709 | 710 | \noindent 711 | The function \texttt{acos} returns angles in the range $[0,\pi]$, 712 | while \texttt{asin} and \texttt{atan} return angles in the range $[-\frac{\pi}{2},\frac{\pi}{2}]$. 713 | 714 | % TODOv6: mention atan2 715 | 716 | Here are some trigonometric identities that \texttt{SymPy} knows: \index{trigonometric identities} 717 | 718 | \small 719 | \begin{verbatimtab} 720 | >>> sin(x) == cos(x - pi/2) 721 | True 722 | >>> simplify( sin(x)*cos(y)+cos(x)*sin(y) ) 723 | sin(x + y) 724 | >>> e = 2*sin(x)**2 + 2*cos(x)**2 725 | >>> trigsimp(e) 726 | 2 727 | >>> trigsimp(log(e)) 728 | log(2*sin(x)**2 + 2*cos(x)**2) 729 | >>> trigsimp(log(e), deep=True) 730 | log(2) 731 | \end{verbatimtab} 732 | \normalsize 733 | 734 | \small 735 | \begin{verbatimtab} 736 | >>> simplify(sin(x)**4 - 2*cos(x)**2*sin(x)**2 + cos(x)**4) 737 | cos(4*x)/2 + 1/2 738 | \end{verbatimtab} 739 | \normalsize 740 | 741 | \noindent 742 | The function \texttt{trigsimp} does essentially the same job as \texttt{simplify}. 743 | 744 | If instead of simplifying you want to expand a trig expression, 745 | you should use \texttt{expand\_trig}, because the default \texttt{expand} won't touch trig functions: 746 | 747 | \small 748 | \begin{verbatimtab} 749 | >>> expand(sin(2*x)) 750 | sin(2*x) 751 | >>> expand_trig(sin(2*x)) # = expand(sin(2*x), trig=True) 752 | 2*sin(x)*cos(x) 753 | \end{verbatimtab} 754 | \normalsize 755 | 756 | 757 | 758 | \ifthenelse{\boolean{TUTORIAL}}{ 759 | \input{99.hyperbolic_functions_sympy_tutorial.tex} 760 | 761 | }{} 762 | 763 | 764 | 765 | %======================================================================= complex_numbers 766 | \lesection{Complex numbers} 767 | \label{sec:sympytut_complex_numbers} 768 | \index{complex number} 769 | \small 770 | \begin{verbatimtab} 771 | >>> from sympy import I, re, im, Abs, arg, conjugate 772 | \end{verbatimtab} 773 | \normalsize 774 | 775 | \ifthenelse{\boolean{TUTORIAL}}{ 776 | Ever since Newton, 777 | the word ``number'' has been used to refer to one of the following types of math objects: 778 | the naturals $\mathbb{N}$, 779 | the integers $\mathbb{Z}$, 780 | the rationals $\mathbb{Q}$, 781 | and the real numbers $\mathbb{R}$. 782 | Each set of numbers is associated with a different class of equations. 783 | The natural numbers $\mathbb{N}$ appear as solutions of the equation $m+n=x$, 784 | where $m$ and $n$ are natural numbers (denoted $m,n \in \mathbb{N}$). 785 | The integers $\mathbb{Z}$ are the solutions to equations of the form $x+m=~n$, where $m,n \in \mathbb{N}$. 786 | The rational numbers $\mathbb{Q}$ are necessary to solve for $x$ in $mx=n$, with $m,n \in \mathbb{Z}$. 787 | The solutions to $x^2=2$ are irrational (so $\notin \mathbb{Q}$) so we need an even larger set that 788 | contains \emph{all} possible numbers: real set of numbers $\mathbb{R}$. 789 | A pattern emerges where more complicated equations require the invention of new types of numbers. 790 | 791 | }{\noindent}% 792 | Consider the quadratic equation $x^2=-1$. 793 | There are no real solutions to this equation, 794 | but we can define an imaginary number $i =\sqrt{-1}$ (denoted \texttt{I} in \texttt{SymPy}) that satisfies this equation: 795 | 796 | \small 797 | \begin{verbatimtab} 798 | >>> I*I 799 | -1 800 | >>> solve( x**2 + 1 , x) 801 | [I, -I] 802 | \end{verbatimtab} 803 | \normalsize 804 | 805 | \noindent 806 | The solutions are $x=i$ and $x=-i$, 807 | and indeed we can verify that $i^2+1=0$ and $(-i)^2+1=0$ 808 | since $i^2=-1$. 809 | 810 | The complex numbers $\mathbb{C}$ are defined as $\{ a+bi \,|\, a,b \in \mathbb{R} \}$. 811 | Complex numbers contain a real part and an imaginary part: 812 | 813 | \small 814 | \begin{verbatimtab} 815 | >>> z = 4 + 3*I 816 | >>> z 817 | 4 + 3*I 818 | >>> re(z) 819 | 4 820 | >>> im(z) 821 | 3 822 | \end{verbatimtab} 823 | \normalsize 824 | 825 | \noindent 826 | The \emph{polar} representation of a complex number is $z=|z|\angle\theta\! = \!|z|e^{i\theta}$. 827 | For a complex number $z=a+bi$, 828 | the quantity $|z|=\sqrt{a^2+b^2}$ is known as the \emph{absolute value} of $z$, 829 | and $\theta$ is its \emph{phase} or its \emph{argument}: 830 | 831 | \small 832 | \begin{verbatimtab} 833 | >>> Abs(z) 834 | 5 835 | >>> arg(z) 836 | atan(3/4) 837 | \end{verbatimtab} 838 | \normalsize 839 | 840 | \noindent 841 | The complex conjugate of $z=a+bi$ is the number $\overline{z} = a-bi$, 842 | which has the same absolute value as $z$ but opposite phase: 843 | 844 | \small 845 | \begin{verbatimtab} 846 | >>> conjugate( z ) 847 | 4 - 3*I 848 | \end{verbatimtab} 849 | \normalsize 850 | 851 | \noindent 852 | Complex conjugation is important for computing the absolute value of $z$ 853 | ($|z|\eqdef\sqrt{ z\overline{z} }$) and for division by $z$ ($\frac{1}{z} = \frac{\overline{z}}{|z|^2}$). 854 | 855 | \subsection{Euler's formula} 856 | \label{complex_numbers:euler_s_formula} 857 | \index{Euler's!formula} 858 | \small 859 | \begin{verbatimtab} 860 | >>> from sympy import expand, rewrite 861 | \end{verbatimtab} 862 | \normalsize 863 | \href{https://en.wikipedia.org/wiki/Euler's_formula}{Euler's formula} shows an important relation 864 | between the exponential function $e^x$ and the trigonometric functions $\sin(x)$ and $\cos(x)$: 865 | \[ 866 | e^{ix} = \cos x + i \sin x. 867 | \] 868 | To obtain this result in \texttt{SymPy}, you must specify that the number $x$ is real 869 | and also tell \texttt{expand} that you're interested in complex expansions: 870 | 871 | \small 872 | \begin{verbatimtab} 873 | >>> x = symbols('x', real=True) 874 | >>> expand(exp(I*x), complex=True) 875 | cos(x) + I*sin(x) 876 | >>> re( exp(I*x) ) 877 | cos(x) 878 | >>> im( exp(I*x) ) 879 | sin(x) 880 | \end{verbatimtab} 881 | \normalsize 882 | 883 | \noindent 884 | Basically, $\cos(x)$ is the real part of $e^{ix}$, 885 | and $\sin(x)$ is the imaginary part of $e^{ix}$. 886 | Whaaat? 887 | I know it's weird, 888 | but weird things are bound to happen when you input imaginary numbers to functions. 889 | 890 | 891 | %======================================================================= calculus 892 | \lesection{Calculus} 893 | \label{sec:sympytut_calculus} 894 | 895 | Calculus is the study of the properties of functions. 896 | The operations of calculus are used to describe the limit behaviour of functions, 897 | calculate their rates of change, 898 | and calculate the areas under their graphs. 899 | In this section we'll learn about the \texttt{SymPy} functions for calculating 900 | limits, derivatives, integrals, and summations. 901 | 902 | \subsection{Infinity} 903 | \label{calculus:infinity} 904 | 905 | \small 906 | \begin{verbatimtab} 907 | from sympy import oo 908 | \end{verbatimtab} 909 | \normalsize 910 | 911 | \noindent 912 | The infinity symbol is denoted \texttt{oo} (two lowercase \texttt{o}s) in \texttt{SymPy}. \index{infinity} 913 | Infinity is not a number but a process: the process of counting forever. 914 | Thus, $\infty + 1 = \infty$, 915 | $\infty$ is greater than any finite number, 916 | and $1/\infty$ is an infinitely small number. 917 | Sympy knows how to correctly treat infinity in expressions: 918 | 919 | \small 920 | \begin{verbatimtab} 921 | >>> oo+1 922 | oo 923 | >>> 5000 < oo 924 | True 925 | >>> 1/oo 926 | 0 927 | \end{verbatimtab} 928 | \normalsize 929 | 930 | \subsection{Limits} 931 | \label{calculus:limits} 932 | \small 933 | \begin{verbatimtab} 934 | from sympy import limit 935 | \end{verbatimtab} 936 | \normalsize 937 | 938 | \noindent 939 | We use limits to describe, with mathematical precision, infinitely large quantities, \index{limit} 940 | infinitely small quantities, and procedures with infinitely many steps. 941 | 942 | The number $e$ is defined as the limit 943 | $\displaystyle e \eqdef \lim_{n\to \infty} \left( 1 + \frac{1}{n}\right)^{n}$: 944 | \small 945 | \begin{verbatimtab} 946 | >>> limit( (1+1/n)**n, n, oo) 947 | E # = 2.71828182845905 948 | \end{verbatimtab} 949 | \normalsize 950 | 951 | \noindent 952 | This limit expression describes the annual growth rate of a loan 953 | with a nominal interest rate of $100\%$ and infinitely frequent compounding. \index{interest rate} 954 | Borrow $\$1000$ in such a scheme, 955 | and you'll owe $\$2718.28$ after one~year. 956 | 957 | Limits are also useful to describe the behaviour of functions. 958 | Consider the function $f(x)=\frac{1}{x}$. 959 | The \texttt{limit} command shows us what happens to $f(x)$ near $x=0$ and as $x$ goes to infinity: 960 | 961 | \small 962 | \begin{verbatimtab} 963 | >>> limit( 1/x, x, 0, dir="+") 964 | oo 965 | >>> limit( 1/x, x, 0, dir="-") 966 | -oo 967 | >>> limit( 1/x, x, oo) 968 | 0 969 | \end{verbatimtab} 970 | \normalsize 971 | 972 | \noindent 973 | As $x$ becomes larger and larger, the fraction $\frac{1}{x}$ becomes smaller and smaller. 974 | In the limit where $x$ goes to infinity, $\frac{1}{x}$ approaches zero: $\lim_{x\to \infty} \frac{1}{x} = 0$. 975 | On the other hand, when $x$ takes on smaller and smaller positive values, 976 | the expression $\frac{1}{x}$ becomes infinite: $\lim_{x \to 0^+} \frac{1}{x} = \infty$. 977 | When $x$ approaches $0$ from the left, we have $\lim_{x \to 0^-} \frac{1}{x} = -\infty$. 978 | If these calculations are not clear to you, 979 | study the graph of $f(x)=\frac{1}{x}$. 980 | 981 | 982 | Here are some other examples of limits: 983 | 984 | \small 985 | \begin{verbatimtab} 986 | >>> limit(sin(x)/x, x, 0) 987 | 1 988 | >>> limit(sin(x)**2/x, x, 0) 989 | 0 990 | >>> limit(exp(x)/x**100,x,oo) # which is bigger e^x or x^100 ? 991 | oo # exp f >> all poly f for big x 992 | \end{verbatimtab} 993 | \normalsize 994 | 995 | \ifthenelse{\boolean{TUTORIAL}}{ 996 | \noindent 997 | Limits are used to define the derivative and the integral operations. 998 | }{} 999 | 1000 | \subsection{Derivatives} 1001 | \label{calculus:derivatives} 1002 | The derivative function, denoted $f'(x)$, $\frac{d}{dx}f(x)$, $\frac{df}{dx}$, or $\frac{dy}{dx}$, \index{derivative} 1003 | describes the \emph{rate of change} of the function $f(x)$. 1004 | The \texttt{SymPy} function \texttt{diff} computes the derivative of any expression: 1005 | 1006 | 1007 | 1008 | \small 1009 | \begin{verbatimtab} 1010 | >>> diff(x**3, x) 1011 | 3*x**2 1012 | \end{verbatimtab} 1013 | \normalsize 1014 | 1015 | \noindent 1016 | The differentiation operation knows the product rule $[f(x)g(x)]^\prime=f^\prime(x)g(x)+f(x)g^\prime(x)$, 1017 | the chain rule $f(g(x))' = f'(g(x))g'(x)$, 1018 | and the quotient rule $\left[\frac{f(x)}{g(x)}\right]^\prime = \frac{f'(x)g(x) - f(x)g'(x)}{g(x)^2}$: 1019 | 1020 | 1021 | 1022 | \small 1023 | \begin{verbatimtab} 1024 | >>> diff( x**2*sin(x), x ) 1025 | 2*x*sin(x) + x**2*cos(x) 1026 | >>> diff( sin(x**2), x ) 1027 | cos(x**2)*2*x 1028 | >>> diff( x**2/sin(x), x ) 1029 | (2*x*sin(x) - x**2*cos(x))/sin(x)**2 1030 | \end{verbatimtab} 1031 | \normalsize 1032 | 1033 | \noindent 1034 | The second derivative of a function \texttt{f} is \texttt{diff(f,x,2)}: 1035 | 1036 | 1037 | 1038 | \small 1039 | \begin{verbatimtab} 1040 | >>> diff(x**3, x, 2) # same as diff(diff(x**3, x), x) 1041 | 6*x 1042 | \end{verbatimtab} 1043 | \normalsize 1044 | 1045 | \ifthenelse{\boolean{TUTORIAL}}{ 1046 | 1047 | \input{99.simle_ode_example.tex} 1048 | }{} 1049 | 1050 | 1051 | \subsection{Tangent lines} 1052 | \label{calculus:tangent_lines} 1053 | 1054 | The \emph{tangent line} to the function $f(x)$ at $x=x_0$ is \index{tangent line} 1055 | the line that passes through the point $(x_0, f(x_0))$ and has 1056 | the same slope as the function at that point. 1057 | The tangent line to the function $f(x)$ at the point $x=x_0$ is described by the equation 1058 | \[ 1059 | T_1(x) = f(x_0) \; + \; f'(x_0)(x-x_0). 1060 | \] 1061 | What is the equation of the tangent line to $f(x)=\frac{1}{2}x^2$ at $x_0=1$? 1062 | 1063 | 1064 | 1065 | \small 1066 | \begin{verbatimtab} 1067 | >>> f = S('1/2')*x**2 1068 | >>> f 1069 | x**2/2 1070 | >>> df = diff(f, x) 1071 | >>> df 1072 | x 1073 | >>> T_1 = f.subs({x:1}) + df.subs({x:1})*(x - 1) 1074 | >>> T_1 1075 | x - 1/2 # y = x - 1/2 1076 | \end{verbatimtab} 1077 | \normalsize 1078 | 1079 | \noindent 1080 | The tangent line $T_1(x)$ has the same value and slope as the function $f(x)$ at $x=1$: 1081 | \small 1082 | \begin{verbatimtab} 1083 | >>> T_1.subs({x:1}) == f.subs({x:1}) 1084 | True 1085 | >>> diff(T_1, x).subs({x:1}) == diff(f, x).subs({x:1}) 1086 | True 1087 | \end{verbatimtab} 1088 | \normalsize 1089 | 1090 | \ifthenelse{\boolean{TUTORIAL}}{}{ 1091 | \noindent 1092 | See Figure~\ref{fig:derivative_and_tangent_line_bis} on page~\pageref{fig:derivative_and_tangent_line_bis}. 1093 | } 1094 | 1095 | \subsection{Optimization} 1096 | \label{calculus:optimization} 1097 | \index{optimization} 1098 | 1099 | \ifthenelse{\boolean{TUTORIAL}}{ 1100 | 1101 | Optimization is about choosing an input for a function $f(x)$ that results in the best value for $f(x)$. 1102 | The best value usually means the \emph{maximum} value 1103 | (if the function represents something desirable like profits) 1104 | or the \emph{minimum} value 1105 | (if the function represents something undesirable like costs). 1106 | 1107 | The derivative $f'(x)$ encodes the information about the \emph{slope} of $f(x)$. 1108 | Positive slope $f'(x)>0$ means $f(x)$ is increasing, 1109 | negative slope $f'(x)<0$ means $f(x)$ is decreasing, 1110 | and zero slope $f'(x)=0$ means the graph of the function is horizontal. 1111 | The \emph{critical points} of a function $f(x)$ are the solutions to the equation $f'(x)=0$. 1112 | Each critical point is a candidate to be either a maximum or a minimum of the function. 1113 | 1114 | The second derivative $f^{\prime\prime}(x)$ encodes the information about the \emph{curvature} of $f(x)$. 1115 | Positive curvature means the function looks like~$x^2$, 1116 | negative curvature means the function looks like $-x^2$. 1117 | 1118 | }{ 1119 | 1120 | Recall the \emph{second derivative test} for finding the maxima and minima of a function, 1121 | which we learned on page~\pageref{optimization_algorithm:alternate_algorithm}. 1122 | 1123 | } 1124 | 1125 | Let's find the critical points of the function $f(x)=x^3-2x^2+x$ and use the information from its second derivative \index{critical point} 1126 | to find the maximum of the function on the interval $x \in [0,1]$. \index{maximum} 1127 | 1128 | \small 1129 | \begin{verbatimtab} 1130 | >>> x = Symbol('x') 1131 | >>> f = x**3-2*x**2+x 1132 | >>> diff(f, x) 1133 | 3*x**2 - 4*x + 1 1134 | >>> sols = solve( diff(f,x), x) 1135 | >>> sols 1136 | [1/3, 1] 1137 | >>> diff(diff(f,x), x).subs( {x:sols[0]} ) 1138 | -2 1139 | >>> diff(diff(f,x), x).subs( {x:sols[1]} ) 1140 | 2 1141 | \end{verbatimtab} 1142 | \normalsize 1143 | 1144 | \noindent 1145 | \href{https://www.google.ca/\#q=plot+x**3-2*x**2++\%2B+x&safe=off}{It will help to look at the graph of this function.} 1146 | The point $x=\frac{1}{3}$ is a local maximum because it is a critical point of $f(x)$ 1147 | where the curvature is negative, meaning $f(x)$ looks like the peak of a mountain at $x=\frac{1}{3}$. 1148 | The maximum value of $f(x)$ on the interval $x\in [0,1]$ is $f\!\left(\frac{1}{3}\right)=\frac{4}{27}$. 1149 | The point $x=1$ is a local minimum because it is a critical point \index{minimum} 1150 | with positive curvature, meaning $f(x)$ looks like the bottom of a valley at $x=1$. 1151 | 1152 | 1153 | 1154 | 1155 | \subsection{Integrals} 1156 | \label{calculus:integrals} 1157 | 1158 | \ifthenelse{\boolean{TUTORIAL}}{ 1159 | 1160 | The \emph{integral} of $f(x)$ corresponds to the computation of the area under the graph of $f(x)$. \index{area} 1161 | The area under $f(x)$ between the points $x=a$ and $x=b$ is denoted as follows: 1162 | \[ 1163 | A(a,b) = \int_a^b f(x) \: dx. 1164 | \] 1165 | The \emph{integral function} $F$ corresponds to the area calculation as a function of the upper limit of integration: 1166 | \[ 1167 | F(c) \eqdef \int_0^c \! f(x)\:dx\,. 1168 | \] 1169 | The area under $f(x)$ between $x=a$ and $x=b$ is obtained by calculating the \emph{change} in the integral function: 1170 | \[ 1171 | A(a,b) = \int_a^b \! f(x)\:dx = F(b)-F(a). 1172 | \] 1173 | 1174 | }{} 1175 | 1176 | In \texttt{SymPy} we use \texttt{integrate(f, x)} to obtain the integral function $F(x)$ of any function $f(x)$: \index{integral} 1177 | $F(x) = \int_0^x f(u)\,du$. 1178 | 1179 | \small 1180 | \begin{verbatimtab} 1181 | >>> integrate(x**3, x) 1182 | x**4/4 1183 | >>> integrate(sin(x), x) 1184 | -cos(x) 1185 | >>> integrate(ln(x), x) 1186 | x*log(x) - x 1187 | \end{verbatimtab} 1188 | \normalsize 1189 | This is known as an \emph{indefinite integral} since the limits of integration are not defined. 1190 | 1191 | In contrast, 1192 | a \emph{definite integral} computes the area under $f(x)$ between $x=a$ and $x=b$. 1193 | Use \texttt{integrate(f, (x,a,b))} to compute the definite integrals of the form $A(a,b)=\int_a^b f(x) \, dx$: 1194 | 1195 | \small 1196 | \begin{verbatimtab} 1197 | >>> integrate(x**3, (x,0,1)) 1198 | 1/4 # the area under x^3 from x=0 to x=1 1199 | \end{verbatimtab} 1200 | \normalsize 1201 | 1202 | \noindent 1203 | We can obtain the same area by first calculating the indefinite integral $F(c)=\int_0^c \!f(x)\,dx$, 1204 | then using $A(a,b) = F(x)\big\vert_a^b = F(b) - F(a)$: 1205 | 1206 | 1207 | 1208 | \small 1209 | \begin{verbatimtab} 1210 | >>> F = integrate(x**3, x) 1211 | >>> F.subs({x:1}) - F.subs({x:0}) 1212 | 1/4 1213 | \end{verbatimtab} 1214 | \normalsize 1215 | Integrals correspond to \emph{signed} area calculations: 1216 | 1217 | 1218 | 1219 | \small 1220 | \begin{verbatimtab} 1221 | >>> integrate(sin(x), (x,0,pi)) 1222 | 2 1223 | >>> integrate(sin(x), (x,pi,2*pi)) 1224 | -2 1225 | >>> integrate(sin(x), (x,0,2*pi)) 1226 | 0 1227 | \end{verbatimtab} 1228 | \normalsize 1229 | 1230 | \noindent 1231 | During the first half of its $2\pi$-cycle, 1232 | the graph of $\sin(x)$ is above the $x$-axis, so it has a positive contribution to the area under the curve. 1233 | During the second half of its cycle (from $x=\pi$ to $x=2\pi$), 1234 | $\sin(x)$ is below the $x$-axis, so it contributes negative area. 1235 | Draw a graph of $\sin(x)$ to see what is going on. 1236 | 1237 | \subsection{Fundamental theorem of calculus} 1238 | \label{calculus:fundamental_theorem_of_calculus} 1239 | \index{fundamental theorem of calculus} 1240 | The integral is the ``inverse operation'' of the derivative. \index{inverse!operation} 1241 | If you perform the integral operation followed by the derivative operation on some function, 1242 | you'll obtain the same function: 1243 | \[ 1244 | \left(\frac{d}{dx} \circ \int dx \right) f(x) = \frac{d}{dx} \int_c^x f(u)\:du = f(x). 1245 | \] 1246 | 1247 | 1248 | 1249 | \small 1250 | \begin{verbatimtab} 1251 | >>> f = x**2 1252 | >>> F = integrate(f, x) 1253 | >>> F 1254 | x**3/3 # + C 1255 | >>> diff(F, x) 1256 | x**2 1257 | \end{verbatimtab} 1258 | \normalsize 1259 | 1260 | \noindent 1261 | Alternately, if you compute the derivative of a function followed by the integral, 1262 | you will obtain the original function $f(x)$ (up to a constant): 1263 | \[ 1264 | \left( \int dx \circ \frac{d}{dx}\right) f(x) = \int_c^x f'(u)\;du = f(x) + C. 1265 | \] 1266 | 1267 | 1268 | 1269 | \small 1270 | \begin{verbatimtab} 1271 | >>> f = x**2 1272 | >>> df = diff(f, x) 1273 | >>> df 1274 | 2*x 1275 | >>> integrate(df, x) 1276 | x**2 # + C 1277 | \end{verbatimtab} 1278 | \normalsize 1279 | 1280 | \noindent 1281 | The fundamental theorem of calculus is important because it tells us how to solve differential equations. 1282 | If we have to solve for $f(x)$ in the differential equation $\frac{d}{dx}f(x) = g(x)$, 1283 | we can take the integral on both sides of the equation to obtain the answer $f(x) = \int g(x)\,dx + C$. 1284 | 1285 | \subsection{Sequences} 1286 | \label{calculus:sequences} 1287 | 1288 | Sequences are functions that take whole numbers as inputs. \index{sequence} 1289 | Instead of continuous inputs $x\in \mathbb{R}$, 1290 | sequences take natural numbers $n\in\mathbb{N}$ as inputs. 1291 | We denote sequences as $a_n$ instead of the usual function notation $a(n)$. 1292 | 1293 | We define a sequence by specifying an expression for its $n$\textsuperscript{th} term: 1294 | 1295 | 1296 | 1297 | \small 1298 | \begin{verbatimtab} 1299 | >>> a_n = 1/n 1300 | >>> b_n = 1/factorial(n) 1301 | \end{verbatimtab} 1302 | \normalsize 1303 | 1304 | \noindent 1305 | Substitute the desired value of $n$ to see the value of the $n$\textsuperscript{th} term: 1306 | 1307 | \small 1308 | \begin{verbatimtab} 1309 | >>> a_n.subs({n:5}) 1310 | 1/5 1311 | \end{verbatimtab} 1312 | \normalsize 1313 | 1314 | \noindent 1315 | %We can use 1316 | The Python list comprehension syntax \texttt{[item for item in list]} 1317 | can be used to print the sequence values for some range of indices: 1318 | 1319 | 1320 | 1321 | \small 1322 | \begin{verbatimtab} 1323 | >>> [ a_n.subs({n:i}) for i in range(0,8) ] 1324 | [oo, 1, 1/2, 1/3, 1/4, 1/5, 1/6, 1/7] 1325 | >>> [ b_n.subs({n:i}) for i in range(0,8) ] 1326 | [1, 1, 1/2, 1/6, 1/24, 1/120, 1/720, 1/5040] 1327 | \end{verbatimtab} 1328 | \normalsize 1329 | 1330 | \noindent 1331 | Observe that $a_n$ is not properly defined for $n=0$ since $\frac{1}{0}$ is a division-by-zero error. 1332 | To be precise, we should say $a_n$'s domain is the positive naturals $a_n:\mathbb{N}^+ \to \mathbb{R}$. 1333 | Observe how quickly the \texttt{factorial} function $n!=1\cdot2\cdot3\cdots(n-1)\cdot n$ grows: 1334 | $7!= 5040$, $10!=3628800$, $20! > 10^{18}$. 1335 | 1336 | 1337 | 1338 | We're often interested in calculating the limits of sequences as $n\to \infty$. 1339 | What happens to the terms in the sequence when $n$ becomes large? 1340 | 1341 | \small 1342 | \begin{verbatimtab} 1343 | >>> limit(a_n, n, oo) 1344 | 0 1345 | >>> limit(b_n, n, oo) 1346 | 0 1347 | \end{verbatimtab} 1348 | \normalsize 1349 | 1350 | \noindent 1351 | Both $a_n=\frac{1}{n}$ and $b_n = \frac{1}{n!}$ \emph{converge} to $0$ as $n\to\infty$. \index{convergence} 1352 | 1353 | \medskip 1354 | 1355 | Many important math quantities are defined as limit expressions. 1356 | An interesting example to consider is the number $\pi$, 1357 | which is defined as the area of a circle of radius $1$. 1358 | We can approximate the area of the unit circle by drawing a many-sided regular polygon around the circle. 1359 | Splitting the $n$-sided regular polygon into identical triangular splices, 1360 | we can obtain a formula for its area $A_n$\ifthenelse{\boolean{TUTORIAL}}{}{ (see solution to \textbf{P\ref{mathprob:octagon-approx-to-circle}})}. 1361 | In the limit as $n\to \infty$, 1362 | the $n$-sided-polygon approximation to the area of the unit-circle becomes exact: \index{approximation} 1363 | 1364 | \small 1365 | \begin{verbatimtab} 1366 | >>> A_n = n*tan(2*pi/(2*n)) 1367 | >>> limit(A_n, n, oo) 1368 | pi 1369 | \end{verbatimtab} 1370 | \normalsize 1371 | 1372 | 1373 | \subsection{Series} 1374 | \label{calculus:series} 1375 | 1376 | Suppose we're given a sequence $a_n$ and we want to compute the sum of all the values in this sequence $\sum_{n}^\infty a_n$. 1377 | Series are sums of sequences. \index{series} 1378 | Summing the values of a sequence $a_n:\mathbb{N}\to \mathbb{R}$ 1379 | is analogous to taking the integral of a function $f:\mathbb{R}\to \mathbb{R}$. 1380 | 1381 | To work with series in \texttt{SymPy}, 1382 | use the \texttt{summation} function whose syntax is analogous to the \texttt{integrate} function: \index{summation} 1383 | \index{sequence!harmonic} 1384 | 1385 | \small 1386 | \begin{verbatimtab} 1387 | >>> a_n = 1/n 1388 | >>> b_n = 1/factorial(n) 1389 | >>> summation(a_n, [n, 1, oo]) 1390 | oo 1391 | >>> summation(b_n, [n, 0, oo]) 1392 | E 1393 | \end{verbatimtab} 1394 | \normalsize 1395 | 1396 | \noindent 1397 | We say the series $\sum a_n$ \emph{diverges} to infinity (or \emph{is divergent}) \index{divergence} 1398 | while the series $\sum b_n$ converges (or \emph{is convergent}). \index{convergence} 1399 | As we sum together more and more terms of the sequence $b_n$, the total becomes closer and closer to some finite number. 1400 | In this case, the infinite sum $\sum_{n=0}^\infty \frac{1}{n!}$ converges to the number $e=2.71828\ldots$. 1401 | 1402 | 1403 | The \texttt{summation} command is useful because it allows us to compute \emph{infinite} sums, 1404 | but for most practical applications we don't need to take an infinite number of terms in a series to obtain a good approximation. 1405 | This is why series are so neat: they represent a great way to obtain approximations. 1406 | 1407 | Using standard Python commands, 1408 | we can obtain an approximation to $e$ that is accurate to six decimals by summing 10 terms in the series: 1409 | 1410 | \small 1411 | \begin{verbatimtab} 1412 | >>> import math 1413 | >>> def b_nf(n): 1414 | return 1.0/math.factorial(n) 1415 | >>> sum( [b_nf(n) for n in range(0,10)] ) 1416 | 2.718281 52557319 1417 | >>> E.evalf() 1418 | 2.718281 82845905 # true value 1419 | \end{verbatimtab} 1420 | \normalsize 1421 | \subsection{Taylor series} 1422 | \label{calculus:taylor_series} 1423 | 1424 | Wait, there's more! 1425 | Not only can we use series to approximate numbers, 1426 | we can also use them to approximate functions. 1427 | 1428 | A \emph{power series} is a series whose terms contain different powers of the variable $x$. \index{Taylor series} 1429 | The $n$\textsuperscript{th} term in a power series is a function of both the sequence index $n$ and the input variable $x$. 1430 | 1431 | For example, the power series of the function $\exp(x)=e^x$ is 1432 | \[ 1433 | \exp(x) = 1 + x + \frac{x^2}{2} + \frac{x^3}{3!} + \frac{x^4}{4!} + \frac{x^5}{5!} + \cdots 1434 | = \sum_{n=0}^\infty \frac{x^n}{n!}. 1435 | \] 1436 | This is, IMHO, one of the most important ideas in calculus: 1437 | you can compute the value of $\exp(5)$ by taking the infinite sum of the terms in the power series with $x=5$: 1438 | 1439 | 1440 | 1441 | \small 1442 | \begin{verbatimtab} 1443 | >>> exp_xn = x**n/factorial(n) 1444 | >>> summation( exp_xn.subs({x:5}), [n, 0, oo] ).evalf() 1445 | 148.413159102577 1446 | >>> exp(5).evalf() 1447 | 148.413159102577 # the true value 1448 | \end{verbatimtab} 1449 | \normalsize 1450 | 1451 | \noindent 1452 | Note that \texttt{SymPy} is actually smart enough to recognize that the infinite series 1453 | you're computing corresponds to the closed-form expression $e^5$: 1454 | 1455 | 1456 | 1457 | \small 1458 | \begin{verbatimtab} 1459 | >>> summation( exp_xn.subs({x:5}), [n, 0, oo]) 1460 | exp(5) 1461 | \end{verbatimtab} 1462 | \normalsize 1463 | Taking as few as 35 terms in the series is sufficient to obtain an approximation to $e$ 1464 | that is accurate to $16$ decimals: 1465 | %so series are not some abstract thing for mathematicians but a practical trick you can when you code: 1466 | 1467 | \small 1468 | \begin{verbatimtab} 1469 | >>> import math # redo using only python 1470 | >>> def exp_xnf(x,n): 1471 | return x**n/math.factorial(n) 1472 | >>> sum( [exp_xnf(5.0,i) for i in range(0,35)] ) 1473 | 148.413159102577 1474 | \end{verbatimtab} 1475 | \normalsize 1476 | 1477 | \noindent 1478 | The coefficients in the power series of a function (also known as the \emph{Taylor series}) 1479 | depend on the value of the higher derivatives of the function. 1480 | The formula for the $n$\textsuperscript{th} term in the Taylor series of $f(x)$ expanded at $x=c$ is $a_n(x) = \frac{f^{(n)}(c)}{n!}(x-c)^n$, 1481 | where $f^{(n)}(c)$ is the value of the $n$\textsuperscript{th} derivative of $f(x)$ evaluated at $x=c$. 1482 | %The term \emph{Taylor series} applies to all series expansions of functions. 1483 | The term \emph{Maclaurin series} refers to Taylor series expansions at $x=0$. \index{Maclaurin series} 1484 | 1485 | The \texttt{SymPy} function \texttt{series} is a convenient way to obtain the series of any function. 1486 | Calling \texttt{series(expr,var,at,nmax)} 1487 | will show you the series expansion of \texttt{expr} 1488 | near \texttt{var}=\texttt{at} 1489 | up to power \texttt{nmax}: 1490 | 1491 | \small 1492 | \begin{verbatimtab} 1493 | >>> series( sin(x), x, 0, 8) 1494 | x - x**3/6 + x**5/120 - x**7/5040 + O(x**8) 1495 | >>> series( cos(x), x, 0, 8) 1496 | 1 - x**2/2 + x**4/24 - x**6/720 + O(x**8) 1497 | >>> series( sinh(x), x, 0, 8) 1498 | x + x**3/6 + x**5/120 + x**7/5040 + O(x**8) 1499 | >>> series( cosh(x), x, 0, 8) 1500 | 1 + x**2/2 + x**4/24 + x**6/720 + O(x**8) 1501 | \end{verbatimtab} 1502 | \normalsize 1503 | 1504 | %Note the power series of $\sin$ and $\sinh$ contain only odd powers of $x$ 1505 | %while the power series of $\cos$ and $\cosh$ contain only even powers. 1506 | 1507 | \noindent 1508 | Some functions are not defined at $x=0$, so we expand them at a different value of $x$. 1509 | For example, the power series of $\ln(x)$ expanded at $x=1$ is 1510 | 1511 | \small 1512 | \begin{verbatimtab} 1513 | >>> series(ln(x), x, 1, 6) # Taylor series of ln(x) at x=1 1514 | x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6) 1515 | \end{verbatimtab} 1516 | \normalsize 1517 | 1518 | \noindent 1519 | Here, the result \texttt{SymPy} returns is misleading. 1520 | The Taylor series of $\ln(x)$ expanded at $x=1$ has terms of the form $(x-1)^n$: 1521 | \[ 1522 | \ln(x) = (x-1) - \frac{(x-1)^2}{2} + \frac{(x-1)^3}{3} - \frac{(x-1)^4}{4} + \frac{(x-1)^5}{5} + \cdots. 1523 | \] 1524 | Verify this is the correct formula by substituting $x=1$. 1525 | \texttt{SymPy} returns an answer in terms of coordinates \emph{relative} to $x=1$. 1526 | %That's okay, 1527 | %because when dealing with series in general we're mostly interested in the coefficients. 1528 | 1529 | Instead of expanding $\ln(x)$ around $x=1$, 1530 | we can obtain an equivalent expression if we expand $\ln(x+1)$ around $x=0$: 1531 | 1532 | 1533 | 1534 | \small 1535 | \begin{verbatimtab} 1536 | >>> series(ln(x+1), x, 0, 6) # Maclaurin series of ln(x+1) 1537 | x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6) 1538 | \end{verbatimtab} 1539 | \normalsize 1540 | 1541 | 1542 | 1543 | 1544 | %======================================================================= vectors 1545 | \lesection{Vectors} 1546 | \label{sec:sympytut_vectors} 1547 | 1548 | A vector $\vec{v} \in \mathbb{R}^n$ is an $n$-tuple of real numbers. \index{vector} 1549 | For example, consider a vector that has three components: 1550 | \[ 1551 | \vec{v} = (v_1,v_2,v_3) \; \in \; \mathbb{R}^3. 1552 | \] 1553 | To specify the vector $\vec{v}$, 1554 | we specify the values for its three components $v_1$, $v_2$, and $v_3$. 1555 | 1556 | A matrix $A \in \mathbb{R}^{m\times n}$ is a rectangular array of real numbers with $m$ rows and $n$ columns. 1557 | A vector is a special type of matrix; 1558 | you can think of the vector $\vec{v}\in \mathbb{R}^n$ as a $1\times n$ matrix. 1559 | Because of this equivalence between vectors and matrices, 1560 | in \texttt{SymPy} we use \texttt{Matrix} objects to represent vectors. 1561 | 1562 | This is how we define vectors and compute their properties: \index{length} 1563 | \index{unit vector} 1564 | 1565 | \small 1566 | \begin{verbatimtab} 1567 | >>> u = Matrix([4,5,6]) # a three-dimensional vector 1568 | >>> u 1569 | [4, 5, 6] 1570 | >>> u[0] # 0-based indexing for components 1571 | 4 1572 | >>> u.norm() # length of u 1573 | sqrt(77) 1574 | >>> uhat = u/u.norm() # unit vector in same dir as u 1575 | >>> uhat 1576 | [4/sqrt(77), 5/sqrt(77), 6/sqrt(77)] 1577 | >>> uhat.norm() 1578 | 1 1579 | \end{verbatimtab} 1580 | \normalsize 1581 | 1582 | 1583 | 1584 | 1585 | \subsection{Dot product} 1586 | \label{vectors:dot_product} 1587 | 1588 | The dot product of the $3$-vectors $\vec{u}$ and $\vec{v}$ can be defined two ways: \index{dot product} 1589 | \[ 1590 | \vec{u}\cdot\vec{v} 1591 | \eqdef 1592 | \underbrace{u_xv_x+u_yv_y+u_zv_z}_{\textrm{algebraic def.}} 1593 | = 1594 | \underbrace{\|\vec{u}\|\|\vec{v}\|\cos(\varphi)}_{\textrm{geometric def.}} 1595 | \quad \in \mathbb{R}, 1596 | \] 1597 | where $\varphi$ is the angle between the vectors $\vec{u}$ and $\vec{v}$. 1598 | In \texttt{SymPy}, 1599 | 1600 | \small 1601 | \begin{verbatimtab} 1602 | >>> u = Matrix([ 4,5,6]) 1603 | >>> v = Matrix([-1,1,2]) 1604 | >>> u.dot(v) 1605 | 13 1606 | \end{verbatimtab} 1607 | \normalsize 1608 | 1609 | \noindent 1610 | We can combine the algebraic and geometric formulas for the dot product 1611 | to obtain the cosine of the angle between the vectors 1612 | \[ 1613 | \cos(\varphi) 1614 | = \frac{ \vec{u}\cdot\vec{v} }{ \|\vec{u}\|\|\vec{v}\| } 1615 | = \frac{ u_xv_x+u_yv_y+u_zv_z }{ \|\vec{u}\|\|\vec{v}\| }, 1616 | \] 1617 | and use the \texttt{acos} function to find the angle measure: 1618 | 1619 | \small 1620 | \begin{verbatimtab} 1621 | >>> acos(u.dot(v)/(u.norm()*v.norm())).evalf() 1622 | 0.921263115666387 # in radians = 52.76 degrees 1623 | \end{verbatimtab} 1624 | \normalsize 1625 | 1626 | \noindent 1627 | Just by looking at the coordinates of the vectors $\vec{u}$ and $\vec{v}$, 1628 | it's difficult to determine their relative direction. 1629 | Thanks to the dot product, however, 1630 | we know the angle between the vectors is $52.76^\circ$, 1631 | which means they \emph{kind of} point in the same direction. 1632 | Vectors that are at an angle $\varphi=90^\circ$ are called \emph{orthogonal}, meaning at right angles with each other. 1633 | The dot product between two vectors is negative when the angle between them is $\varphi > 90^\circ$. 1634 | 1635 | The notion of the ``angle between vectors'' applies more generally to vectors with any number of dimensions. 1636 | The dot product for $n$-dimensional vectors is $\vec{u}\cdot\vec{v}=\sum_{i=1}^n u_iv_i$. 1637 | This means we can talk about ``the angle between'' 1000-dimensional vectors. 1638 | That's pretty crazy if you think about it---there is no way we could possibly ``visualize'' 1000-dimensional vectors, 1639 | yet given two such vectors we can tell if they point mostly in the same direction, 1640 | in perpendicular directions, or mostly in opposite directions. 1641 | 1642 | The dot product is a commutative operation $\vec{u}\cdot\vec{v} = \vec{v}\cdot\vec{u}$: 1643 | 1644 | 1645 | 1646 | \small 1647 | \begin{verbatimtab} 1648 | >>> u.dot(v) == v.dot(u) 1649 | True 1650 | \end{verbatimtab} 1651 | \normalsize 1652 | 1653 | 1654 | \ifthenelse{\boolean{FORLA}}{ 1655 | \input{99.vectors_projectsions_FORLA.tex} 1656 | }{} 1657 | 1658 | 1659 | 1660 | \subsection{Cross product} 1661 | \label{vectors:cross_product} 1662 | 1663 | The \emph{cross product}, denoted $\times$, \index{cross product} 1664 | takes two vectors as inputs and produces a vector as output. 1665 | The cross products of individual basis elements are defined as follows: 1666 | \[ 1667 | \hat{\imath}\times\hat{\jmath} =\hat{k}, \qquad 1668 | \hat{\jmath}\times\hat{k} =\hat{\imath}, \qquad 1669 | \hat{k}\times \hat{\imath}= \hat{\jmath}. 1670 | \] 1671 | The cross product is defined by the following equation: 1672 | \[ 1673 | \vec{u}\times\vec{v}= 1674 | \left( 1675 | u_yv_z-u_zv_y, \; u_zv_x-u_xv_z, \; u_xv_y-u_yv_x 1676 | \right). 1677 | \] 1678 | 1679 | \noindent 1680 | Here's how to compute the cross product of two vectors: 1681 | \small 1682 | \begin{verbatimtab} 1683 | >>> u = Matrix([ 4,5,6]) 1684 | >>> v = Matrix([-1,1,2]) 1685 | >>> u.cross(v) 1686 | [4, -14, 9] 1687 | \end{verbatimtab} 1688 | \normalsize 1689 | 1690 | \noindent 1691 | The vector $\vec{u}\times \vec{v}$ is orthogonal to both $\vec{u}$ and $\vec{v}$. 1692 | The norm of the cross product $\|\vec{u}\times \vec{v}\|$ is proportional to the lengths of the vectors 1693 | and the sine of the angle between them: 1694 | \small 1695 | \begin{verbatimtab} 1696 | (u.cross(v).norm()/(u.norm()*v.norm())).n() 1697 | 0.796366206088088 # = sin(0.921..) 1698 | \end{verbatimtab} 1699 | \normalsize 1700 | 1701 | \noindent 1702 | The cross product is anticommutative, $\vec{u}\times\vec{v} = -\vec{v}\times\vec{u}$: 1703 | \small 1704 | \begin{verbatimtab} 1705 | >>> u.cross(v) 1706 | [4, -14, 9] 1707 | >>> v.cross(u) 1708 | [-4, 14,-9] 1709 | \end{verbatimtab} 1710 | \normalsize 1711 | 1712 | \noindent 1713 | 1714 | Watch out for this, because it's a new thing. 1715 | The product of two numbers $a$ and $b$ is commutative: $ab = ba$. \index{commutative} 1716 | The dot product of two vectors $\vec{u}$ and $\vec{v}$ is commutative: $\vec{u}\cdot\vec{v} = \vec{v}\cdot\vec{u}$. 1717 | However the cross product is not commutative: $\vec{u}\times\vec{v} \neq \vec{v}\times\vec{u}$, 1718 | it is anticommutative: $\vec{u}\times\vec{v} = -\vec{v}\times\vec{u}$. 1719 | %Sandy said: Hmmm....we're not really supposed to have more than one colon per sentence...is this an informal use case? Or do we want to fully respect the grammar? 1720 | % @Sandy: yes let's go with informal rule-breaking-double-: exception since it's in technical appendix (people already scared by the math, but now code + math = very little ppl read this far ;) 1721 | 1722 | 1723 | 1724 | 1725 | %======================================================================= mechanics 1726 | \lesection{Mechanics} 1727 | \label{sec:sympytut_mechanics} 1728 | 1729 | The module called \href{http://pyvideo.org/video/2653/dynamics-and-control-with-python}{\texttt{sympy.physics.mechanics}} 1730 | contains elaborate tools for describing mechanical systems, 1731 | manipulating reference frames, forces, and torques. 1732 | These specialized functions are not necessary for a first-year mechanics course. 1733 | The basic \texttt{SymPy} functions like \texttt{solve}, 1734 | and the vector operations you learned in the previous sections are powerful enough for basic Newtonian mechanics. 1735 | %Let's look into this. 1736 | 1737 | \subsection{Dynamics} 1738 | \label{mechanics:dynamics} 1739 | 1740 | The net force acting on an object is the sum of all the external forces acting on it $\vec{F}_{\textrm{net}} = \sum \vec{F}$. 1741 | Since forces are vectors, \index{force} 1742 | we need to use vector addition to compute the net force. 1743 | 1744 | Compute $\vec{F}_{\textrm{net}}=\vec{F}_1 + \vec{F}_2$, 1745 | where $\vec{F}_1=4\hat{\imath}$[N] and $\vec{F}_2 = 5\angle 30^\circ$[N]: 1746 | \small 1747 | \begin{verbatimtab} 1748 | >>> F_1 = Matrix( [4,0] ) 1749 | >>> F_2 = Matrix( [5*cos(30*pi/180), 5*sin(30*pi/180) ] ) 1750 | >>> F_net = F_1 + F_2 1751 | >>> F_net 1752 | [4 + 5*sqrt(3)/2, 5/2] 1753 | >>> F_net.evalf() 1754 | [8.33012701892219, 2.5] # in Newtons 1755 | \end{verbatimtab} 1756 | \normalsize 1757 | 1758 | \noindent 1759 | To express the answer in length-and-direction notation, 1760 | use \texttt{norm} to find the length of $\vec{F}_{\textrm{net}}$, 1761 | and use the two-input inverse tangent function \texttt{atan2} to compute the direction: 1762 | \small 1763 | \begin{verbatimtab} 1764 | >>> F_net.norm().evalf() 1765 | 8.69718438067042 # |F_net| in [N] 1766 | >>> (atan2( F_net[1],F_net[0] )*180/pi).n() 1767 | 16.7053138060100 # angle in degrees 1768 | \end{verbatimtab} 1769 | \normalsize 1770 | The net force on the object is $\vec{F}_{\textrm{net}}= 8.697\angle 16.7^\circ$[N]. 1771 | 1772 | 1773 | \subsection{Kinematics} 1774 | \label{mechanics:kinematics} 1775 | 1776 | Let $x(t)$ denote the position of an object, \index{kinematics} 1777 | $v(t)$ denote its velocity, 1778 | and $a(t)$ denote its acceleration. 1779 | Together $x(t)$, $v(t)$, and $a(t)$ are known as the \emph{equations of motion} of the object. 1780 | 1781 | 1782 | \ifthenelse{\boolean{TUTORIAL}}{ 1783 | 1784 | The equations of motion are related by the derivative operation: 1785 | \[ 1786 | a(t) \overset{\frac{d}{dt} }{\longleftarrow} v(t) \overset{\frac{d}{dt} }{\longleftarrow} x(t). 1787 | \] 1788 | Assume we know the initial position $x_i\eqdef x(0)$ and the initial velocity $v_i\eqdef v(0)$ of the object 1789 | and we want to find $x(t)$ for all later times. 1790 | We can do this starting from the dynamics of the problem---the forces acting on the object. 1791 | 1792 | Newton's second law $\vec{F}_{\textrm{net}} = m\vec{a}$ states that a net force $\vec{F}_{\textrm{net}}$ 1793 | applied on an object of mass $m$ produces acceleration $\vec{a}$. 1794 | Thus, we can obtain an objects acceleration if we know the net force acting on it. 1795 | Starting from the knowledge of $a(t)$, we can obtain $v(t)$ by integrating 1796 | then find $x(t)$ by integrating $v(t)$: 1797 | \[ 1798 | a(t) 1799 | \; \; \; \overset{v_i+ \int\!dt }{\longrightarrow} \; \; \; 1800 | v(t) 1801 | \; \; \; \overset{x_i+ \int\!dt }{\longrightarrow} \; \; \; 1802 | x(t). 1803 | \] 1804 | The reasoning follows from the fundamental theorem of calculus: 1805 | if $a(t)$ represents the change in $v(t)$, 1806 | then the total of $a(t)$ accumulated between $t=t_1$ and $t=t_2$ 1807 | is equal to the total change in $v(t)$ between these times: $\Delta v = v(t_2) - v(t_1)$. 1808 | Similarly, the integral of $v(t)$ from $t=0$ until $t=\tau$ is equal to $x(\tau) - x(0)$. 1809 | 1810 | }{ 1811 | 1812 | Starting from the knowledge of $\vec{F}_{\textrm{net}}$, 1813 | we can compute $a(t)=\frac{ \vec{F}_{\textrm{net}} }{ m }$, 1814 | then obtain $v(t)$ by integrating $a(t)$, and finally obtain $x(t)$ by integrating $v(t)$: 1815 | \[ 1816 | \underbrace{ 1817 | \frac{ \vec{F}_{\textrm{net}} }{ m } = a(t) 1818 | }_{\textrm{Newton's 2\textsuperscript{nd} law}} 1819 | \underbrace{ \overset{v_i+ \int\!dt }{\longrightarrow} 1820 | \; \; \; 1821 | v(t) 1822 | \; \; \; \overset{x_i+ \int\!dt }{\longrightarrow} \; \; \; 1823 | x(t). 1824 | }_{\textrm{kinematics}} 1825 | \] 1826 | 1827 | } 1828 | 1829 | 1830 | \subsection{Uniform acceleration motion (UAM)} 1831 | \label{mechanics:UAM} 1832 | 1833 | Let's analyze the case where the net force on the object is constant. 1834 | A constant force causes a constant acceleration $a = \frac{F}{m} = \textrm{constant}$. 1835 | If the acceleration function is constant over time $a(t)=a$. 1836 | We find $v(t)$ and $x(t)$ as follows: 1837 | \small 1838 | \begin{verbatimtab} 1839 | >>> t, a, v_i, x_i = symbols('t a v_i x_i') 1840 | >>> v = v_i + integrate(a, (t, 0,t) ) 1841 | >>> v 1842 | a*t + v_i 1843 | >>> x = x_i + integrate(v, (t, 0,t) ) 1844 | >>> x 1845 | a*t**2/2 + v_i*t + x_i 1846 | \end{verbatimtab} 1847 | \normalsize 1848 | 1849 | \noindent 1850 | You may remember these equations from 1851 | \ifthenelse{\boolean{TUTORIAL}}{your high school physics class.} 1852 | {Section~\ref{sec:kinematics_with_calculus} (page~\pageref{sec:kinematics_with_calculus}).} 1853 | They are the \emph{uniform accelerated motion} (UAM) equations: \index{uniformly accelerated motion} 1854 | \begin{align*} 1855 | a(t) &= a, \\ 1856 | v(t) &= v_i + at, \\[-2mm] 1857 | x(t) &= x_i + v_it + \frac{1}{2}at^2. 1858 | \end{align*} 1859 | In high school, you probably had to memorize these equations. 1860 | Now you know how to derive them yourself starting from first principles. 1861 | 1862 | For the sake of completeness, we'll now derive the fourth UAM equation, 1863 | which relates the object's final velocity to the initial velocity, 1864 | the displacement, and the acceleration, without reference to time: 1865 | \small 1866 | \begin{verbatimtab} 1867 | >>> expand(v*v) 1868 | a**2*t**2 + 2*a*t*v_i + v_i**2 1869 | >>> simplify(expand(v*v) - 2*a*x) 1870 | -2*a*x_i + v_i**2 1871 | \end{verbatimtab} 1872 | \normalsize 1873 | 1874 | \noindent 1875 | The above calculation shows $v_f^2 - 2ax_f = -2ax_i + v_i^2$. 1876 | After moving the term $2ax_f$ to the other side of the equation, we obtain 1877 | \begin{align*} 1878 | (v(t))^2 \; = \; v_f^2 = v_i^2 + 2a\Delta x \; = \; v_i^2 + 2a(x_f-x_i). 1879 | \end{align*} 1880 | The fourth equation is important for practical purposes 1881 | because it allows us to solve physics problems without using the time variable. 1882 | 1883 | 1884 | \subsubsection{Example} 1885 | 1886 | Find the position function of an object at time $t =3$[s], 1887 | if it starts from $x_i=20$[m] with $v_i=10$[m/s] and undergoes 1888 | a constant acceleration of $a=5$[m/s$^2$]. 1889 | What is the object's velocity at $t=3$[s]? 1890 | 1891 | \small 1892 | \begin{verbatimtab} 1893 | >>> x_i = 20 # initial position 1894 | >>> v_i = 10 # initial velocity 1895 | >>> a = 5 # acceleration (constant during motion) 1896 | >>> v = v_i + integrate(a, (t,0,t)) 1897 | >>> x = x_i + integrate(v, (t,0,t)) 1898 | >>> x 1899 | 5*t**2/2 + 10*t + 20 1900 | >>> x.subs({t:3}).n() # x(3) in [m] 1901 | 72.5 1902 | >>> diff(x,t).subs({t:3}).n() # v(3) in [m/s] 1903 | 25 # = sqrt( v_i**2 + 2*a*52.5 ) 1904 | \end{verbatimtab} 1905 | \normalsize 1906 | 1907 | \noindent 1908 | If you think about it, 1909 | physics knowledge combined with computer skills is like a superpower! 1910 | 1911 | 1912 | \subsection{General equations of motion} 1913 | \label{mechanics:general_eqns_of_motion} 1914 | 1915 | The procedure 1916 | $a(t) \; \overset{v_i+ \int\!dt }{\longrightarrow} \; v(t) \; \overset{x_i+ \int\!dt }{\longrightarrow} \; x(t)$ 1917 | can be used to obtain the position function $x(t)$ even when the acceleration is not constant. 1918 | Suppose the acceleration of an object is $a(t)=\sqrt{k t}$; 1919 | what is its $x(t)$? 1920 | 1921 | \small 1922 | \begin{verbatimtab} 1923 | >>> t, v_i, x_i, k = symbols('t v_i x_i k') 1924 | >>> a = sqrt(k*t) 1925 | >>> v = v_i + integrate(a, (t,0,t)) 1926 | >>> x = x_i + integrate(v, (t,0,t)) 1927 | >>> x 1928 | x_i + v_i*t + (4/15)*(k*t)**(5/2)/k**2 1929 | \end{verbatimtab} 1930 | \normalsize 1931 | 1932 | 1933 | 1934 | 1935 | \subsection{Potential energy} 1936 | \label{mechanics:potential_energy} 1937 | 1938 | \ifthenelse{\boolean{TUTORIAL}}{ 1939 | Instead of working with the kinematic equations of motion $x(t)$, $v(t)$, and $a(t)$ which depend on time, 1940 | we can solve physics problems using \emph{energy} calculations. 1941 | A key connection between the world of forces and the world of energy is the concept of \emph{potential energy}. 1942 | If you move an object against a conservative force (think raising a ball in the air against the force of gravity), 1943 | you can think of the work you do against the force as being stored in the potential energy of the object. 1944 | }{} 1945 | 1946 | For each force $\vec{F}(x)$ there is a corresponding potential energy $U_F(x)$. \index{potential energy} \index{energy!potential} 1947 | The change in potential energy associated with the force $\vec{F}(x)$ and displacement $\vec{d}$ 1948 | is defined as the negative of the work done by the force during the displacement: \index{work} \index{force} 1949 | $U_F(x) = - W = - \int_{\vec{d}} \vec{F}(x)\cdot d\vec{x}$. 1950 | 1951 | The potential energies associated with gravity $\vec{F}_g = -mg\hat{\jmath}$ \index{gravitational potential energy} 1952 | and the force of a spring $\vec{F}_s = -k\vec{x}$ are calculated as follows: \index{spring potential energy} 1953 | 1954 | \small 1955 | \begin{verbatimtab} 1956 | >>> x, y = symbols('x y') 1957 | >>> m, g, k, h = symbols('m g k h') 1958 | >>> F_g = -m*g # Force of gravity on mass m 1959 | >>> U_g = - integrate( F_g, (y,0,h) ) 1960 | >>> U_g 1961 | m*g*h # Grav. potential energy 1962 | >>> F_s = -k*x # Spring force for displacement x 1963 | >>> U_s = - integrate( F_s, (x,0,x) ) 1964 | >>> U_s 1965 | k*x**2/2 # Spring potential energy 1966 | \end{verbatimtab} 1967 | \normalsize 1968 | 1969 | \noindent 1970 | Note the negative sign in the formula defining the potential energy. 1971 | This negative is cancelled by the negative sign of the dot product $\vec{F}\cdot d\vec{x}$: 1972 | when the force acts in the direction opposite to the displacement, 1973 | the work done by the force is negative. 1974 | 1975 | \subsection{Simple harmonic motion} 1976 | \label{mechanics:simple_harmonic_motion} 1977 | \index{simple harmonic motion} 1978 | \small 1979 | \begin{verbatimtab} 1980 | from sympy import Function, dsolve 1981 | \end{verbatimtab} 1982 | \normalsize 1983 | 1984 | \noindent 1985 | The force exerted by a spring is given by the formula $F=-kx$. 1986 | If the only force acting on a mass $m$ is the force of a spring, 1987 | we can use Newton's second law to obtain the following equation: 1988 | \[ 1989 | F=ma 1990 | \quad \Rightarrow \quad 1991 | -kx = ma 1992 | \quad \Rightarrow \quad 1993 | -kx(t) = m\frac{d^2}{dt^2}\Big[x(t)\Big]. 1994 | \] 1995 | The motion of a mass-spring system is described by the \emph{differential equation} $\frac{d^2}{dt^2}x(t) + \omega^2 x(t)=0$, 1996 | where the constant $\omega = \sqrt{\frac{k}{m}}$ is called the angular frequency. 1997 | We can find the position function $x(t)$ using the \texttt{dsolve} method: 1998 | 1999 | \small 2000 | \begin{verbatimtab} 2001 | >>> t = Symbol('t') # time t 2002 | >>> x = Function('x') # position function x(t) 2003 | >>> w = Symbol('w', positive=True) # angular frequency w 2004 | >>> sol = dsolve( diff(x(t),t,t) + w**2*x(t), x(t) ) 2005 | >>> sol 2006 | x(t) == C1*sin(w*t) + C2*cos(w*t) 2007 | >>> x = sol.rhs 2008 | >>> x 2009 | C1*sin(w*t) + C2*cos(w*t) 2010 | \end{verbatimtab} 2011 | \normalsize 2012 | 2013 | \noindent 2014 | Note the solution $x(t)=C_1\sin(\omega t)+C_2 \cos(\omega t)$ is equivalent to $x(t) = A\cos(\omega t + \phi)$, 2015 | which is more commonly used to describe simple harmonic motion. 2016 | We can use the \texttt{expand} function with the argument \texttt{trig=True} to convince ourselves of this equivalence: 2017 | 2018 | \small 2019 | \begin{verbatimtab} 2020 | >>> A, phi = symbols("A phi") 2021 | >>> expand(A*cos(w*t - phi), trig=True) 2022 | A*sin(phi)*sin(w*t) + A*cos(phi)*cos(w*t) 2023 | \end{verbatimtab} 2024 | \normalsize 2025 | 2026 | \noindent 2027 | If we define $C_1=A\sin(\phi)$ and $C_2=A\cos(\phi)$, 2028 | we obtain the form $x(t)=C_1\sin(\omega t)+C_2 \cos(\omega t)$ that \texttt{SymPy} found. 2029 | 2030 | 2031 | \subsubsection{Conservation of energy} 2032 | 2033 | We can verify that the total energy of the mass-spring system is conserved by showing $E_T(t) = U_s(t) + K(t) = \textrm{constant}$: 2034 | 2035 | \small 2036 | \begin{verbatimtab} 2037 | >>> x = sol.rhs.subs({"C1":0,"C2":A}) 2038 | >>> x 2039 | A*cos(t*w) 2040 | >>> v = diff(x, t) 2041 | -A*w*sin(t*w) 2042 | >>> E_T = (0.5*k*x**2 + 0.5*m*v**2).simplify() 2043 | >>> E_T 2044 | 0.5*A**2*(k*cos(w*t)**2 + m*w**2*sin(w*t)**2) 2045 | >>> E_T.subs({k:m*w**2}).simplify() 2046 | 0.5*m*(w*A)**2 # = K_max 2047 | >>> E_T.subs({w:sqrt(k/m)}).simplify() 2048 | 0.5*k*A**2 # = U_max 2049 | \end{verbatimtab} 2050 | \normalsize 2051 | 2052 | 2053 | 2054 | \ifthenelse{\boolean{TUTORIAL}}{}{ 2055 | 2056 | \printcp 2057 | \vspace{-2mm} 2058 | 2059 | 2060 | %======================================================================= conclusion 2061 | \section*{Conclusion} 2062 | % \label{sec:sympytut_conclusion} 2063 | 2064 | I'll conclude with some words of warning about technological dependence. 2065 | Computer technology is very powerful and everywhere around us, 2066 | but we must not forget that computers are merely calculators that depend on human commands to direct them. 2067 | This means it's important for you to learn how to do math ``by hand'' first, 2068 | in order to know how to instruct computers to do the math for you. 2069 | 2070 | % CAUTION 2071 | I don't want you to use the tricks you learned in this tutorial to avoid learning how to do math 2072 | and blindly rely on \texttt{SymPy} to do math calculations for you. 2073 | That's not a good idea! 2074 | I'll be very disappointed if you use \texttt{SymPy} to skip the ``intellectual suffering'' 2075 | necessary to learn the new math concepts like numbers, equations, functions, etc. 2076 | That's what math is all about---understand math concepts and the relationships between concepts. 2077 | The part that is about rote memorized of math calculations procedures that you should have learned at school is not important at all. 2078 | The tedious and repetitive math calculations is precisely what can be ``outsourced'' to \texttt{SymPy}. 2079 | 2080 | 2081 | % PROBLEM SOLVING STRATEGY 2082 | To solve problems in math (or physics, chemistry, biology, etc.) 2083 | the most important things are to: 2084 | A) define the variables relevant for the problem, 2085 | B) draw a diagram, 2086 | and C) clearly set up the problem's equations in terms of the variables you defined. 2087 | With these steps in place, 2088 | half the work of solving the problem is already done! 2089 | Computers can't help with these important, 2090 | initial modelling and problem-specific tasks---only humans are good at this stuff. 2091 | Once you set up the problem (A, B, C), 2092 | \texttt{SymPy} can help you breeze through any subsequent calculations that might be necessary to obtain the final answer. 2093 | 2094 | % HISTORICAL PROOF = INSPIRATIONAL STATEMENT 2095 | Most of the big math and science discoveries were made using pen and paper, 2096 | which shows that scribbling on paper is a useful as a tool for thinking. 2097 | With what you learned about \texttt{SymPy}, 2098 | you now have access to the combination of pencil and paper for thinking and \texttt{SymPy} for calculating. 2099 | It's a very powerful combination! 2100 | What is a real-world problem you'd like to solve? 2101 | Try modelling the problem using math equations and see what happens. 2102 | Go out there and do some science! 2103 | 2104 | 2105 | % ---- using sympy shoulders of giants, but understanding the equations makes you a math giant! 2106 | 2107 | 2108 | 2109 | %======================================================================= links 2110 | \section*{Links} 2111 | % \label{sec:sympytut_links} 2112 | 2113 | [ Installation instructions for \texttt{jupyter notebook} ] \\ 2114 | \href{https://jupyter.readthedocs.io/en/latest/install.html} 2115 | {\texttt{https://jupyter.readthedocs.io/en/latest/install.html}} 2116 | 2117 | \medskip 2118 | \noindent 2119 | [ The official \texttt{SymPy} tutorial ] \\ 2120 | \href{http://docs.sympy.org/latest/tutorial/intro.html}{\texttt{http://docs.sympy.org/latest/tutorial/intro.html}} 2121 | 2122 | \medskip 2123 | \noindent 2124 | [ A list of \texttt{SymPy} gotchas ] \\ 2125 | \href{http://docs.sympy.org/dev/gotchas.html}{\texttt{http://docs.sympy.org/dev/gotchas.html}} 2126 | 2127 | 2128 | 2129 | } 2130 | 2131 | 2132 | 2133 | % TODOv6: include linear algebra parts even in math phys book --- plug LA book ---- Jul 14: vetoing this idea bcs would add too many pages 2134 | -------------------------------------------------------------------------------- /99.vectors_projectsions_FORLA.tex: -------------------------------------------------------------------------------- 1 | %!TEX root = sympy_tutorial.tex 2 | 3 | \vspace{-4mm} 4 | 5 | 6 | \subsection{Projections} 7 | \label{vectors:projections} 8 | 9 | \vspace{-2mm} 10 | 11 | Dot products are used for computing projections. 12 | Assume you're given two vectors $\vec{u}$ and $\vec{n}$ and you want to find the component 13 | of $\vec{u}$ that points in the $\vec{n}$ direction. 14 | The following formula based on the dot product will give you the answer: 15 | \[ 16 | \Pi_{\vec{n}}( \vec{u} ) \equiv \frac{ \vec{u} \cdot \vec{n} }{ \| \vec{n} \|^2 } \vec{n}. 17 | \] 18 | 19 | \vspace{-2mm} 20 | 21 | \noindent 22 | This is how to implement this formula in \texttt{SymPy}: 23 | \small 24 | \begin{verbatimtab} 25 | >>> u = Matrix([4,5,6]) 26 | >>> n = Matrix([1,1,1]) 27 | >>> (u.dot(n) / n.norm()**2)*n 28 | [5, 5, 5] # projection of v in the n dir 29 | \end{verbatimtab} 30 | \normalsize 31 | 32 | \noindent 33 | In the case where the direction vector $\hat{n}$ is of unit length $\|\hat{n}\| = 1$, 34 | the projection formula simplifies to $\Pi_{\hat{n}}( \vec{u} ) \equiv (\vec{u}\cdot\hat{n})\hat{n}$. 35 | 36 | 37 | Consider now the plane $P$ defined by $(1,1,1)\cdot[(x,y,z)-(0,0,0)]=0$. 38 | A plane is a two dimensional subspace of $\mathbb{R}^3$. 39 | We can decompose any vector $\vec{u} \in \mathbb{R}^3$ into two parts $\vec{u}=\vec{v} + \vec{w}$ 40 | such that $\vec{v}$ lies inside the plane and $\vec{w}$ is perpendicular to the plane (parallel to $\vec{n}=(1,1,1)$). 41 | 42 | To obtain the perpendicular-to-$P$ component of $\vec{u}$, 43 | compute the projection of $\vec{u}$ in the direction $\vec{n}$: 44 | \small 45 | \begin{verbatimtab} 46 | >>> w = (u.dot(n) / n.norm()**2)*n 47 | [5, 5, 5] 48 | \end{verbatimtab} 49 | \normalsize 50 | 51 | \noindent 52 | To obtain the in-the-plane-$P$ component of $\vec{u}$, 53 | start with $\vec{u}$ and subtract the perpendicular-to-$P$ part: 54 | \small 55 | \begin{verbatimtab} 56 | >>> v = u - (u.dot(n)/n.norm()**2)*n # same as u - w 57 | [ -1, 0, 1] 58 | \end{verbatimtab} 59 | \normalsize 60 | 61 | \noindent 62 | You should check on your own that $\vec{v}+\vec{w}=\vec{u}$ as claimed. 63 | 64 | \vspace{-5mm} 65 | -------------------------------------------------------------------------------- /AUTHORS.txt: -------------------------------------------------------------------------------- 1 | Ivan Savov (initial .tex version from the `No bullshit guide to math and physics` appendix) 2 | Sandra Gordon (editor) 3 | Zdeněk Janák (iPython notebook conversion) 4 | 5 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Attribution 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution 4.0 International Public License 58 | 59 | By exercising the Licensed Rights (defined below), You accept and agree 60 | to be bound by the terms and conditions of this Creative Commons 61 | Attribution 4.0 International Public License ("Public License"). To the 62 | extent this Public License may be interpreted as a contract, You are 63 | granted the Licensed Rights in consideration of Your acceptance of 64 | these terms and conditions, and the Licensor grants You such rights in 65 | consideration of benefits the Licensor receives from making the 66 | Licensed Material available under these terms and conditions. 67 | 68 | 69 | Section 1 -- Definitions. 70 | 71 | a. Adapted Material means material subject to Copyright and Similar 72 | Rights that is derived from or based upon the Licensed Material 73 | and in which the Licensed Material is translated, altered, 74 | arranged, transformed, or otherwise modified in a manner requiring 75 | permission under the Copyright and Similar Rights held by the 76 | Licensor. For purposes of this Public License, where the Licensed 77 | Material is a musical work, performance, or sound recording, 78 | Adapted Material is always produced where the Licensed Material is 79 | synched in timed relation with a moving image. 80 | 81 | b. Adapter's License means the license You apply to Your Copyright 82 | and Similar Rights in Your contributions to Adapted Material in 83 | accordance with the terms and conditions of this Public License. 84 | 85 | c. Copyright and Similar Rights means copyright and/or similar rights 86 | closely related to copyright including, without limitation, 87 | performance, broadcast, sound recording, and Sui Generis Database 88 | Rights, without regard to how the rights are labeled or 89 | categorized. For purposes of this Public License, the rights 90 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 91 | Rights. 92 | 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. Share means to provide material to the public by any means or 116 | process that requires permission under the Licensed Rights, such 117 | as reproduction, public display, public performance, distribution, 118 | dissemination, communication, or importation, and to make material 119 | available to the public including in ways that members of the 120 | public may access the material from a place and at a time 121 | individually chosen by them. 122 | 123 | j. Sui Generis Database Rights means rights other than copyright 124 | resulting from Directive 96/9/EC of the European Parliament and of 125 | the Council of 11 March 1996 on the legal protection of databases, 126 | as amended and/or succeeded, as well as other essentially 127 | equivalent rights anywhere in the world. 128 | 129 | k. You means the individual or entity exercising the Licensed Rights 130 | under this Public License. Your has a corresponding meaning. 131 | 132 | 133 | Section 2 -- Scope. 134 | 135 | a. License grant. 136 | 137 | 1. Subject to the terms and conditions of this Public License, 138 | the Licensor hereby grants You a worldwide, royalty-free, 139 | non-sublicensable, non-exclusive, irrevocable license to 140 | exercise the Licensed Rights in the Licensed Material to: 141 | 142 | a. reproduce and Share the Licensed Material, in whole or 143 | in part; and 144 | 145 | b. produce, reproduce, and Share Adapted Material. 146 | 147 | 2. Exceptions and Limitations. For the avoidance of doubt, where 148 | Exceptions and Limitations apply to Your use, this Public 149 | License does not apply, and You do not need to comply with 150 | its terms and conditions. 151 | 152 | 3. Term. The term of this Public License is specified in Section 153 | 6(a). 154 | 155 | 4. Media and formats; technical modifications allowed. The 156 | Licensor authorizes You to exercise the Licensed Rights in 157 | all media and formats whether now known or hereafter created, 158 | and to make technical modifications necessary to do so. The 159 | Licensor waives and/or agrees not to assert any right or 160 | authority to forbid You from making technical modifications 161 | necessary to exercise the Licensed Rights, including 162 | technical modifications necessary to circumvent Effective 163 | Technological Measures. For purposes of this Public License, 164 | simply making modifications authorized by this Section 2(a) 165 | (4) never produces Adapted Material. 166 | 167 | 5. Downstream recipients. 168 | 169 | a. Offer from the Licensor -- Licensed Material. Every 170 | recipient of the Licensed Material automatically 171 | receives an offer from the Licensor to exercise the 172 | Licensed Rights under the terms and conditions of this 173 | Public License. 174 | 175 | b. No downstream restrictions. You may not offer or impose 176 | any additional or different terms or conditions on, or 177 | apply any Effective Technological Measures to, the 178 | Licensed Material if doing so restricts exercise of the 179 | Licensed Rights by any recipient of the Licensed 180 | Material. 181 | 182 | 6. No endorsement. Nothing in this Public License constitutes or 183 | may be construed as permission to assert or imply that You 184 | are, or that Your use of the Licensed Material is, connected 185 | with, or sponsored, endorsed, or granted official status by, 186 | the Licensor or others designated to receive attribution as 187 | provided in Section 3(a)(1)(A)(i). 188 | 189 | b. Other rights. 190 | 191 | 1. Moral rights, such as the right of integrity, are not 192 | licensed under this Public License, nor are publicity, 193 | privacy, and/or other similar personality rights; however, to 194 | the extent possible, the Licensor waives and/or agrees not to 195 | assert any such rights held by the Licensor to the limited 196 | extent necessary to allow You to exercise the Licensed 197 | Rights, but not otherwise. 198 | 199 | 2. Patent and trademark rights are not licensed under this 200 | Public License. 201 | 202 | 3. To the extent possible, the Licensor waives any right to 203 | collect royalties from You for the exercise of the Licensed 204 | Rights, whether directly or through a collecting society 205 | under any voluntary or waivable statutory or compulsory 206 | licensing scheme. In all other cases the Licensor expressly 207 | reserves any right to collect such royalties. 208 | 209 | 210 | Section 3 -- License Conditions. 211 | 212 | Your exercise of the Licensed Rights is expressly made subject to the 213 | following conditions. 214 | 215 | a. Attribution. 216 | 217 | 1. If You Share the Licensed Material (including in modified 218 | form), You must: 219 | 220 | a. retain the following if it is supplied by the Licensor 221 | with the Licensed Material: 222 | 223 | i. identification of the creator(s) of the Licensed 224 | Material and any others designated to receive 225 | attribution, in any reasonable manner requested by 226 | the Licensor (including by pseudonym if 227 | designated); 228 | 229 | ii. a copyright notice; 230 | 231 | iii. a notice that refers to this Public License; 232 | 233 | iv. a notice that refers to the disclaimer of 234 | warranties; 235 | 236 | v. a URI or hyperlink to the Licensed Material to the 237 | extent reasonably practicable; 238 | 239 | b. indicate if You modified the Licensed Material and 240 | retain an indication of any previous modifications; and 241 | 242 | c. indicate the Licensed Material is licensed under this 243 | Public License, and include the text of, or the URI or 244 | hyperlink to, this Public License. 245 | 246 | 2. You may satisfy the conditions in Section 3(a)(1) in any 247 | reasonable manner based on the medium, means, and context in 248 | which You Share the Licensed Material. For example, it may be 249 | reasonable to satisfy the conditions by providing a URI or 250 | hyperlink to a resource that includes the required 251 | information. 252 | 253 | 3. If requested by the Licensor, You must remove any of the 254 | information required by Section 3(a)(1)(A) to the extent 255 | reasonably practicable. 256 | 257 | 4. If You Share Adapted Material You produce, the Adapter's 258 | License You apply must not prevent recipients of the Adapted 259 | Material from complying with this Public License. 260 | 261 | 262 | Section 4 -- Sui Generis Database Rights. 263 | 264 | Where the Licensed Rights include Sui Generis Database Rights that 265 | apply to Your use of the Licensed Material: 266 | 267 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 268 | to extract, reuse, reproduce, and Share all or a substantial 269 | portion of the contents of the database; 270 | 271 | b. if You include all or a substantial portion of the database 272 | contents in a database in which You have Sui Generis Database 273 | Rights, then the database in which You have Sui Generis Database 274 | Rights (but not its individual contents) is Adapted Material; and 275 | 276 | c. You must comply with the conditions in Section 3(a) if You Share 277 | all or a substantial portion of the contents of the database. 278 | 279 | For the avoidance of doubt, this Section 4 supplements and does not 280 | replace Your obligations under this Public License where the Licensed 281 | Rights include other Copyright and Similar Rights. 282 | 283 | 284 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 285 | 286 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 287 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 288 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 289 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 290 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 291 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 292 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 293 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 294 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 295 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 296 | 297 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 298 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 299 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 300 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 301 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 302 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 303 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 304 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 305 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 306 | 307 | c. The disclaimer of warranties and limitation of liability provided 308 | above shall be interpreted in a manner that, to the extent 309 | possible, most closely approximates an absolute disclaimer and 310 | waiver of all liability. 311 | 312 | 313 | Section 6 -- Term and Termination. 314 | 315 | a. This Public License applies for the term of the Copyright and 316 | Similar Rights licensed here. However, if You fail to comply with 317 | this Public License, then Your rights under this Public License 318 | terminate automatically. 319 | 320 | b. Where Your right to use the Licensed Material has terminated under 321 | Section 6(a), it reinstates: 322 | 323 | 1. automatically as of the date the violation is cured, provided 324 | it is cured within 30 days of Your discovery of the 325 | violation; or 326 | 327 | 2. upon express reinstatement by the Licensor. 328 | 329 | For the avoidance of doubt, this Section 6(b) does not affect any 330 | right the Licensor may have to seek remedies for Your violations 331 | of this Public License. 332 | 333 | c. For the avoidance of doubt, the Licensor may also offer the 334 | Licensed Material under separate terms or conditions or stop 335 | distributing the Licensed Material at any time; however, doing so 336 | will not terminate this Public License. 337 | 338 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 339 | License. 340 | 341 | 342 | Section 7 -- Other Terms and Conditions. 343 | 344 | a. The Licensor shall not be bound by any additional or different 345 | terms or conditions communicated by You unless expressly agreed. 346 | 347 | b. Any arrangements, understandings, or agreements regarding the 348 | Licensed Material not stated herein are separate from and 349 | independent of the terms and conditions of this Public License. 350 | 351 | 352 | Section 8 -- Interpretation. 353 | 354 | a. For the avoidance of doubt, this Public License does not, and 355 | shall not be interpreted to, reduce, limit, restrict, or impose 356 | conditions on any use of the Licensed Material that could lawfully 357 | be made without permission under this Public License. 358 | 359 | b. To the extent possible, if any provision of this Public License is 360 | deemed unenforceable, it shall be automatically reformed to the 361 | minimum extent necessary to make it enforceable. If the provision 362 | cannot be reformed, it shall be severed from this Public License 363 | without affecting the enforceability of the remaining terms and 364 | conditions. 365 | 366 | c. No term or condition of this Public License will be waived and no 367 | failure to comply consented to unless expressly agreed to by the 368 | Licensor. 369 | 370 | d. Nothing in this Public License constitutes or may be interpreted 371 | as a limitation upon, or waiver of, any privileges and immunities 372 | that apply to the Licensor or You, including from the legal 373 | processes of any jurisdiction or authority. 374 | 375 | 376 | ======================================================================= 377 | 378 | Creative Commons is not a party to its public 379 | licenses. Notwithstanding, Creative Commons may elect to apply one of 380 | its public licenses to material it publishes and in those instances 381 | will be considered the “Licensor.” The text of the Creative Commons 382 | public licenses is dedicated to the public domain under the CC0 Public 383 | Domain Dedication. Except for the limited purpose of indicating that 384 | material is shared under a Creative Commons public license or as 385 | otherwise permitted by the Creative Commons policies published at 386 | creativecommons.org/policies, Creative Commons does not authorize the 387 | use of the trademark "Creative Commons" or any other trademark or logo 388 | of Creative Commons without its prior written consent including, 389 | without limitation, in connection with any unauthorized modifications 390 | to any of its public licenses or any other arrangements, 391 | understandings, or agreements concerning use of licensed material. For 392 | the avoidance of doubt, this paragraph does not form part of the 393 | public licenses. 394 | 395 | Creative Commons may be contacted at creativecommons.org. 396 | 397 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | SymPy Tutorial 2 | ============== 3 | A tutorial that shows the powerful capabilities of the computer 4 | algebra system SymPy for solving problems in high school math, 5 | calculus, mechanics, vectors, and linear algebra. 6 | 7 | 8 | Canonical URL 9 | ------------- 10 | 11 | http://minireference.com/static/tutorials/sympy_tutorial.pdf 12 | 13 | 14 | 15 | 16 | Jupyter notebooks 17 | ----------------- 18 | 19 | Click the Binder button below to play with the code of this tutorial 20 | as an interactive notebook. 21 | 22 | [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/minireference/sympytut_notebooks/HEAD) 23 | 24 | Navigate to the `notebooks/` directory and start with `Intro.ipynb`, 25 | or jumpt directly to the topics you're interested in. 26 | 27 | source: https://github.com/minireference/sympytut_notebooks/tree/master/notebooks 28 | 29 | 30 | 31 | TODOs 32 | ----- 33 | - [ ] Review on paper 34 | - [ ] Add plug for the LA book 35 | - [ ] Regenerate notebooks from tex 36 | 37 | 38 | License 39 | ------- 40 | The tutorial and notebooks are licensed under CC-BY-4.0. 41 | 42 | 43 | -------------------------------------------------------------------------------- /figures/cover_v40_noline_lite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/minireference/sympy_tutorial/96335e264bea88decd50801fbefc9d80d3702d4a/figures/cover_v40_noline_lite.png -------------------------------------------------------------------------------- /notebook/cover_v40_noline_lite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/minireference/sympy_tutorial/96335e264bea88decd50801fbefc9d80d3702d4a/notebook/cover_v40_noline_lite.png -------------------------------------------------------------------------------- /sympy_tutorial.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/minireference/sympy_tutorial/96335e264bea88decd50801fbefc9d80d3702d4a/sympy_tutorial.pdf -------------------------------------------------------------------------------- /sympy_tutorial.tex: -------------------------------------------------------------------------------- 1 | \documentclass[9pt]{IEEEtran} 2 | 3 | \usepackage[T1]{fontenc} 4 | \usepackage{lmodern} 5 | \usepackage{amssymb,amsmath} 6 | \usepackage{ifxetex,ifluatex} 7 | 8 | 9 | 10 | 11 | \usepackage{fixltx2e} % provides \textsubscript 12 | % use upquote if available, for straight quotes in verbatim environments 13 | \IfFileExists{upquote.sty}{\usepackage{upquote}}{} 14 | \ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex 15 | \usepackage[utf8]{inputenc} 16 | \else % if luatex or xelatex 17 | \ifxetex 18 | \usepackage{mathspec} 19 | \usepackage{xltxtra,xunicode} 20 | \else 21 | \usepackage{fontspec} 22 | \fi 23 | \defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase} 24 | \newcommand{\euro}{€} 25 | \fi 26 | % use microtype if available 27 | \IfFileExists{microtype.sty}{\usepackage{microtype}}{} 28 | \ifxetex 29 | \usepackage[setpagesize=false, % page size defined by xetex 30 | unicode=false, % unicode breaks when used with xetex 31 | xetex]{hyperref} 32 | \else 33 | \usepackage[unicode=true]{hyperref} 34 | \fi 35 | \hypersetup{breaklinks=true, 36 | bookmarks=true, 37 | pdfauthor={}, 38 | pdftitle={Taming math and physics using SymPy}, 39 | colorlinks=true, 40 | citecolor=blue, 41 | urlcolor=black, 42 | linkcolor=magenta, 43 | pdfborder={0 0 0}} 44 | \urlstyle{same} % don't use monospace font for urls 45 | \setlength{\parindent}{0pt} 46 | \setlength{\parskip}{6pt plus 2pt minus 1pt} 47 | \setlength{\emergencystretch}{3em} % prevent overfull lines 48 | \setcounter{secnumdepth}{0} 49 | 50 | \usepackage{etoolbox} 51 | 52 | 53 | \title{{\Huge Taming math and physics using \texttt{SymPy} }} 54 | % A tale of with equations and code} 55 | %\author{Ivan Savov} 56 | \author{{\normalsize Tutorial based on the \href{http://minireference.com}{{\sc No bullshit guide}} series of textbooks by \href{mailto:ivan.savov+SYMPYTUT@gmail.com}{Ivan Savov}}} 57 | \date{\today} 58 | 59 | %\usepackage{listings} 60 | \usepackage{moreverb} 61 | \usepackage[letterpaper,bmargin=1.1cm,rmargin=0.95cm,lmargin=0.95cm,tmargin=1cm,headsep=0.2cm,footskip=0.5cm]{geometry} 62 | 63 | 64 | \usepackage{bbm} 65 | \usepackage{wrapfig} 66 | \usepackage{graphicx} 67 | 68 | \usepackage{ifthen} 69 | 70 | \newboolean{TUTORIAL} % if TUTORIAL==true: 71 | \setboolean{TUTORIAL}{true} % show extra defs and repeats of explanations 72 | 73 | \newboolean{FORLA} % if FORLA: show extra content for LA book 74 | \setboolean{FORLA}{true} % if not FORLA: show content for MathPhys book 75 | 76 | 77 | \newcommand{\printcp}{} 78 | \newcommand{\printni}{} 79 | 80 | % doest work 81 | %\usepackage[titles]{tocloft} 82 | %\setlength{\cftbeforechapskip}{.1ex} 83 | %\setlength{\cftbeforesecskip}{-.5ex} 84 | 85 | \setcounter{secnumdepth}{1} 86 | \setcounter{tocdepth}{0} 87 | \usepackage{setspace} 88 | %\addtocontents{toc}{\protect\setstretch{-20.1}} 89 | 90 | \newcommand*{\eqdef}{\stackrel{\raisebox{-2pt}{\scalebox{0.48}{def}}}{=}} % "defined to be equal" symbol (prev. used \equiv; other common is := ) 91 | 92 | \begin{document} 93 | 94 | 95 | \makeatletter 96 | \preto{\@verbatim}{\topsep=0pt \partopsep=0pt \vspace{-1.2mm}} 97 | \makeatother 98 | 99 | 100 | 101 | \maketitle 102 | 103 | %\vspace{-2mm} 104 | 105 | \begin{abstract} 106 | Most people consider math and physics to be scary beasts from which it is best to keep one's distance. 107 | Computers, however, can help us tame the complexity and tedious arithmetic manipulations associated with these subjects. 108 | Indeed, math and physics are much more approachable once you have the power of computers on your side. 109 | % 110 | %Understand math and physics 111 | 112 | This tutorial serves a dual purpose. 113 | On one hand, it serves as a review of the fundamental concepts of mathematics for computer-literate people. 114 | %who may have forgotten their math or never quite learned it detail. 115 | On the other hand, this tutorial serves to demonstrate to students how a computer algebra system 116 | can help them with their classwork. 117 | A word of warning is in order. 118 | Please don't use \texttt{SymPy} to avoid the suffering associated with your homework! 119 | Teachers assign homework problems to you 120 | %not because they want you to suffer but 121 | because they want you to learn. 122 | Do your homework by hand, 123 | but if you want, you can check your answers using \texttt{SymPy}. 124 | Better yet, use \texttt{SymPy} to invent extra practice problems for yourself. 125 | % 126 | %Let's get started! 127 | 128 | %The whole point of homework is for you to suffer. 129 | %Mathematical skill is developed through mathematical suffering---only 130 | %when trying to solve a problem that you haven't solved before will you 131 | %be forced to think and practice your skills. 132 | %Do not use \texttt{SymPy} to cheat on your homework! 133 | %You can use \texttt{SymPy} to check your answers though. 134 | %In fact, one of the best ways to learn math is to 135 | % solve them by hand, and then check your answers using \texttt{sympy}. 136 | 137 | %Let's kick some mathematical ass! 138 | 139 | \end{abstract} 140 | 141 | \begin{spacing}{-1} 142 | \tableofcontents 143 | \end{spacing} 144 | 145 | \input{99.sympy_tutorial.tex} 146 | 147 | 148 | 149 | 150 | %======================================================================= matrices 151 | \ifthenelse{\boolean{FORLA}}{ 152 | \input{99.LA_sympy_tutorial.tex} 153 | }{} 154 | 155 | 156 | 157 | \vspace{-2mm} 158 | %======================================================================= conclusion 159 | \section*{Conclusion} 160 | \label{sec:conclusion} 161 | 162 | I would like to conclude with some words of caution about the overuse of computers. 163 | Computer technology is very powerful and is everywhere around us, 164 | but let's not forget that computers are actually very dumb: 165 | computers are mere calculators and they depend on your knowledge to direct them. 166 | It's important that you learn how to do complicated math by hand in order to be 167 | able to instruct computers to do math for you and to check the results of your computer calculations. 168 | I don't want you to use the tricks you learned in this tutorial to avoid math problems from now on 169 | and simply rely blindly on \texttt{SymPy} for all your math needs. 170 | I want both you and the computer to become math powerhouses! 171 | The computer will help you with tedious calculations (they're good at that) 172 | and you'll help the computer by guiding it when it gets stuck (humans are good at that). 173 | 174 | 175 | 176 | 177 | 178 | %======================================================================= links 179 | \section*{Links} 180 | \label{sec:links} 181 | 182 | [ Installation instructions for \texttt{jupyter notebook} ] \\ 183 | \href{https://jupyter.readthedocs.io/en/latest/install.html}{\texttt{https://jupyter.readthedocs.io/en/latest/install.html}} 184 | 185 | \noindent 186 | [ The official \texttt{SymPy} tutorial ] \\ 187 | \href{http://docs.sympy.org/latest/tutorial/intro.html}{\texttt{http://docs.sympy.org/latest/tutorial/intro.html}} 188 | 189 | \noindent 190 | [ A list of \texttt{SymPy} gotchas ] \\ 191 | \href{http://docs.sympy.org/dev/gotchas.html}{\texttt{http://docs.sympy.org/dev/gotchas.html}} 192 | 193 | \noindent 194 | [ SymPy video tutorials by Matthew Rocklin ] \\ 195 | \href{http://pyvideo.org/speaker/583/matthew-rocklin}{\texttt{http://pyvideo.org/speaker/583/matthew-rocklin}} 196 | 197 | 198 | 199 | 200 | 201 | %======================================================================= book_plug 202 | \section*{Book plug} 203 | \label{sec:book_plug} 204 | 205 | 206 | The examples and math explanations in this tutorial are sourced from the 207 | {\sc no bullshit guide} series of books published by Minireference~Co. 208 | We publish textbooks that make math and physics accessible and affordable for everyone. 209 | If you're interested in %relearning you high school math and 210 | learning more about the math, physics, and calculus topics discussed in this tutorial, 211 | check out the \textbf{No bullshit guide to math and physics}. 212 | %As the book's author, 213 | %I'm somewhat biased so I can't give you an objective review. 214 | The book contains the distilled information that normally comes in two first-year university books: 215 | the introductory physics book (1000+ pages) and the first-year calculus book (1000+ pages). 216 | Would you believe me if I told you that you can learn the 217 | same material from a single book that is \texttt{1/7}\textsuperscript{th} the size and \texttt{1/10}\textsuperscript{th} of the 218 | price of mainstream textbooks? 219 | 220 | % It's not a scam, it's just the free market doing its thing. 221 | % Until now mainstream publishers pushed their products to the captive audience of students. 222 | % With eBooks and print-on-demand technology, random Ph.D.'s like me can write books 223 | % Which book do you trust more? The one written by committee or the one written by a human? 224 | % 225 | 226 | 227 | %The fundamental tenet of the Minireference Co. publishing company is the utmost respect for the reader, 228 | %so we 229 | 230 | \begin{wrapfigure}[18]{r}{0pt} 231 | \includegraphics[width=135pt,height=207pt]{figures/cover_v40_noline_lite.png} 232 | %\includegraphics[width=125pt]{/Library/WebServer/Documents/miniref/data/media/physics/mass_spring-highres.png} 233 | \end{wrapfigure} 234 | 235 | This book contains short lessons on math and physics, 236 | written in a style that is jargon-free and to the point. 237 | % 238 | % The main focus of the book is to show the intricate connections between the concepts of mechanics and calculus. 239 | % 240 | Often calculus and mechanics are taught as separate subjects. 241 | It shouldn't be like that. 242 | If you learn calculus without mechanics, it will be boring. 243 | If you learn mechanics without calculus, you won't truly understand what is going on. 244 | % 245 | This textbook covers both subjects in an integrated manner. 246 | % highlighting the connections between the subjects. 247 | 248 | Contents: 249 | \begin{itemize} 250 | \item {\sc high school math}%: (40pp) %Review of algebra, functions and trigonometry. 251 | \item {\sc vectors}%: (20pp) 252 | \item {\sc mechanics} 253 | \item {\sc differential calculus}%: (30pp) 254 | \item {\sc integral calculus}%: (20pp) 255 | \item 250+ practice problems %: (20pp) 256 | % \item {\sc linear algebra}%: (60pp) 257 | \end{itemize} 258 | 259 | \noindent 260 | %Available at the \textbf{McGill bookstore.}}{} 261 | \hfill {\small 5\textonehalf[in] $\times$ 8\textonehalf[in] $\times$ 445[pages] } 262 | 263 | 264 | %Save yourself some time: instead of reading three books you can read just one. 265 | %The print version will be available December 1$^{\text{st}}$. 266 | %Get in touch with me by email if you want to buy a copy of the book in print or as a PDF. 267 | % 268 | %I will also appreciate it if you send me feedback and comments. 269 | %where I post other tutorials like this one. 270 | %Don't hesitate to get in touch with me if you have any questions or feedback: 271 | %. I would also like to hear what you feedback 272 | %do you like the style of writing? 273 | 274 | %in which all the material that you normally taught in first year science is explained in a concise manner. 275 | 276 | % 277 | %If you liked this tutorial you can check out the other ones on \url{http://minireference.com} 278 | %and order the printed book which has not only formulas but also compact explanations: 279 | %\url{http://minireference.com/order_book/}. 280 | 281 | 282 | % 283 | %Also of interest, 284 | 285 | %The coverage of the math and physics topics in this tutorial were not sufficient 286 | %to do justice to the subjects. The goal here is to quickly introduce you to the 287 | %useful \texttt{SymPy} commands. 288 | % 289 | %you should consider some of my other tutorials on mechanics 290 | %If you're interested in learning more about calculus and mechanics, 291 | %you should consider the \emph{No bullshit guide to math and physics}---a short textbook like no other. 292 | 293 | \noindent 294 | For more information, see the book's website %and find more information on the following website 295 | at \, \href{http://minireference.com/}{\texttt{minireference.com}}. 296 | 297 | The linear algebra examples presented in Section~\ref{sec:linear_algebra} are 298 | sourced from the \href{https://gum.co/noBSLA}{\textbf{No bullshit guide to linear algebra}}. 299 | Check out the book if you're taking a linear algebra course of if you're missing the prerequisites 300 | for learning machine learning, computer graphics, or quantum mechanics. 301 | 302 | I'll close on a note for potential readers who suffer from math-phobia. 303 | Both books start with an introductory chapter that reviews all 304 | high school math concepts needed to make math and physics 305 | accessible to everyone. 306 | Don't worry, we'll fix this math-phobia thing right up for you; 307 | \textbf{when you've got \texttt{SymPy} skills, math fears \emph{you}!} 308 | 309 | To stay informed about upcoming titles, 310 | follow \href{https://twitter.com/minireference}{\texttt{@minireference}} on twitter 311 | and check out the facebook page at \href{http://fb.me/noBSguide}{\texttt{fb.me/noBSguide}}. 312 | %You're also invited to the \textbf{online office hours} where I'll answer 313 | %your questions and solve problems from past years' finals\ \ \hfill \href{http://on.fb.me/1aPxy5w}{\texttt{on.fb.me/1aPxy5w}} 314 | %For comments, feedback, and questions, you can get in touch with me here \hfill 315 | 316 | 317 | 318 | 319 | \end{document} 320 | 321 | --------------------------------------------------------------------------------