# Sage Introduction¶

This document aims to give a crash-course to Sage. There are many additional resources for help, including the built-in documentation (discussed below), the official Sage tutorial, and the (highly recommended) open textbook Computational Mathematics with SageMath.

Sage is free and open source. Information on running a local installation can be found on the Sage installation guide. Alternatively, Sage can be run "in the cloud" by making a (free) account on the CoCalc website or by uploading a Jupyter notebook to a public git repository and using mybinder.org.

This document is written as a Jupyter notebook, the most common (and convenient) way to write and execute Sage code. A notebook is composed of cells. Most of the cells in this notebook consist of an Input section (containing Sage code) and (potentially) an output section (containing the result of evaluating that Sage code) $-$ some code cells simply perform a computation without returning anything (for instance, updating the values of variables). A few cells (including the current one) consist of formatted text and $\rm\LaTeX$ equations, written using the Markdown markup language. A third type of cell contains plain, unformatted text.

To execute a piece of Sage code, click on the Input section of the corresponding code cell and hit Shift + Enter (only hitting Enter simply adds a new line). The reader should execute each statement as they work through the notebook, and is encouraged to modify the code and play around as they go. Note that skipping a cell may result in errors when later cells are executed (for instance, if one skips a code block defining a variable and later tries to run code calling that variable). To add a new cell, click to the left of any cell and press the "a" key (to insert above) or the "b" key (to insert below). To delete a cell, click to the left of a cell and press the "d" key twice. These (and other) tasks can also be accomplished through the menu bars at the top of the page.

This introduction is based off of a worksheet originally written by Steven Melczer.

### Part 1: The Basics of Sage¶

We begin with an explanation of arithmetic in Sage, if statements, for and while loops, and Sage functions (in the programming sense; symbolic mathematical functions are described in Part 2 below).

In [1]:
# Any text on a line after a '#' symbol is considered a comment, and is not evaluated by Sage
# Sage can be used as a calculator using usual math notation
# (recall you need to click on a cell and hit Shift + Enter to evaluate it)
1 + 3*4
Out[1]:
13
In [2]:
# Code in a Sage cell should be entered in sequence, with one "instruction" per line
# (multiple instructions can be put on the same line using a semicolon -- see examples below)
# The result of previous executions of Sage cells (both the current cell and other cells) is stored by Sage
# All (non-commented) code is executed, however only the output of the final line is printed by default
1 + 2
2 ^ 3
Out[2]:
8
In [3]:
# Variables are defined using the "=" operator
# Note that some operations (such as variable assignment) do not have an output
# So we add another line to print the value of our variable
mult = 11 * 12
mult
Out[3]:
132
In [4]:
# randint(a, b) returns a random integer between a and b inclusive
A = randint(0, 10^9)
B = randint(0, 10^9)
A+B
Out[4]:
1267489433
In [5]:
# Sage can compute with large integers
A*B
Out[5]:
377455941306838470
In [6]:
# Even very large integers can be computed exactly
A^100
Out[6]:
52540162234708150168537360901340793898262914480134450681087275068949877439818165995850940958175574383097273301183442124322832074701780784366063634430390961173909263802221249551415953948624019616135099842509313163690545837642284313016350555993943872237461064850611579617770780900741395912343302373327962563865658714436193391737923003396437221549761327143000410666464936720210334895137965877988507356437096240451329389643846537315650815206100389903330283369642709298815304915626231364419512975472941867926065026039278251042107824488375642749207377037512552111434163166732225516472319774351668790341847389341826177484229916197499584756984118913676127402037919235588908040982318782860767465844037938836127036017387658746127918234459179497914877883932122815906140967349157630012081839479025814019660928228842531347957073180266286971714934750996630689044188111669342333698295988142490386962890625
In [7]:
# To print other lines, use the print command
print(2^3) # This is an integer
print(3/9) # This is an exact rational number
print(3.0/9.0) # This is a floating point number
print(11 % 3) # This is 11 mod 3
8
1/3
0.333333333333333
2
In [8]:
# Multiple instructions can be put on the same line using a semicolon
# Again, only the output of the final line is displayed by default
2+2; print(1+2); 3*5
3
Out[8]:
15
In [9]:
# The "show" command outputs a latex-like pretty output
# Sage knows common math constants such as pi (lower case), e, and I (or the alternative i)
# Most common mathematical functions are supported by default
show(5/10 + 1/pi)
show(sin(pi/3))
show(log(2))
show(log(2).n(1000)) # Adding ".n()" gives a numerical approximation (can use ".n(k)" to get k bits)
show(exp(i*2*pi/3))
show(exp(I*2*pi/101))
In [10]:
# Sage computes with *exact* rational numbers
# For example, the following computes the sum of 1 + 1/2 + ... + 1/100
In [11]:
# Sage also has support for matrices and vectors
A = random_matrix(ZZ, 5)
b = random_vector(ZZ, 5)
show(A)
show(b)
In [12]:
# Sage can solve the linear system Ax = b for x using the solve_right method of matrices
# (named because x appears to the right of A in the system to solve)
show(A.solve_right(b))
In [13]:
# There are many useful built-in functions on matrices (e.g., to compute the determinant)
A.determinant()
Out[13]:
21
In [14]:
# Sage can even deal with matrices with symbolic entries
B = Matrix(SR, A)
B[4,4] = x
show(B)
show(B.solve_right(b))
In [15]:
# Mathematical objects and variables can be inserted in print commands using commas,
# or using empty curly braces {} and .format(math1,math2,...)
print("The area of a circle of radius 1 is approximately", pi.n())
print("The square-root of {} is approximately {}".format(log(2), sqrt(log(2)).n()))
The area of a circle of radius 1 is approximately 3.14159265358979
The square-root of log(2) is approximately 0.832554611157698
In [16]:
# To access the help page for a function, type the name of the function and then add a question mark
# For instance, evaluating the expression "sin?" (without quotes) gives the help page for sine
# THIS WILL OPEN A NEW WINDOW AREA
# Using two question marks (e.g. "sin??") shows the source code of the function
# (Note that for many low level functions like sin Sage relies on outside packages
# and the source code is not very informative)

# Similar information is provided by the "help" command, which prints below the current cell
print?
In [17]:
# The values "_", "__", and "___" (using one, two, and three underscores)
# are the last three output values. Printing displays content but does *not*
# return a value, so a block ending with a print statement has no output
print(_)
print(__)
21
15
In [18]:
# The output of previous cells can be directly accessed using the syntax Out[k]
# NOTE: cells are numbered by execution order --  running cells repeatedly or in
# different orders will change their numbering!
Out[13]
Out[18]:
21
In [19]:
# Sage is built on Python, and uses much of the same syntax.
# In particular, indentation is extremely important.
# If statements are defined with indentation
a = 2

if a<0:
print("Negative")
elif a==0:
print("Zero")
else:
print("Positive")
Positive
In [20]:
# In addition, an if statement can be written in one line
a = 2
if a>0: print("Positive")
Positive
In [21]:
# Functions are also defined with indentation
def fact(n):
if n==0:
return 1
else:
return n*fact(n-1)

print(fact(4))
print(fact(10))
print(fact) # Prints reference to the function
24
3628800
<function fact at 0x7f1efdac7010>
In [22]:
# running this code displays the source code for the function fact
fact??
In [23]:
# Lists in Sage are defined with square brackets
LST = [1,2,3,4]

print(LST)
print(len(LST)) # Print the length of the list
print(LST[0]) # Access elements from the left (starting at index 0)
print(LST[1]) # Print second element of the list
print(LST[-2]) # Negative indices access elements from the right
print(LST[1:3]) # Define sublist
print(LST[1:-1]) # Define sublist using negative index
print(LST[1:]) # Define sublist from a fixed index to end of list
[1, 2, 3, 4]
4
1
2
3
[2, 3]
[2, 3]
[2, 3, 4]
In [24]:
# Lists can be concatenated with '+'
# Strings can be concatenated similarly (they are lists of characters)
print([1,2,3] + ["a","b","c"])
print("hello" + " " + "world")
[1, 2, 3, 'a', 'b', 'c']
hello world
In [25]:
# For loops work over lists or generators, and are indented similarly to if statements and functions
LST = [0,1,2,3,4,5]
for k in LST:
print(k^2)
0
1
4
9
16
25
In [26]:
# The notation a..b can be used to build the list of numbers between integers a and b
for k in (0..6):
print(k^2)
0
1
4
9
16
25
36
In [27]:
# As in Python, Sage contains the function range(k), which encodes the numbers 0,1,...,k-1
# In Sage versions 8.x and lower, which rely on Python 2, range(k) returns the list [0,1,...,k-1]
# In Sage 9.0 and higher, which use Python 3, range(k) returns an *iterator* that can be converted to a list
# (think of an iterator as a method to construct elements of a list, one by one, which can be more efficient)
# We assume in our discussions that the user of this document is using Sage 9.0 or higher
# More details on this change can be found here: https://docs.python.org/3.0/whatsnew/3.0.html#views-and-iterators-instead-of-lists

print(range(5)) # printing an iterator just returns the iterator
print(list(range(5))) # the iterator can be converted to a regular list
for k in range(5): # loops can range directly over iterators, which can be more efficient
print(k^2)
range(0, 5)
[0, 1, 2, 3, 4]
0
1
4
9
16
In [28]:
# For loops can also be defined over one line
for k in range(5): print(k^2)
0
1
4
9
16
In [29]:
# There is a powerful alternate syntax for building lists using a
# function f(x) on the elements of a list LST: [f(k) for k in LST]
print([k^2 for k in range(5)])
print([cos(k*pi) for k in [1..5]])
[0, 1, 4, 9, 16]
[-1, 1, -1, 1, -1]
In [30]:
# While loops are defined similarly to for loops
k = 0
while k<5:
print(k^2)
k = k+1
0
1
4
9
16
In [31]:
# While loops can be broken using 'break'
k = 0
while True:
if k>= 5:
break
print(k^2)
k = k+1
0
1
4
9
16
In [32]:
# The map operator applies a function to each element of a list
# Similar to range, in Sage 9.0+ map returns a "map object" / iterator
# The list command can be used to obtain an honest list from a map object
list(map(abs,[-1,2,-3,4]))
Out[32]:
[1, 2, 3, 4]
In [33]:
# User defined functions can also be mapped, where appropriate
def double(k):
return 2*k

list(map(double,[-1,2,-3,4]))
Out[33]:
[-2, 4, -6, 8]
In [34]:
# Can also use map with 'lambda expressions' to define a function in place
print(list(map(lambda t: t*2, [-1,2,-3,4])))
print(lambda t: t^2) # Defines the function f(x) = x^2 in place
[-2, 4, -6, 8]
<function <lambda> at 0x7f1efd98a5f0>
In [35]:
# Can filter a list using 'filter'
# Similar to range and map, in Sage 9.0+ filter returns a "filter object" / iterator
# The list function can be applied to obtain an honest list from a filter object

print(list(filter(lambda t: t>0, [-1,2,-3,4])))
[2, 4]
In [36]:
# Can also use the list 'comprehension form' to filter elements when building a list
[p^2 for p in [1..10] if is_prime(p)]
Out[36]:
[4, 9, 25, 49]
In [37]:
# Can sort lists, when appropriate.
# Sort is a function of a list (see Part 2 below for additional details)
L = [1,4,3,2,7,6]
L.sort() # Modifies the list L in place
print(L)
L = ["a","acb","abc","ab"]
L.sort() # Sort in lexicographical order
print(L)
[1, 2, 3, 4, 6, 7]
['a', 'ab', 'abc', 'acb']
In [38]:
# Lists are stored by reference. Simply writing L2 = L1, makes L1 and L2 point to the *same* list
# Use L2 = copy(L1) to make an independent copy
# Note copy only works at one level of lists
# (use the "deepcopy" command to copy a list of lists, and make everything independent)

L1 = [1,2,3]
L2 = L1 # L2 points to the same list as L1
L3 = copy(L1) # L3 points to a new list, initialized with the same values as L1
L2[0]=-1
print(L1); print(L2); print(L3)
[-1, 2, 3]
[-1, 2, 3]
[1, 2, 3]
In [39]:
# Note that the concatenation operator creates a *new* list, so in the following L1 and L2 are separate
L1 = [1,2,3]
L2 = L1 + [4]
print(L1); print(L2)
[1, 2, 3]
[1, 2, 3, 4]
In [40]:
# Beware of the following code that creates the list [0,1,2,...,999]
# It does so very inefficiently, as a new list is created every loop iteration
L = []
for i in range(1000):
L = L + [i]
print(L)
# Instead, replace the loop body with L.append(i) or L += [i]
# This will do the same thing while only creating a single list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999]

### Part 2: The Symbolic Ring and Sage Types¶

We now see how to manipulate symbolic variables and abstract functions, including basic calculus operations and plotting, and how to determine the type and parent of an object.

In [41]:
# Before running this section, we reset all variables
reset()
In [42]:
# By default, when opening a notebook the variable "x" can be used to define a symbolic function / expression
poly = x^2 - 1
print(poly)
x^2 - 1
In [43]:
# Using any other (undeclared) variable will give an error
# This behaviour can cause frustration for first-time Sage users
poly2 = y^2 - 1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/usr/lib/python3/dist-packages/sage/all_cmdline.py in <module>
1 # Using any other (undeclared) variable will give an error
2 # This behaviour can cause frustration for first-time Sage users
----> 3 poly2 = y**Integer(2) - Integer(1)

NameError: name 'y' is not defined
In [44]:
# You can "undeclare" a variable with the restore command
restore(x)
show(x)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/usr/lib/python3/dist-packages/sage/all_cmdline.py in <module>
1 # You can "undeclare" a variable with the restore command
----> 2 restore(x)
3 show(x)

/usr/lib/python3/dist-packages/sage/misc/reset.pyx in sage.misc.reset.restore (build/cythonized/sage/misc/reset.c:2294)()
140             import sage.all
141             D = sage.all.__dict__
--> 142     _restore(G, D, vars)
143     import sage.calculus.calculus
144     _restore(sage.calculus.calculus.syms_cur, sage.calculus.calculus.syms_default, vars)

/usr/lib/python3/dist-packages/sage/misc/reset.pyx in sage.misc.reset._restore (build/cythonized/sage/misc/reset.c:2701)()
155             else:
156                 vars = vars.split()
--> 157         for k in vars:
158             if k in D:
159                 G[k] = D[k]

TypeError: 'sage.symbolic.expression.Expression' object is not iterable
In [45]:
# If the variable x is assigned a different value, this does not change the value of our symbolic expression!
# However, any new expressions containing x will use the updated value of x.
x = 2
print(poly)
poly2 = x^2 - 1
print(poly2)
x^2 - 1
3

MAKE SURE YOU UNDERSTAND THIS CRUCIAL POINT: This behaviour occurs because Sage variables (for instance, x on the left hand side of x = 2) are distinct from the underlying symbolic variables used to define symbolic expressions. By default the Sage variable x is initialized to a symbolic variable "x", and the expression poly above is defined in terms of this symbolic variable. Changing the Sage variable x to a new value does nothing to the underlying symbolic variable "x", which is why the value of poly does not change after setting x = 2.

In [46]:
# The easiest way to define a new symbolic variable having
# the same name as a Sage variable is with the "var" command
x = 2
print(x) # Prints the value of the Sage variable x
var('x') # Makes the Sage variable x point to the symbolic variable "x"
print(x) # Prints the value of the Sage variable x, which is now the symbolic variable "x"
2
x
In [47]:
# Multiple variables can be defined at the same time
var('a b c') # Initialize Sage variables a, b, and c to symbolic variables "a", "b", and "c"
poly2 = (a + b*c)^2
print(poly2)
(b*c + a)^2
In [48]:
# The commands "type" and "parent" illustrate the domains in which Sage objects live.
# Symbolic expressions, defined with symbolic variables, live in the Symbolic Ring.
# Sage automatically determines where objects defined with "=" should live.
var('a')
poly = a
print(type(poly))
print(parent(poly))
<class 'sage.symbolic.expression.Expression'>
Symbolic Ring
In [49]:
poly = 10
print(type(poly))
print(parent(poly))
print(type(1/2))
print(parent(1/2))
print(type(0.5))
print(parent(0.5))
<class 'sage.rings.integer.Integer'>
Integer Ring
<class 'sage.rings.rational.Rational'>
Rational Field
<class 'sage.rings.real_mpfr.RealLiteral'>
Real Field with 53 bits of precision
In [50]:
# In Sage (as in Python) objects can have their own functions
# Type "poly2." (without quotes) then hit the *Tab* key to see the available functions for poly2
# Run the command "poly2.subs?" to see the help page for the function poly2.subs
# Run the command "poly2.subs??" to see the source code for the function poly2.subs
var('a b c')
poly2 = (a + b*c)^2
print(poly2.subs(a=1,b=2,c=3))
print(poly2.subs)
print(parent(poly2.subs))
49
<built-in method substitute of sage.symbolic.expression.Expression object at 0x7f1f001122c0>
<class 'builtin_function_or_method'>
In [51]:
# Sage has many commands for manipulating expressions, such as simplify and expand.
# Be careful -- in the Symbolic Ring, Sage simplifies without checking restrictions on variables
var('x')
print(((x-1)*(x+1)/(x-1)).simplify())
print(simplify((x-1)*(x+1)/(x-1))) # simplify(p) is a built-in shortcut for type(p).simplify()
x + 1
x + 1
In [52]:
# Expanding an expression
print(expand((x-1)*(x+1)))
x^2 - 1
In [53]:
# Factoring an expression
pol = x^2-1
print(pol.factor())
(x + 1)*(x - 1)
In [54]:
# Factoring a larger expression
f = x^23-x^16-2*x^13+3*x^20-2*x^10+2*x^11-2*x^4+2*x+5*x^3-5
show(f)
show(f.factor())
In [55]:
# Equations are also symbolic expressions, defined using "=="
eq1 = (x^3 == 1)
print(eq1)
print(eq1.lhs())
print(eq1.rhs())
x^3 == 1
x^3
1
In [56]:
# The solve command works with equations
show(solve(eq1, x))
In [57]:
# Symbolic functions can be defined with symbolic variables
f = sin(x)+2*cos(x)
show(f)
In [58]:
# You can also define f in a "callable" format
f(x) = sin(x)+2*cos(x)

This format allows you to specify the order of the arguments if you want to call a multivariate function, e.g., F(x, y, z) = sin(x) + 2*cos(y) + 3*z.

In [59]:
# The find_root command can be used to approximate roots numerically
# (additional details on finding roots of polynomials are given in the next section)
f(x).find_root(-10, 10)
Out[59]:
8.31762924297529
In [60]:
# Symbolic functions can be plotted with the plot command
plot(f(x),x,0,10) # Syntax is "plot(function, variable, xmin value, xmax value)"
Out[60]:
In [61]:
# Plots can be "added" to overlap -- run "plot?" or "help(plot)" for plotting options
p1 = plot(sin(x),x,0,pi)
p2 = plot(cos(x),x,0,pi,color="red")
p1+p2
Out[61]:
In [62]:
# Common plot options include
# plot_points (default 200)
# xmin and xmax
# color
# detect_poles (vertical asymptotes)
# alpha (line transparency)
# thickness (line thickness)
# linestype (dotted with ':', dashdot with '-.', solid with '-')
# Use commands list p.set_aspect_ratio, etc.

pp = plot([]) # Define empty plot
cols = rainbow(20) # Define 20 evenly spaced colors
for k in range(20):
pp = pp + plot(log(x+k),1,10,color=cols[k],thickness=2)

pp # Print superimposed graphs
Out[62]:
In [63]:
# 3d plots are similar (user may need to load the 3D viewer after running this code)
var('x y')
f(x,y) = x^2 + sin(x)*cos(y)
plot3d(f, (x,-1,1), (y,-1,1))
Out[63]:
In [64]:
# The series command computes power series of symbolic expressions representing functions
show(log(1/(1-x)).series(x,10))
In [65]:
# The series command can also compute Laurent series
show(tan(x).series(x==pi/2,10))

Some methods available to symbolic expressions may not be available for symbolic series as they are of the type "symbolic series" rather than "symbolic expressions".

In [66]:
# To go from a series expression to the polynomial defined by its terms, use the truncate command
show(arctan(x).series(x,10))
show(arctan(x).series(x,10).truncate())

Sage can also compute derivates, integrals, and limits from Calculus such as:

$$\renewcommand{\d}{\mathrm{d}}\frac{\d}{\d x}\sin x \qquad \int \sin(x) \cos(x) \,\d x \qquad \int_{-\infty}^\infty e^{-x^2}\,\d x \qquad \lim_{x\to0}\frac{\sin x}{x}$$
In [67]:
# The diff/differentiate command computes derivatives
# The integral/integrate command is similar
show(diff(sin(x),x))
show(integrate(sin(x)*cos(x),x))
show(integrate(exp(-x^2),x,-infinity,infinity))
show(limit(sin(x)/x,x=0))
In [68]:
# This also works with abstract symbolic functions
var('x y')
function('f')(x)
show(diff(sin(f(x)),x,x))
function('g')(x,y)
show(diff(g(sin(x),f(x)),x))
In [69]:
# Here we set up and solve a differential equation
x = var('x')
y = function('y')(x)
show(desolve(y*diff(y,x) == x, y))

Sage can even find closed-form expressions of some interesting sums such as these:

$$\sum_{k=0}^n a^k \qquad \sum_{k=0}^n \binom{n}{k} \qquad \sum_{n=1}^\infty \frac{1}{n^2}$$
In [70]:
# Sage can calculate some symbolic sums
var('a k n')
show(sum(a^k,k,0,n))
show(sum(binomial(n,k), k, 0, n))
show(sum(1/n^2, n, 1, infinity))
In [71]:
# You can use the assume to command to put restrictions on variables
# This can be useful for infinite series
# Just running sum(a^k,k,0,infinity) throws a "ValueError" -- need to *assume* |a|<1
assume(abs(a)<1)
show(sum(a^k,k,0,infinity))
In [72]:
# Assumptions stay with variables until cleared using forget
# Run this cell directly after the previous cell
print(bool(a<1)) # Test if a < 1, under assumption abs(a) < 1
forget(abs(a)<1)
print(bool(a<1)) # Test if a < 1, under no assumptions
True
False
In [ ]:
################################################
# EXERCISE: Make a function to compute the nth Fibonacci number (defined by fib(n+2) = fib(n+1) + fib(n),
# fib(0) = 0, and fib(1) = 1). What is the highest number you can compute in 5 seconds?
#
# Adding the line "@cached_function" directly before the function definition tells Sage to store the
# result of each function return, which will speed up the computation. Add this line then see how high
# you can go in 5 seconds.
################################################
In [ ]:
################################################
# EXERCISE: Compute the sum of the first 100 positive perfect squares.
################################################
In [ ]:
################################################
# EXERCISE: Create a list containing the first 100 primes of the form 4*k+1
################################################
In [ ]:
################################################
# EXERCISE: Guess the result of uncommenting and running the following code.
# Explain the output that does occur.
################################################
# var('p q r'); r = q; q = p; p = r
# print(p); print(q); print(r)
In [ ]:
################################################
# EXERCISE: Uncomment and hit <Tab> with the cursor on the far right of the following line see the
# available functions for poly2 which begin with "s". Select one of the functions, look up its
# documentation, then run the function (with appropriate arguments if necessary)
################################################
# poly2.s