# Preface

The purpose of this tutorial is to introduce students in APMA 0330 (Methods of Applied Mathematics - I) to the computer algebra system Sage. Sage is built out of nearly 100 open-source packages, and features a unified interface. Sage can be used to study elementary and advanced, pure and applied mathematics. This includes a huge range of mathematics including basic algebra, calculus, elementary to very advanced number theory, cryptography, numerical computation, commutative algebra, group theory, combinatorics, graph theory, exact linear algebra and much more. It utilizes various software packages and seamlessly integrates their functionality into a common experience.

The goal of this tutorial is two-fold. On one side, it provides tools to assist in solving problems based on an alternate software, that is free of charge---Sage. Therefore, this tutorial contains many scripts written is Sage. You, as the user, are free to use all codes for your needs, and have the right to distribute this tutorial and refer to this tutorial as long as this tutorial is accredited appropriately. On the other side, this tutorial supplements and accompanies the textbook Applied Differential Equations. The Primary Course by Vladimir Dobrushkin, CRC Press, 2015; http://www.crcpress.com/product/isbn/9781439851043. It contains many examples from real world problems that are used for demonstration and clarification of material presented in the textbook.

In this tutorial, the user learns the essential steps in mathematical modeling, including the identification of state variables, assumptions, the invocation of relevant science or empirical laws, the derivation of the governing differential equations, the avalable methods of solutions, the design of a computational algorithm, the generation of computer graphics, and the effect of the system's parameters. Therefore, the tutorial is an introduction to mathematical modeling with differential equations. Any comments and/or contributions for this tutorial are welcome; you can send your remarks to <Vladimir_Dobrushkin@brown.edu>

• index
• modules |
• next |
• previous |
• Contents

Introduction
Case Sensitivity
Basic Arithmetic Operations
Complex numbers
Arrays
Functions (explicit and implicit)
Calculus

Part I: Plotting

Plotting functions (Cartesian and polar coordinates)
(a) explicitly
(b) implicitly
vertical and horizontal lines
lables and texts
arrows
polar plot

Part II: First Order ODEs

Solving ODEs
(a) Using DSolve
(b) Verification
(c) Plotting
Direction fields
Separable equations
Equations reducible to separable equations.
Exact equations
Integrating Factors
Linear and Bernoulli equations
Riccati equation

Existence and Uniqueness of solutions
Qualitative analysis
Applications

Part III: Numerical Methods and Applications

Recurrences
Numerical solutions

a) Euler methods
b) Polynomial approximations
c) Runge-Kutta methods
d) Multistep methods
4) Numerov's method

Applications

Part IV: Second and Higher Order Differential Equations

Fundamental set of solutions. Wronskian
General solution
Reduction of order
Non-homogeneous equations.
Lagrange's method
Method of undetermined coefficients

Operator methods (not sure yet)
Applications

Part V: Series and Recurrences

Recurrences
Power series solutions to ODEs
Bessel functions
Airy functions
Orthogonal polynomials
a. Chebyshev
b. Legendre
c. Hermite
d. Laguerre
Euler Systems of equations

Part VI: Laplace Transformation

Laplace transform
Heaviside function and discontinuous functions
Inverse Laplace transformation
Laplace transformation in differential equations
ODE with discontinuous functions

Mechanical and Electrical Vibrations
Other applications

# Introduction¶

Sage was initially created by William Stein in 2004--2005, using open source programs released under the GPL or a GPL-compatible license. The main goal of the project was to create a viable open source alternative to proprietary mathematical software to be used for research and teaching. The first release of the program was in February 2005. By the end of the year, Sage included Pari, GAP, and Singular libraries as standard and worked as a common interface to other mathematical programs like Mathematica and Maple.

# Distribution¶

There are two ways in which Sage can be distributed. One is as a "regular" OS X, Windows and/or Linux application named something like Sage-VERSION. This version needs to be downloaded and installed in your machine. Although it's a Desktop application, the software opens in your primary browser acting as a native webapp. The binaries can be downloaded in the following links:

Although the desktop version has the advantage of working offline, the best choice is to use the online version, which is more user friendly and can store work in the cloud. The cloud version can be accessed in the following link:

https://cloud.sagemath.com/

https://cloud.sagemath.com/

2) Will be presented to you a login page in which you have to create an account

Both desktop and cloud versions will open in your default browser. Although, with the cloud version you can use Sage, R, Octave, Python, Cython, GAP, Macaulay2,
Singular, and much more. You can edit documents with inverse and forward search, and Sage mode. Collaboratively edit IPython notebooks, Sage worksheets, and all
other document types Write, compile, and run code in most programming languages and also use command line terminals.

One of the strengths of Sage is that it can be used over the network without requiring any installation of the application.
The Sage Notebook is a web browser-based graphical user interface for Sage. It allows writing and running code, displaying
embedded two and three dimensional plots, and organizing and sharing data with other users. The Sage Notebook works with
most web browsers without the need for additional add-ons or extensions. However, Java is required to run Jmol, the Java
applet used in Sage to plot 3D objects.

In addition to these main options, Sage can be applied in alternative ways. For instance, a single cell containing Sage code can be embedded
in any webpage and evaluated using a public single cell server. There is also support to embed Sage code and graphics in LaTeX documents
using Sagetex.

1) For you to use Sage, first you have to create a new project.

2) Once you've created the new project and given a name and description, you will create a new Sage file. Once you created the .sagews file, your're all set! Just start using Sage.

3) You execute commands by pressing Shif+Enter (simultaneously).

# Case Sensitivity¶

Sage is case sensitive for both variables can be defined and for commands. The variable "a" (lower case) is different from "A" (upper case). You will know if the command that you enter is correct because the color of the command will change to black. The irartional constant Pi (=3.141926...) can be entered either as pi or, its numerical value float(pi), which gives output: 3.141592653589793.
One of the key aspects of using Sage is knowing how to enter a command. Once you have typed the command, hit shift-enter.

## Basic Arithmetic Operations¶

The goal of this document is not to teach you numerical analysis, but to explain how to express your ideas in Sage. By numerical computation, we essentially mean machine precision floating point computations.

Type in the first cell, hold the shift key down, and press the enter key.

sage: a=1
You may be surprised that nothing appeared to happen. In fact, the value 1 was assigned to the variable a, but this result was not echoed. Repeat on the cell below; click on the cell, then use "shift-enter" or click on "evaluate". So if you type
sage: a
Sage will provide you the numerical value: 1. Similarly,
sage: b=2; b

This time the value 2 was assigned to b and then the value of b was echoed. The semicolon is used to separate commands appearing on the same line. The same thing could be done by typing "b=2", pressing enter, typing "b".

Feel free to use whichever of these approaches is most comfortable to you.

You may type more than one command in a window by placing semicolons between them.
sage: 2+3/5; 34*18-333/5579
The underscore character refers to the previous result.
sage: factor(_) 3 * 193
Sage is using simple arithmetic expressions: “+”, “−”, “∗”, and “∕”. You will learn more later.

## Standard Functions¶

Familiar from calculus functions such as exponential and power functions as well as many others are built-in into sage. For example, the square root and greatest common division are among them:
sage:  sqrt(a)sage:  gcd(b)
The function exp(x) is an alternate form of e^x
sage: e^2; exp(2) e^2

However, to use any function, one need first to define an intependent variable or variables. It can ve done as follows:

sage:  x1 = var('x1'); x1x1sage:  a, b, c = var('a, b, c ')

or just

sage: var('a, b, c ')

Logarithm function

The absolute value function is denote by abs. Some examples:

sage:  abs(pi*I)pisage: abs(log(1/3))-log(1/3)

The binomial coefficient

## Numerical Evaluations¶

To echo a floating point number, you have to use the float() function with the
variable you assigned the expression or fraction.

sage: b=2/3sage: float(b)0.6666666666666666
We can evaluate trigonometric expressions with numerical entries. For instance:

sage: q = cos(2*pi/50)sage: numerical_approx(q))0.992114701314478sage: q.n()0.992114701314478sage: q.n(prec=100) # bits0.99211470131447783104979304279sage: q.n(digits=50) # decimal digitssage: n(q)0.992114701314478sage: N(q)0.992114701314478
sage: RealField(100) # Real Field with 100 bits of precisionsage: RealField(100)(q)0.99211470131447783104979304279sage: RR  # Real Field with 53 bits of precisiosage: RR(q)0.992114701314478sage: RealField(100)  # Real Field with 100 bits of precision0.99211470131447783104979304279
sage: a=2/pi*sqrt(3)sage: RealField(100)(a)1.1026577908435840990226529966
The solve function solves equations. To use it, first specify some variables; then the arguments to solve are an equation (or a system of equations), together with the variables for which to solve:
sage: u = var('u')sage: diff(sin(u), u)cos(u)

## Some Numbers¶

Sage understands π, e, and i or j (the square of i or j is −1).
sage: 3*pi; n(_); n(e); I^23*pi9.424777960769382.71828182845905-1

Sage knows some famous numbers. For instance, the golden ratio $$\phi = \dfrac{1 + \sqrt{5}}{2} \approx 1.618$$ can be invoked as follows

sage: R = RealField(n) #n is the number of decimal places you wantsage: Rsage: R(golden_ratio)

For example,

sage: R = RealField(16)sage: RReal Field with 16 bits of precisionsage: R(golden_ratio)1.618sage: R = RealField(50)sage: R(golden_ratio)
1.6180339887499

The binomial coefficient

$\binom{x}{k} = x(x-1)(x-2) \cdots (x-k+1)/k!$
is defined for arbitrary x and non-negative integer k. The expression in the numerator is called falling factorial and denoted as
$x^{\underline{k}} = x(x-1)(x-2) \cdots (x-k+1) .$
sage: n=var('n')sage: binomial(n, 2)1/2*(n-1)*nsage: binomial(5, 2)10

Multinomial coefficients $$\binom{n}{a,b,c,\ldots} = \dfrac{n!}{a! \,b! \,c!\, \cdots} , \quad n=a+b+c+\cdots ,$$ (and in particular, binomial coefficients $$\binom{n}{a} = \dfrac{n!}{a! \,(n-a)!}$$ ) can be evaluated using the factorial operator. For instance, multinomial coefficient $$\binom{213}{14\,26\,43\, 53\, 77}$$ is divisible by 2^(13), but not divisible by 2^(14):

sage: (factorial(213)/(factorial(14)*factorial(26)*factorial(43)*factorial(53)*factorial(77)))/(2^13)93363309484444679588239580775138831058136467706688777059897484314845545215474470906701382347877254311222104806441347873998876875

## Complex Numbers¶

sage: z = complex(-3,4);
sage: z(-3+4j)sage: real(z)-3.0sage: imag(z)4.0sage: abs(z)5.0sage: arg(z)(2.214297435588181+0j)sage: conjugate(z)(-3-4j)sage: z1 = complex(-3,4);sage: z1(-3+4j)sage: z2=z1*i;sage: z2(-4-3j)sage: a = arrow((0,0),(real(z1),imag(z1)))sage: asage: plot(a)
sage: b = arrow((0,0),(real(z2),imag(z2)))sage: bsage: plot(b)
sage: plot(a+b)
sage: z = 1+isage: a = arg(z)sage: a1/4*pisage: b = abs(z)sage: bsqrt(2)sage: c = abs(z)*e^(I*(arg(z)));sage: csqrt(2)*e^(1/4*I*pi)sage: simplify(c)I + 1sage: sqrt(-8,all=true)[2*sqrt(-2), -2*sqrt(-2)]sage: solve( x^3 == -8, x )[x == I*sqrt(3)*(-1)^(1/3) - (-1)^(1/3), x == -I*sqrt(3)*(-1)^(1/3) - (-1)^(1/3), x == 2*(-1)^(1/3)]

## Functions

### I. How to define functions

There are several ways to define things which might deserve to be called “functions”. If one just start

sage: def f(z): return z^2sage: type(f)type 'function'sage: f(2)4sage: plot(f,0 2)Graphics object consisting of 1 graphic primitive

As you see, this function can be plotted, but not differentiated or integrated because z is a dummy variable. It can be fixed by typing:

sage: var('z') # define z to be a variablezsage: f(z)z^2sage: plot(f(z),0 2)Graphics object consisting of 1 graphic primitive

Another way is to define a “callable symbolic expression”. These can be plotted, differentiated, and integrated. To define a function, just type in the formula. There are some examples.

sage: f(x)=(cos(x)-1)/x^2# f(x) is now defined and values can be passedsage: f(3)1/9*cos(3) - 1/9sage: f(pi)-2/pi^2sage: f(pi).n()  # numerically evaluate -0.202642367284676
sage: type(f)type 'sage.symbolic.expression.Expression'
Symbolic variables must be defined as such
sage: var('a b')(a, b)sage: f(a+b)(cos(a + b) - 1)/(a + b)^2
Simple example of constructing useful 2D function plot:
sage: f(x).plot()
# plot(function, (starting x pass to function, ending x pass to function), ymin = graphical range min, ymax = graphical range maxsage: plot(f(x), (-2*pi, 2*pi),ymin = -1, ymax = 1)

## II. Built-in special functions

There are many functions, including special functions, that are available in Sage. We start with ceiling and floor functions that are denoted by

$\lceil x \rceil \qquad\mbox{and} \qquad \lfloor x \rfloor ,$

respectively. Here x is an arbitrary real number.

sage: ceil(sin(8)/sin(2))2sage: ceil(5.37)6

The error function, defined for real values of x, as

$\mbox{erf}(x) = \frac{2}{\sqrt{\pi}}\, \int_0^x e^{-t^2}\,{\text d}t .$
This function is also defined for complex values, via analytic continuation.
sage: erf(2)erf(2)sage: erf(2).n() 0.995322265018953sage: erf(2).n(100) 0.99532226501895273416206925637

## III. Discontinuous functions

To define a discontinous function, intervals must be continuos and individually discrete i.e., intervals must connect to next but must be over a defined interval; variable definition is optional.

sage: f1 = x^2sage: f2 = 4-xsage: f = piecewise([[(0,2),f1],[(2,4),f2]], x)# examplessage: f(1)1sage: f(2.5)1.50000000000000sage: f(1.5)2.25000000000000#important note!!!!!sage: f(2)3#function at the interval junction returns (f1(2)+f2(2))/2, true for all junctions

Plot of piecewise function

sage: f.plot()
A derivative of a peicewise continuous function returns derivative of pieces
sage: f.derivative()Piecewise defined function with 2 parts, [[(0, 2), x |--> 2*x], [(2, 4), x |--> -1]]

# Usefule attributes

# Critical points only defined over individual functions, does not include interval points

sage: f.critical_points()[]
sage: f.domain()(0, 4)sage: f.intervals()[(0, 2), (2, 4)]sage: f.end_points()[0, 2, 4]sage: f.which_function(1)x |--> x^2sage: f.which_function(3)x |--> -x + 4


# 1. Part 1: Plotting

Part I. Plotting

Plotting functions
Implicit plot
Vertical and horizontal lines
Lables and texts
Arrows
Pollar plot
Direction fields

# 1. Part 2: First Order ODEs

Solving ODEs
Direction fields
Separable equations
Equations reducible to separable equations.
Exact equations
Integrating Factors
Linear and Bernoulli equations
Riccati equation

Existence and Uniqueness of solutions
Qualitative analysis
Applications

# 1. Part 3: Numerical Methods and Applications

Recurrences
Numerical solutions

a) Euler methods
b) Polynomial approximations
c) Runge-Kutta methods
d) Multistep methods
4) Numerov's method

Applications

# 1. Part 4: Second and Higher Order ODEs

Second order differential equations

Fundamental set of solutions. Wronskian
General solution
Reduction of order
Non-homogeneous equations.
Lagrange's method
Method of undetermined coefficients

Operator methods (not sure yet)
Applications

# 1. Part 5: Series and Recurrences

First order recurrences
Second order recurrences
Generating functions
Series solutions for the first order equations
Series solutions for the second order equations
Generalized series solutions.
Bessel equation
Airy equation
Chebyshev equations
Legendre equation
Hermite equation
Laguerre equation
Applications

# 1. Part 6: Laplace Transform

Laplace transform
Heaviside function
Laplace Transform of Discontinuous Functions
Inverse Laplace transformation
Laplace transformation in differential equations

Mechanical and Electrical Vibrations
Other applications