Sage Python is an open-source computational tool used in STEM courses. As an example of what Sage can do, channel Archimedes and compute the \(n\)-th approximation to the polar angle \(\theta\) of the cartesian point \((x,y)\) by pasting the code
(x,y) = (-1,0)
d = 0
n = 10
theta = sqrt((x-1)^2+y^2)
alpha = theta/2
f(x) = sqrt(2-2*sqrt(1-x^2))/2
for k in range(n):
if d > 0: theta = N(theta,digits=d)
show(theta)
alpha = f(alpha)
theta = 4 * 2^k * alpha
below. Try \((x,y)=(-1,0)\) with \((d,n)=(0,10)\) and \((d,n)=(50,50)\) (\(d\) is the number of decimal places).
Sage
Enter code here then press "Evaluate".
Sage code below is in blue boxes. Warning: Sage Python code is not always the same as vanilla Python code. In particular, if you use numpy or similar, ignore the rest of this page.
Sage Glossary
Case matters
Lowercase, uppercase, camelcase.
Show
show(...) displays the result, whether it is a number, an equation, a graph, a surface, etc.
Arithmetic
Addition a + b, subtraction a - b, multiplication a * b, division a / b, mod a % b, powers a ^ b, and parentheses(...). For example,
outputs \(19\) and \(150\) and \(3\) and \(23/5\).
Decimals
To convert a number a to a decimal with n digits, write N(a,digits=n). For example, the code
a = 1234/1728
show(a)
a = N(a,digits=20)
show(a)
outputs \(617/864\) and \(0.71412037037037037037\).
Square roots
The code
a = sqrt(25)
b = sqrt(1234/1728)
c = N(b,digits=40)
show(a)
show(b)
show(c)
outputs \(5\) and
\(\dfrac1{12}\sqrt{\dfrac{617}6}\)
and \(0.8450564302875698314535479970302979455774\).
Conditionals
Equal a == b, not equal a != b, less than a < b, greater than a > b, less or equal a <= b, greater or equal a >= b. The code
show(5^2 == 25)
show(15 != 10)
show(15 <= 10)
outputs "True" and "True" and "False".
If statement
if <conditional>: is a header announcing the start of an if block of code. The code block after the header is executed if the conditional is True. The code block after the header is always indented:
if d^2 > 9:
... first line of code block
... second line of code block
Range
range(5)
is the same as 0,1,2,3,4 and range(2,9) is the same as 2,3,4,5,6,7,8.
Lists
[a,b,c,...] (enclosed in brackets).
Lists can also be generated through comprehension, for example [ k^2 for k in range(10) ] returns [0,1,4,9,16,25,36,49,64,81].
Lists are mutable.
Tuples
(a,b,c,...) (enclosed in parentheses). A 1-tuple is written with a comma (a,). Tuples are immutable.
Here comprehension( k^2 for k in range(10) ) yields a generator.
For statement
for i in range(5): and for i in range(2,9): are headers announcing the start of a for block. The code block after the header is executed repeatedly with the indexi taking sequentially the values in the range.
The code block after the header is always indented:
for i in range(2,9):
... first line of code block
... second line of code block
Graphics Object
This is how Sage stores the data in a drawing of a point, a line, a graph, a surface, etc. It is stored in the computer as a graphics object. Graphics objects A, B, C, etc. may be combined by writing
A + B + C + etc. Graphics objects are displayed using show.
Function
f(x) = x^2*sin(x) or g(x,y)= x^2*sin(x*y) are functions. Evaluate functions using a = f(2) or a = f(x=2) or b = g(3,y) or b = g(x=3). Then show(a) results in \(4\sin2\) and show(b) results in \(9\sin(3y)\). No need to write var('x'), Sage automatically creates x as a variable.
Constants and Variables
Sometimes x is a constant, sometimes x is a variable. The code
x = 2
show(x)
outputs \(2\). Here x is a constant. The value of the constant x is \(2\).
The code
var('x')
show(x)
outputs \(x\). Here x is a variable. The code var('x','y','a') defines three variables x, y, a. Defining a function f(x) = x^2 automatically makes x a variable.
Equations
The code
f(x) = x^2
m = 2
b = 4
var('y')
show(y == m*x+b)
show(y == f(x))
outputs the equations \(y=2x+4\) and \(y=x^2\). Equations can be given names, for example
var('x','y')
eq = y == 2*x+4
show(eq)
outputs \(y=2x+4\).
Points
P = point((x,y)) creates a graphics point P corresponding to the point \((x,y)\). To draw it, use show(P).
For multiple points, use points(L) where L is a list of points.
2D Cartesian Plot
G = plot(f(x),(x,a,b)) creates a graphics plot G corresponding to the plot of the function \(f(x)\) over the interval \(a\le x\le b\).
To draw it, use show(G).
2D Polar Plot
G = polar_plot(f(theta),(theta,a,b)) creates a graphics plot G corresponding to the plot of the function \(f(\theta)\) over the interval \(a\le \theta\le b\).
To draw it, use show(G).
3D Plot
G = plot3d(f(x,y),(x,a,b),(y,c,d)) creates a graphics plot G corresponding to the plot of the function \(f(x,y)\) over the region \(a\le x\le b\), \(c \le y \le d\).
To draw it, use show(G).
Complex Numbers
Complex numbers are written as usual x+y*i or r*e^(i*theta). The code abs(z), arg(z) return the absolute value, argument of $z$, conjugate(z) is the conjugate of $z$, and z.real(), z.imag() are the real and imaginary parts of $z$.
Complex Plot
The code complex_plot(f, (a,b),(c,d)) draws the complex function \(f(z)\) over the region \(a\le x\le b\), \(c\le y\le d\).
Here the brightness is $r$ ($r=0$ is black) and the hue is $\theta$ ($\theta=0$ is red), where $f(z)=re^{i\theta}$.
Multiple Functions
To plot multiple functions \(f,g,h\) at the same time, enter them into plot or plot3d etc. as a list [f,g,h].
Line Segment
line([(x_1,y_1),(x_2,y_2)]) creates a graphics line segment corresponding to the line segment joining the points \((x_1,y_1)\) and \((x_2,y_2)\). Notice the two points are inside a list [...]. Can have more than two points, for example, if L=[a,b,c,d] is a list of four points, then show(line(L)) draws the line segments joining the points \(a\), \(b\), \(c\), \(d\) in order.
Derivative
Write derivative(f,x) or Df(x) = derivative(f,x).
To show it, write show(derivative(f,x)) or show(Df(x)).
Strings
A string is any sequence of characters enclosed in quotes '...', for example 'alpharomeo'. The string '2' is different than the number 2.
Labels
You can add color to a plot by writing plot(f,x,a,b,color='blue').
You can add a label 'alpharomeo' to a plot by writing plot(f,x,a,b,legend_label='alpharomeo').
Anti-derivative or Indefinite Integral
Write integral(f,x) or I(x)=integrate(f,x).
To show it, write show(integral(f,x)) or show(I(x)).
This gives the indefinite integral $\int f(x)\,dx$.
Area or Definite Integral
Write integral(f,x,a,b) or I=integrate(f,x,a,b).
To show it, write show(integral(f,x,a,b)) or show(I).
This gives the definite integral $\int_a^b f(x)\,dx$.
Random Variables
The code
U = RealDistribution('uniform', [a, b])
G = RealDistribution('gaussian', sigma)
B = RealDistribution('beta', [a, b])
generates random variables with the specified distributions. They are sampled by
u = U.get_random_element()
g = G.get_random_element()
b = B.get_random_element()