{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Sage Introduction\n",
"\n",
"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**](https://doc.sagemath.org/html/en/tutorial/index.html), and the (highly recommended) open textbook [**Computational Mathematics with SageMath**](http://sagebook.gforge.inria.fr/english.html).\n",
"\n",
"Sage is free and open source. Information on running a local installation can be found on the [**Sage installation guide**](https://doc.sagemath.org/html/en/installation/index.html). Alternatively, Sage can be run \"in the cloud\" by making a (free) account on the [**CoCalc website**](https://cocalc.com/) or by uploading a Jupyter notebook to a public git repository and using [**mybinder.org**](https://mybinder.org).\n",
"\n",
"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.\n",
"\n",
"**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.\n",
"\n",
"This introduction is based off of a worksheet originally written by [Steven Melczer](https://melczer.ca/)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 1: The Basics of Sage\n",
"\n",
"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)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Any text on a line after a '#' symbol is considered a comment, and is not evaluated by Sage\n",
"# Sage can be used as a calculator using usual math notation \n",
"# (recall you need to click on a cell and hit Shift + Enter to evaluate it)\n",
"1 + 3*4"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Code in a Sage cell should be entered in sequence, with one \"instruction\" per line\n",
"# (multiple instructions can be put on the same line using a semicolon -- see examples below)\n",
"# The result of previous executions of Sage cells (both the current cell and other cells) is stored by Sage\n",
"# All (non-commented) code is executed, however only the output of the final line is printed by default\n",
"1 + 2\n",
"2 ^ 3"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Variables are defined using the \"=\" operator\n",
"# Note that some operations (such as variable assignment) do not have an output\n",
"# So we add another line to print the value of our variable\n",
"mult = 11 * 12\n",
"mult"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# randint(a, b) returns a random integer between a and b inclusive\n",
"A = randint(0, 10^9)\n",
"B = randint(0, 10^9)\n",
"A+B"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Sage can compute with large integers\n",
"A*B"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Even very large integers can be computed exactly\n",
"A^100"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# To print other lines, use the print command\n",
"print(2^3) # This is an integer\n",
"print(3/9) # This is an exact rational number\n",
"print(3.0/9.0) # This is a floating point number\n",
"print(11 % 3) # This is 11 mod 3"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Multiple instructions can be put on the same line using a semicolon\n",
"# Again, only the output of the final line is displayed by default\n",
"2+2; print(1+2); 3*5"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The \"show\" command outputs a latex-like pretty output\n",
"# Sage knows common math constants such as pi (lower case), e, and I (or the alternative i)\n",
"# Most common mathematical functions are supported by default\n",
"show(5/10 + 1/pi)\n",
"show(sin(pi/3))\n",
"show(log(2))\n",
"show(log(2).n(1000)) # Adding \".n()\" gives a numerical approximation (can use \".n(k)\" to get k bits)\n",
"show(exp(i*2*pi/3))\n",
"show(exp(I*2*pi/101))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Sage computes with *exact* rational numbers\n",
"# For example, the following computes the sum of 1 + 1/2 + ... + 1/100\n",
"show(add(1/n for n in (1..100)))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Sage also has support for matrices and vectors\n",
"A = random_matrix(ZZ, 5)\n",
"b = random_vector(ZZ, 5)\n",
"show(A)\n",
"show(b)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Sage can solve the linear system Ax = b for x using the solve_right method of matrices\n",
"# (named because x appears to the right of A in the system to solve)\n",
"show(A.solve_right(b))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# There are many useful built-in functions on matrices (e.g., to compute the determinant)\n",
"A.determinant()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Sage can even deal with matrices with symbolic entries\n",
"B = Matrix(SR, A)\n",
"B[4,4] = x\n",
"show(B)\n",
"show(B.solve_right(b))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Mathematical objects and variables can be inserted in print commands using commas, \n",
"# or using empty curly braces {} and .format(math1,math2,...)\n",
"print(\"The area of a circle of radius 1 is approximately\", pi.n())\n",
"print(\"The square-root of {} is approximately {}\".format(log(2), sqrt(log(2)).n()))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# To access the help page for a function, type the name of the function and then add a question mark\n",
"# For instance, evaluating the expression \"sin?\" (without quotes) gives the help page for sine\n",
"# THIS WILL OPEN A NEW WINDOW AREA\n",
"# Using two question marks (e.g. \"sin??\") shows the source code of the function\n",
"# (Note that for many low level functions like sin Sage relies on outside packages \n",
"# and the source code is not very informative)\n",
"\n",
"# Similar information is provided by the \"help\" command, which prints below the current cell\n",
"print?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The values \"_\", \"__\", and \"___\" (using one, two, and three underscores) \n",
"# are the last three output values. Printing displays content but does *not* \n",
"# return a value, so a block ending with a print statement has no output\n",
"print(_)\n",
"print(__)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The output of previous cells can be directly accessed using the syntax Out[k]\n",
"# NOTE: cells are numbered by execution order -- running cells repeatedly or in \n",
"# different orders will change their numbering!\n",
"Out[13]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Sage is built on Python, and uses much of the same syntax. \n",
"# In particular, indentation is extremely important.\n",
"# If statements are defined with indentation\n",
"a = 2\n",
"\n",
"if a<0:\n",
" print(\"Negative\")\n",
"elif a==0:\n",
" print(\"Zero\")\n",
"else:\n",
" print(\"Positive\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# In addition, an if statement can be written in one line\n",
"a = 2\n",
"if a>0: print(\"Positive\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Functions are also defined with indentation\n",
"def fact(n):\n",
" if n==0:\n",
" return 1\n",
" else:\n",
" return n*fact(n-1)\n",
"\n",
"print(fact(4))\n",
"print(fact(10))\n",
"print(fact) # Prints reference to the function"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# running this code displays the source code for the function fact\n",
"fact??"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Lists in Sage are defined with square brackets\n",
"LST = [1,2,3,4]\n",
"\n",
"print(LST)\n",
"print(len(LST)) # Print the length of the list\n",
"print(LST[0]) # Access elements from the left (starting at index 0)\n",
"print(LST[1]) # Print second element of the list\n",
"print(LST[-2]) # Negative indices access elements from the right\n",
"print(LST[1:3]) # Define sublist\n",
"print(LST[1:-1]) # Define sublist using negative index\n",
"print(LST[1:]) # Define sublist from a fixed index to end of list"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Lists can be concatenated with '+'\n",
"# Strings can be concatenated similarly (they are lists of characters)\n",
"print([1,2,3] + [\"a\",\"b\",\"c\"])\n",
"print(\"hello\" + \" \" + \"world\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# For loops work over lists or generators, and are indented similarly to if statements and functions\n",
"LST = [0,1,2,3,4,5]\n",
"for k in LST:\n",
" print(k^2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The notation a..b can be used to build the list of numbers between integers a and b\n",
"for k in (0..6):\n",
" print(k^2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# As in Python, Sage contains the function range(k), which encodes the numbers 0,1,...,k-1\n",
"# In Sage versions 8.x and lower, which rely on Python 2, range(k) returns the list [0,1,...,k-1]\n",
"# In Sage 9.0 and higher, which use Python 3, range(k) returns an *iterator* that can be converted to a list\n",
"# (think of an iterator as a method to construct elements of a list, one by one, which can be more efficient)\n",
"# We assume in our discussions that the user of this document is using Sage 9.0 or higher\n",
"# 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\n",
"\n",
"print(range(5)) # printing an iterator just returns the iterator\n",
"print(list(range(5))) # the iterator can be converted to a regular list\n",
"for k in range(5): # loops can range directly over iterators, which can be more efficient\n",
" print(k^2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# For loops can also be defined over one line\n",
"for k in range(5): print(k^2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# There is a powerful alternate syntax for building lists using a \n",
"# function f(x) on the elements of a list LST: [f(k) for k in LST]\n",
"print([k^2 for k in range(5)])\n",
"print([cos(k*pi) for k in [1..5]])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# While loops are defined similarly to for loops\n",
"k = 0\n",
"while k<5:\n",
" print(k^2)\n",
" k = k+1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# While loops can be broken using 'break'\n",
"k = 0\n",
"while True:\n",
" if k>= 5:\n",
" break\n",
" print(k^2)\n",
" k = k+1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The map operator applies a function to each element of a list \n",
"# Similar to range, in Sage 9.0+ map returns a \"map object\" / iterator\n",
"# The list command can be used to obtain an honest list from a map object\n",
"list(map(abs,[-1,2,-3,4]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# User defined functions can also be mapped, where appropriate\n",
"def double(k):\n",
" return 2*k\n",
"\n",
"list(map(double,[-1,2,-3,4]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Can also use map with 'lambda expressions' to define a function in place\n",
"print(list(map(lambda t: t*2, [-1,2,-3,4])))\n",
"print(lambda t: t^2) # Defines the function f(x) = x^2 in place"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Can filter a list using 'filter'\n",
"# Similar to range and map, in Sage 9.0+ filter returns a \"filter object\" / iterator\n",
"# The list function can be applied to obtain an honest list from a filter object\n",
"\n",
"print(list(filter(lambda t: t>0, [-1,2,-3,4])))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Can also use the list 'comprehension form' to filter elements when building a list\n",
"[p^2 for p in [1..10] if is_prime(p)]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Can sort lists, when appropriate.\n",
"# Sort is a function of a list (see Part 2 below for additional details)\n",
"L = [1,4,3,2,7,6]\n",
"L.sort() # Modifies the list L in place\n",
"print(L)\n",
"L = [\"a\",\"acb\",\"abc\",\"ab\"]\n",
"L.sort() # Sort in lexicographical order\n",
"print(L)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Lists are stored by reference. Simply writing L2 = L1, makes L1 and L2 point to the *same* list\n",
"# Use L2 = copy(L1) to make an independent copy\n",
"# Note copy only works at one level of lists \n",
"# (use the \"deepcopy\" command to copy a list of lists, and make everything independent)\n",
"\n",
"L1 = [1,2,3]\n",
"L2 = L1 # L2 points to the same list as L1\n",
"L3 = copy(L1) # L3 points to a new list, initialized with the same values as L1\n",
"L2[0]=-1\n",
"print(L1); print(L2); print(L3)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Note that the concatenation operator creates a *new* list, so in the following L1 and L2 are separate\n",
"L1 = [1,2,3]\n",
"L2 = L1 + [4]\n",
"print(L1); print(L2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Beware of the following code that creates the list [0,1,2,...,999]\n",
"# It does so very inefficiently, as a new list is created every loop iteration\n",
"L = []\n",
"for i in range(1000):\n",
" L = L + [i]\n",
"print(L)\n",
"# Instead, replace the loop body with L.append(i) or L += [i]\n",
"# This will do the same thing while only creating a single list"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 2: The Symbolic Ring and Sage Types\n",
"\n",
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Before running this section, we reset all variables\n",
"reset()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# By default, when opening a notebook the variable \"x\" can be used to define a symbolic function / expression\n",
"poly = x^2 - 1\n",
"print(poly)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Using any other (undeclared) variable will give an error\n",
"# This behaviour can cause frustration for first-time Sage users\n",
"poly2 = y^2 - 1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# You can \"undeclare\" a variable with the restore command\n",
"restore(x)\n",
"show(x)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# If the variable x is assigned a different value, this does not change the value of our symbolic expression!\n",
"# However, any new expressions containing x will use the updated value of x.\n",
"x = 2\n",
"print(poly)\n",
"poly2 = x^2 - 1\n",
"print(poly2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**MAKE SURE YOU UNDERSTAND THIS CRUCIAL POINT: \n",
"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.**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The easiest way to define a new symbolic variable having\n",
"# the same name as a Sage variable is with the \"var\" command\n",
"x = 2\n",
"print(x) # Prints the value of the Sage variable x\n",
"var('x') # Makes the Sage variable x point to the symbolic variable \"x\"\n",
"print(x) # Prints the value of the Sage variable x, which is now the symbolic variable \"x\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Multiple variables can be defined at the same time\n",
"var('a b c') # Initialize Sage variables a, b, and c to symbolic variables \"a\", \"b\", and \"c\"\n",
"poly2 = (a + b*c)^2\n",
"print(poly2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The commands \"type\" and \"parent\" illustrate the domains in which Sage objects live.\n",
"# Symbolic expressions, defined with symbolic variables, live in the Symbolic Ring.\n",
"# Sage automatically determines where objects defined with \"=\" should live.\n",
"var('a')\n",
"poly = a\n",
"print(type(poly))\n",
"print(parent(poly))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Some additional examples\n",
"poly = 10\n",
"print(type(poly))\n",
"print(parent(poly))\n",
"print(type(1/2))\n",
"print(parent(1/2))\n",
"print(type(0.5))\n",
"print(parent(0.5))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# In Sage (as in Python) objects can have their own functions\n",
"# Type \"poly2.\" (without quotes) then hit the *Tab* key to see the available functions for poly2\n",
"# Run the command \"poly2.subs?\" to see the help page for the function poly2.subs\n",
"# Run the command \"poly2.subs??\" to see the source code for the function poly2.subs\n",
"var('a b c')\n",
"poly2 = (a + b*c)^2\n",
"print(poly2.subs(a=1,b=2,c=3))\n",
"print(poly2.subs)\n",
"print(parent(poly2.subs))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Sage has many commands for manipulating expressions, such as simplify and expand.\n",
"# Be careful -- in the Symbolic Ring, Sage simplifies without checking restrictions on variables\n",
"var('x')\n",
"print(((x-1)*(x+1)/(x-1)).simplify())\n",
"print(simplify((x-1)*(x+1)/(x-1))) # simplify(p) is a built-in shortcut for type(p).simplify()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Expanding an expression\n",
"print(expand((x-1)*(x+1)))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Factoring an expression\n",
"pol = x^2-1\n",
"print(pol.factor())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Factoring a larger expression\n",
"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\n",
"show(f)\n",
"show(f.factor())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Equations are also symbolic expressions, defined using \"==\"\n",
"eq1 = (x^3 == 1)\n",
"print(eq1)\n",
"print(eq1.lhs())\n",
"print(eq1.rhs())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The solve command works with equations\n",
"show(solve(eq1, x))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Symbolic functions can be defined with symbolic variables\n",
"f = sin(x)+2*cos(x)\n",
"show(f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# You can also define f in a \"callable\" format\n",
"f(x) = sin(x)+2*cos(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The find_root command can be used to approximate roots numerically\n",
"# (additional details on finding roots of polynomials are given in the next section)\n",
"f(x).find_root(-10, 10)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Symbolic functions can be plotted with the plot command\n",
"plot(f(x),x,0,10) # Syntax is \"plot(function, variable, xmin value, xmax value)\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Plots can be \"added\" to overlap -- run \"plot?\" or \"help(plot)\" for plotting options\n",
"p1 = plot(sin(x),x,0,pi)\n",
"p2 = plot(cos(x),x,0,pi,color=\"red\")\n",
"p1+p2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Common plot options include\n",
"# plot_points (default 200)\n",
"# xmin and xmax\n",
"# color\n",
"# detect_poles (vertical asymptotes)\n",
"# alpha (line transparency)\n",
"# thickness (line thickness)\n",
"# linestype (dotted with ':', dashdot with '-.', solid with '-')\n",
"# Use commands list p.set_aspect_ratio, etc.\n",
"\n",
"pp = plot([]) # Define empty plot\n",
"cols = rainbow(20) # Define 20 evenly spaced colors\n",
"for k in range(20):\n",
" pp = pp + plot(log(x+k),1,10,color=cols[k],thickness=2)\n",
"\n",
"pp # Print superimposed graphs"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 3d plots are similar (user may need to load the 3D viewer after running this code)\n",
"var('x y')\n",
"f(x,y) = x^2 + sin(x)*cos(y)\n",
"plot3d(f, (x,-1,1), (y,-1,1))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The series command computes power series of symbolic expressions representing functions\n",
"show(log(1/(1-x)).series(x,10))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The series command can also compute Laurent series\n",
"show(tan(x).series(x==pi/2,10))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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\"."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# To go from a series expression to the polynomial defined by its terms, use the truncate command\n",
"show(arctan(x).series(x,10))\n",
"show(arctan(x).series(x,10).truncate())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Sage can also compute derivates, integrals, and limits from Calculus such as:\n",
"\n",
"$$ \\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} $$"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The diff/differentiate command computes derivatives\n",
"# The integral/integrate command is similar\n",
"show(diff(sin(x),x))\n",
"show(integrate(sin(x)*cos(x),x))\n",
"show(integrate(exp(-x^2),x,-infinity,infinity))\n",
"show(limit(sin(x)/x,x=0))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# This also works with abstract symbolic functions\n",
"var('x y')\n",
"function('f')(x)\n",
"show(diff(sin(f(x)),x,x))\n",
"function('g')(x,y)\n",
"show(diff(g(sin(x),f(x)),x))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Here we set up and solve a differential equation\n",
"x = var('x')\n",
"y = function('y')(x)\n",
"show(desolve(y*diff(y,x) == x, y))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Sage can even find closed-form expressions of some interesting sums such as these:\n",
"\n",
"$$ \\sum_{k=0}^n a^k \\qquad \\sum_{k=0}^n \\binom{n}{k} \\qquad \\sum_{n=1}^\\infty \\frac{1}{n^2} $$"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Sage can calculate some symbolic sums\n",
"var('a k n')\n",
"show(sum(a^k,k,0,n))\n",
"show(sum(binomial(n,k), k, 0, n))\n",
"show(sum(1/n^2, n, 1, infinity))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# You can use the assume to command to put restrictions on variables\n",
"# This can be useful for infinite series\n",
"# Just running sum(a^k,k,0,infinity) throws a \"ValueError\" -- need to *assume* |a|<1\n",
"assume(abs(a)<1)\n",
"show(sum(a^k,k,0,infinity))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Assumptions stay with variables until cleared using forget\n",
"# Run this cell directly after the previous cell\n",
"print(bool(a<1)) # Test if a < 1, under assumption abs(a) < 1\n",
"forget(abs(a)<1)\n",
"print(bool(a<1)) # Test if a < 1, under no assumptions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"################################################\n",
"# EXERCISE: Make a function to compute the nth Fibonacci number (defined by fib(n+2) = fib(n+1) + fib(n),\n",
"# fib(0) = 0, and fib(1) = 1). What is the highest number you can compute in 5 seconds?\n",
"#\n",
"# Adding the line \"@cached_function\" directly before the function definition tells Sage to store the \n",
"# result of each function return, which will speed up the computation. Add this line then see how high\n",
"# you can go in 5 seconds.\n",
"################################################\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"################################################\n",
"# EXERCISE: Compute the sum of the first 100 positive perfect squares. \n",
"# (Use the add function -- type \"add?\" or \"help(add)\" for its documentation)\n",
"################################################\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"################################################\n",
"# EXERCISE: Create a list containing the first 100 primes of the form 4*k+1\n",
"################################################\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"################################################\n",
"# EXERCISE: Guess the result of uncommenting and running the following code.\n",
"# Explain the output that does occur.\n",
"################################################\n",
"# var('p q r'); r = q; q = p; p = r\n",
"# print(p); print(q); print(r)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"################################################\n",
"# EXERCISE: Uncomment and hit with the cursor on the far right of the following line see the\n",
"# available functions for poly2 which begin with \"s\". Select one of the functions, look up its\n",
"# documentation, then run the function (with appropriate arguments if necessary)\n",
"################################################\n",
"# poly2.s"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "SageMath 9.5",
"language": "sage",
"name": "sagemath"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.4"
},
"latex_envs": {
"LaTeX_envs_menu_present": true,
"autoclose": false,
"autocomplete": true,
"bibliofile": "biblio.bib",
"cite_by": "apalike",
"current_citInitial": 1,
"eqLabelWithNumbers": true,
"eqNumInitial": 1,
"hotkeys": {
"equation": "Ctrl-E",
"itemize": "Ctrl-I"
},
"labels_anchors": false,
"latex_user_defs": false,
"report_style_numbering": false,
"user_envs_cfg": false
},
"latex_metadata": {
"author": "Curtis Bright",
"date": "September 12, 2022",
"title": "Computational Mathematics: Handout 01"
}
},
"nbformat": 4,
"nbformat_minor": 4
}