-
Notifications
You must be signed in to change notification settings - Fork 217
MathematicalSyntaxErrors
This page is for help with the mathematical syntax used in Sage generally, and in particular inside SageMathCloud. There is a highly related page for working with and editing SageMathCloud worksheets, including help with the user-interface.
The Good News: The twenty errors described here are easily responsible for over 95% of mistakes that I see students making in mid-level undergraduate math courses. (e.g. integral calculus, multivariable calculus, differential equations, matrix algebra, discrete math, ...) In fact, the first five errors might be responsible for 80% just by themselves.
Remember: if you don't find what you need, or if you'd like to ask a question, then please email [email protected] at any time. We'd love to hear from you! Please include a link (the address in your browser) to any relevant project or document.
Context: A worksheet is a file ending in .sagews
and is subdivided into cells. Each cell has an input region and an output region, which might be 0, 1, 2, or many lines long. The input can be mathematical, in the Sage syntax, or it could be in many other formats, including markdown
, html
, R, and so forth. This page deals with Sage, and not those other languages.
Citation: By the way, much of this information has been taken from Sage for Undergraduates, a book written by Gregory V. Bard and published by The American Mathematical Society in 2015. (The pdf-file of that book is available for free, and the print version has an extremely low price.) This file is largely based on Appendix A: "What to do When Frustrated!" of that book.
This particular case is best explained with an example:
solve( x^3 - 5x^2 + 6x == 0, x )
<--- Wrong!
is not correct. You must type instead
solve( x^3 - 5*x^2 + 6*x == 0, x )
In other words, Sage needs that asterisk or multiplication symbol between the coefficients 5 and 6, and the terms to which they are attached: namely
f(x) = 5cos( 6x )
<--- Wrong!
but will accept
f(x) = 5*cos( 6*x )
Another common manifestation is
f(x) = x(x+1)
<--- Wrong!
but instead it should be
f(x) = x*(x+1)
In defense of Sage, it should be noted that Java, C, C++, Python, FORTRAN, Pascal, BASIC, and many other computer languages have this same rule. However, for those users who find this extremely frustrating, there is a way out of this requirement. If you place the following line
implicit_multiplication(True)
at the start of a SageMathCloud session, then you will be in "implicit multiplication mode."
Consider the following code:
implicit_multiplication(True)
g=(12+3x)/(-12+2x)
plot( g, 2, 8, ymin=-30, ymax=30 )
Note that the definition of
Note about SageMathCell: At this particular moment (July 6th, 2016) the implicit_multiplication
trick will work in SageMathCloud, but not in SageMathCell.
The declaration of variables can be something confusing to those who have not done a lot of programming in the years prior to learning Sage. In languages such as C, C++, and Java, all the variables must be declared---no exceptions. In Sage, the variable
Let's say that I want to graph a sphere,
$ x^2 + y^2 + z^2 = r^2 $
for the value var("y z")
very early in my code, perhaps at the first or second line.
The r=5
then Sage will understand that var("r")
is not needed.
The variable var("x")
in my code.
var("y z")
r=5
implicit_plot3d( x^2 + y^2 + z^2 == r^2, (x,-r,r), (y,-r,r), (z,-r,r) )
For stylistic reasons, some users like to declare var("x y z")
in place of var("y z")
because there is no impact in Sage to the redundant declaration of
Similar to the previous section, for users who find declaring variables to be frustrating, there is a way out of the requirement. At the start of a SageMathCloud session or a Sage Cell Server window, typing
automatic_names(True)
will result in variables no longer needing to be declared. I do not recommend this, because it is a very bad programming habit, and will disadvantage the student when learning other programming languages.
Also, functions (e.g.
var("t")
g = 9.82
f1(t) = 3 - 5*t
f2(t) = 4 + 5*t
f3(t) = 7 + 0.5*g*t^2
plot( [ f1(t), f2(t), f3(t) ], (t, 0, 2), gridlines="minor" )
We have to declare
In almost all cases, when something incorrect is inputted into Sage, an extremely long error message appears. This many-lined report can be extremely intimidating, and even moderately experienced Sage users might not know what to make of it.
This is actually called a "stack trace" and it is very useful to experienced programmers, who can use it to locate a bug very rapidly. However (for new users) it can be very intimidating. The key is to realize that the last line of the error message is usually the most useful.
Whenever you have a huge error message, start with the very last line. That's often all you need. Alternatively, some of my students find it easier to ignore the error message entirely, read their own code, and figure out what is wrong themselves.
Matching parentheses can be tricky, and therefore some users can get frustrated by mismatched parentheses. Luckily, Sage has two great features to help you with this commonly performed task.
This feature is better demonstrated by an example. With cut-and-paste, put the following code into a cell of a SageMathCloud worksheet.
f(x) = 1/(1 + 1/(3 + 1/(5 + 1/(7 + 1/(1 + 1/(3 + 1/(5 + 1/(7 + x))))))))
plot( f(x), -5, 5 )
Now click on f(x), and scroll with the arrow keys along that long expresion. What you'll see is that the parentheses will turn green as you pass over them. Now, if you look carefully at the right of the expression, whenever you pass over a "$(
While the previous example was a bit contrived, a real-world example is the following function, which represents the future value (after
v(t) = 1000*((1+0.005)^(12*t)-1)/0.005
As you can see, there are six parentheses (three left and three right), and indeed, it can be tricky to get their placement exactly right.
Sometimes, after entering a function, it can be a great help to use the show(f(x))
command to see if you've got it right or not. For example,
f(x) = 1/(1 + 1/(3 + 1/(5 + 1/(7 + 1/(1 + 1/(3 + 1/(5 + 1/(7 + x))))))))
show(f(x))
produces the lovely (and correct) image below:
The comma is a very important symbol in most computer languages, including Python, on which Sage is based. That's why we do not use commas inside of large numbers when programming in almost any computer language.
As an example, the correct syntax for solving
is to type
var("x y")
solve( [59*x + 79*y == 572, x + y == 8] , [x,y] )
and press shift+enter.
However, the highly related problem $$\begin{array}{rcl} 59x + 79y & = & 28,233 \ x + y & = & 387 \ \end{array}$$
is not solved by typing
var("x y")
solve( [59*x + 79*y == 28,233, x + y == 387 ] , [x,y] )
but instead, you should remove the comma from inside the 28,233. In other words, you should type instead
var("x y")
solve( [59*x + 79*y == 28233, x + y == 387 ] , [x,y] )
This is even more important for very large numbers, like 7,255,881. We really want to have those two interior commas in a number that large, when we write text such as in an email or on MathExchange. However, while programming, we do not use the interior commas.
Instead, you should type
var("x y")
solve( [15163*x + 20303*y == 7255881, 257*x + 257*y == 99459 ] , [x,y] )
which correctly computes the answer
When using Sage, we should be very careful not to capitalize the built-in functions. For example, the following code is correct:
print sin(pi/4)
print ln(e^3)
print sqrt(60)
print arctan(1)
While the following code is incorrect, because the initial letters of the built-in functions have been (illegally) capitlized.
print Sin(pi/4)
print Ln(e^3)
print Sqrt(60)
print Arctan(1)
By the way, if you look in most calculus textbooks, you will see that it is a long-standing tradition not to capitalize those initial letters.
While we're talking about the built-in functions, it might be nice to clarify an issue about log and ln. In higher mathematics, the useful logarithm is almost always the natural logarithm, not the common logarithm or the binary logarithm. For this reason, higher mathematics textbooks, such as those used in the university curriculum after the midpoint of a math degree, use log(x)
to mean the natural logarithm of
Yet, high-school mathematics textbooks, and many textbooks used in freshman calculus or precalculus, use the following notation:
-
ln(x)
is the natural logarithm of$x$ . (In other words, base$e$ .) -
ld(x)
is the binary logarithm of$x$ . (In other words, base$2$ .) -
log(x)
is the common logarithm of$x$ . (In other words, base$10$ .) - It should be noted that the last one is very popular in both chemistry and geology. For example, pH uses the common logarithm, as does the Richter scale for earthquakes.
In any case, to be compatible with higher mathematics textbooks, Sage uses log(x)
internally to mean the natural logarithm of
Yet, if you type ln(x)
, Sage will understand and allow it. This leads to an odd situation. If you type ln(17)
then Sage will respond log(17)
, and that can be rather confusing to a precalculus student.
When programming, it is very easy to get the parameters in the wrong order.
Consider the following example. Let's suppose that I'm asked to find the 4th-degree Taylor approximation to the function
Therefore, I type taylor( sqrt(x), x, 4, 9 )
and I get back something very strange. The response is
715/8589934592*(x - 4)^9 - 429/1073741824*(x - 4)^8 + 33/16777216*(x - 4)^7 - 21/2097152*(x - 4)^6 + 7/131072*(x - 4)^5 - 5/16384*(x - 4)^4 + 1/512*(x - 4)^3 - 1/64*(x - 4)^2 + 1/4*x + 1
which is weird because I am expecting a 4th-degree polynomial, and I have a 9th-degree polynomial instead. Moreover, the repeated appearance of
I should have typed instead taylor( sqrt(x), x, 9, 4 )
to do that. I get the much more reasonable answer of
-5/279936*(x - 9)^4 + 1/3888*(x - 9)^3 - 1/216*(x - 9)^2 + 1/6*x + 3/2
which is a polynomial of the fourth degree. Because I see repeated uses of
This whole episode shows you that the order of parameters matters a lot. Moreover, if you do exchange two parameters, then you might be asking for something valid, but very different from your intension.
The best way to painlessly avoid this problem is to type taylor?
which will bring up a help window about the taylor command. You can glue a question mark to the end of any command, and Sage will bring up the help window for you.
Few things can be more frustrating than a computer program which has become unresponsive, especially if you're working on something important. Sometimes, if working in a coffee-shop or a hotel, your wifi access will expire. This cuts off your internet connection, and severs the link between your computer and SageMathCloud.
SageMathCloud has a very handy feature. If you look in the upper-right corner of your web-browser window, you'll see a wifi-symbol, followed by a number, the unit "milliseconds" (abbreviated as "ms") and then a pair of diagonal arrows point at each other. Here's an example:
That means I have a good connection, and the latency is 66 milliseconds. In other words, a packet leaving SageMathCloud will arrive at my computer about 0.066 sec after it was sent. Alternatively, if my internet connection were to go down suddenly, I'd see something that looks like this:
and that's how I know that my internet connection has gone down. So if a command that normally works stops working, be sure and glance up and see---perhaps you've lost your internet connection!
Let's say that I want to make a nice 3D plot of some algebraic surface which is defined implicitly. Yet, perhaps I have forgotten... is the command implicit_plot3D
? implicitplot3D
? implicitplot3d
? implicit_plot3d
? or implicitPlot3D
?
What I should do, in a SageMathCell, is type imp
and then hit the tab button. After a few moments, a handy pull-down list appears with the five commands that begin with the letters "imp."
Sometimes, a command is a method of some object. For example, look at the following code.
A = matrix( 3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(A)
A.rref()
The rref
command "belongs" to A
, because this command is only for matrices, and A
is a matrix. (The way to say this in computer science is "rref
is a method of the object A
, which has class matrix
.")
What if I forget that the command is rref
? If you type the first two lines of the previous code block, and then type (on the third line) type only A.r
followed by the tab button, then you get a rather long list of commands which would be suitable for that situation. Of course, rref
is among them.
blah: find out about search_doc
and if it should be included here
The letter e
in Sage usually refers to 2.718281828... just like in calculus and related courses. However, it sometimes indicates scientific notation.
For example, if you type 10^19.39
into Sage, then the reply will be 2.45470891568503e19
.
Now, if you want to multiply this answer by 2, ...
-
You should type
2*2.45470891568503e19
-
You should not type
2*2.45470891568503*e19
becausee19
looks like a variable name. -
You should definitely not type
2*2.45470891568503*e^19
because$e$ is being interpreted as 2.718281828 when it appears alone. (Contrastingly, whene
appears in the middle of a number, then it is interpreted as scientific notation.) -
However, you can type instead
2*2.45470891568503*10^19
which is fine. This is probably preferred, because it is more human readable. -
When looking at a number, the human reflex is to look at the left-most part, because those are the most significant figures. The right-most part, ordinarily, refers to precision that you don't usually need. For example, typing
N(sqrt(2))
yields1.41421356237310
. Honestly, the237310
at the end is a level of precision not really required by most applications. -
In stark contrast to this, the numbers
6.02e23
and6.02e-23
are very, very different numbers. It is important to understand that while6.02
and6
are "almost the same number" in a certain sense,6.02e23
and6.02
are not "almost the same number" at all. It is crucial to understand that6.02e23
and6.02e-23
are not "almost the same thing." -
You might imagine that very few people might make the mistake which I describe in the previous bullet, but that's not true in practice. The next entry is a true story.
Sometimes, when working with matrix algebra (linear algebra), we might want to perform a check on our computation. We might multiply back two inputs and expect to see an identity matrix.
If you don't know what "the identity matrix is," basically it is a square grid of numbers that has exactly the following pattern, but it can be of different sizes. (Here is a
Once, in the third column of a 1.4572234780951267e-14
. Did this mean our calculation was in error? I highlighted one of the values, and asked my class what it meant, when we didn't get the $0$s in the required spots.
Much to my horror, the class wasn't able to understand that
While Sage is an excellent tool for financial mathematics, be certain that you put no dollar signs in front of the numbers. Likewise, you should not put the Euro symbol after any numbers. You should not use any other currency symbols either.
Like any programming language, Sage uses those symbols to perform various tasks.
For example, to find the monthly payment on a 30-year mortgage for a $ 450,000 house with 10% down, and 4% compounded monthly, you should type
find_root( 450000*0.9 == x*(1 - (1 + 0.04/12)^-(12*30))/(0.04/12), 0, 1000000)
which correctly computes the answer: $ 1933.53... is the monthly payment.
You may not put a dollar sign in front of the 450000
, nor in front of the 1000000
.
Also, note that I did not include the comma inside of 450000
when indicating $ 450,000. (See also the entry "5: Commas in the middle of large numbers" of this list, above.)
For those who have not studied mathematical finance, note that the above code solves the equation
$$ 450000(0.9) = x \frac{1 - \left (1+\frac{0.04}{12} \right)^{-(30)(12)}}{\frac{0.04}{12}} $$
for
blah blah blah
blah blah blah
In many of the common programming languages, such as Java, C, C++, Pascal, and so forth, the indentation does not matter at all. While there are style guides, and some instructors enforce those, the compiler isn't interested in your indentation. However, in Python, the exact opposite is true. The indentation is very important, and it affects how the computer views your code. This can flummox experienced and semi-experienced programmers who come to Python, having learned other languages before.
Consider the following bit of python code, and note the careful indentation.
def newton_method(f, x_old, max_iterate = 10, verbose=False):
"""An implementation of Newton’s Method, to find a
root of f(x) given an initial guess for x. A default of 10
iterations will be carried out unless the optional
parameter max_iterate is set to something else. Set
verbose = True to see all the intermediate stages."""
f_prime(x) = diff( f, x )
for j in range(0, max_iterate):
ratio = f(x_old) / f_prime(x_old)
x_new = x_old - ratio
if (verbose==True):
print "iteration=", j
print "x_old=", x_old
print "f(x)=", f(x_old)
print "f’(x)=", f_prime(x_old)
print "ratio=", ratio
print "x_new=", x_new
print
x_old = N(x_new)
return x_old
By the way, the above code was taken from Sage for Undergraduates, a book written by Gregory V. Bard and published by The American Mathematical Society in 2015. (The pdf-file of that book is available for free, and the print version has an extremely low price.) It was Figure 6 in Section 5.4. (blah: verify)
Here's how it works:
-
The
print
statements are subordinate to theif
statement, which is subordinate to thefor
statement, which is subordinate to thedef
statement. Therefore, they are indented three times. -
The
if
statement, and the setting of the variablesratio
,x_new
, andx_old
with the=
sign, are subordinate to thefor
statement and thedef
statement, but not theif
statement. The programmer must be careful with the indentation to avoid screwing up that relationship. -
The "docstring" (i.e. the very large comment set off in quotes), the setting of the function
f_prime(x)
with the=
sign, thefor
statement, and thereturn
statement, are only subordinate to thedef
statement. Therefore, they are indented once. -
All the commands above, except the
def
statement itself, are subordinate to thedef
statement but possibly to other statements too. That's why thedef
statement is the only command that is indented zero times. -
In summary, the indentation shows which commands are subordinate to which other commands. The indentation is absolutely important. It is not a minor detail.
The reader might find reading all of "Ch 5: Programming in Sage and Python" of Sage for Undergraduates to be a useful introduction to Python.
Look at the large block of code in the previous item. Do you see how the def
command, the for
command, and the if
command each have a set of commands subordinate to them?
Whenever a command (such as def
, for
, or if
, but also else
) has commands subordinate to it, there must be a colon (:
) at the end of that line. This colon isn't optional, and it helps Python understand the syntax.
While the colon makes the code more human readable, I find that sometimes programmers often forget it.
A common question in a "college algebra" class might be to expand something like $$ -1 + 2x\left (5 - x\left (3 + x\left (2 - x\left (3 + x \right )\right )\right )\right ) $$ to get the answer $$ 2x^5 + 6x^4 - 4x^3 - 6x^2 + 10x - 1 $$
However, older textbooks will write $$ -1 + 2x\left (5 - x\left {3 + x\left [ 2 - x\left (3 + x \right )\right ]\right }\right ) $$ instead of the original, using brackets and braces as higher-order parentheses. It's been a long time since such usage was common, but often home-schooled students will learn from their parents' high school algebra textbooks.
In any case, brackets have a specific meaning in Python and therefore, Sage. Brackets indicate lists, and should never be used as higher-order parentheses. Likewise, braces should never be used as higher-ordered parentheses. (If you are curious, braces in Python are used to program a data structure that maps one value to another, which Python calls "a dictionary.")
The correct way to code $$ -1 + 2x\left (5 - x\left (3 + x\left (2 - x\left (3 + x \right )\right )\right )\right ) $$ is with
-1 + 2*x*(5 - x*(3 + x*(2 - x*(3 + x ))))
and for completeness, the correct way to code $$ 2x^5 + 6x^4 - 4x^3 - 6x^2 + 10x - 1 $$ is with
2*x^5 + 6*x^4 - 4*x^3 - 6*x^2 + 10*x - 1
Greg's to-do list:
-
Because this particular wiki/FAQ page might be read serially, sort these items. done!
-
Is the multiple lines of output issue an issue in SageMathCell only? or also in SageMathCloud as well? (Only SageMathCell.) done!
- Implicit Multiplication done!
- Did you forget to declare a variable? done!
- Huge error messages appear done!
- Mismatched parentheses done! (4 1/3. Automatic Syntax Highlighting, 4 2/3. Showing a Function)
- Commas in the middle of large numbers done!
- Capitalizing the built-in functions (6.5=A Note about "log" versus "ln") done!
- Parameters in the wrong order done!
- Your internet connection has silently gone down done!
- Misspelling a command done! (blah: search_doc)
- Scientific notation mistakes (10.5=The tale of the damaged identity matrix) done!
- Using currency signs inside of equations done!
- Mistakes involving the percent sign (blah)
- Line-breaks where they aren't permitted (blah)
- Using indentation that Python doesn't approve of done!
- Missing a colon in Python commands that have subordinate commands done!
- Using brackets or braces as higher-order parentheses done!
- (SageMathCell-only) multiple lines of output issue declined!
- blah: Move "I'm getting this huge error message" elsewhere, in addition to being here.
- I am getting this huge error message...
- I am getting an error message, ending with blah
- How can I tell if I have mismatched parentheses?
- Scientific notation appears to be broken. What am I doing wrong?
- I have functions/commands which work with small numbers but not large ones. How do I fix that?
- I have functions/commands which work without coefficients, but when I put coefficents on the terms, they stop working. Why?
blah blah blah --- implicit multiplication
blah blah balh
blah blah blah --- forgot to declare a variable
The mystery of the unwanted comma: Question: I have functions/commands which work with small numbers but not large ones. How do I fix that?
This Wiki is for CoCalc.com.
A more structured documentation is the CoCalc User Manual.
For further questions, please contact us.