Sage: Tips and Tricks

Sage Beginner's Guide

May 2011


Unlock the full potential of Sage for simplifying and automating mathematical computing with this book and eBook


Sage Beginner's Guide

Sage Beginner's Guide

Unlock the full potential of Sage for simplifying and automating mathematical computing

        Read more about this book      

(For more resources related to this topic, see here.)

Calling the reset() function
Tip: If you start getting strange results from your calculations, you may have accidentally re-defined a built-in function or constant. Try calling the reset() function and running the calculation again. Remember that reset will delete any variables or functions that you may have defined, so your calculation will have to start over from the beginning.


The value of variable i
Tip: Although the variable i is often used as a loop counter, the default value of i in Sage is the square root of negative one. Remember that you can use the command restore('i') to restore i to its default value.


Calling Maxima directly
Tip: Sage uses Maxima, an open-source computer algebra system, to handle many symbolic calculations. You can interact directly with Maxima from a Sage worksheet or the interactive shell by using the maxima object. For example, the following command will factor an expression using Maxima:

F = maxima.factor('x^5 - y^5')


The factor function
Tip: The factor function in Sage is used to factor both polynomials and integers. This behaviour is different from Mathematica, where Factor[] is used to factor polynomials and FactorInteger[] is used to factorize integers.


Logarithms in Sage
Tip: The log function in Sage assumes the base of the logarithm is e. If you want to use a different base (such as 10), use the optional argument with keyword base to specify the base. For example: log(x, base=10)


Specifying colors in Sage
Tip: There are several ways to specify a color in Sage. For basic colors, you can use a string containing the name of the color, such as red or blue. You can also use a tuple of three floating-point values between 0 and 1.0. The first value is the amount of red, the second is the amount of green, and the third is the amount of blue. For example, the tuple (0.5, 0.0, 0.5) represents a medium purple color.


Organizing code blocks
Tip: If you find a block of code occurring more than once in your program, stop and move that block of code to a function. Duplicate blocks of code will make your programs harder to read and more prone to bugs.


The for statement
Tip: Don't forget to put a colon at the end of the for statement! Remember to consistently indent every statement in the loop body.


Manipulating the data in an object
Tip: As you start using objects, you may be frustrated by the lack of direct access to the data. You may find yourself tempted to avoid using the methods defined by the object, and directly manipulate the data in the object. This defeats the purpose of using objects! If the methods seem to be hindering your use of the object, you probably aren't using them right. Take another look at the documentation and examples, and re-think your approach.


Items of different types in a list
Tip: The items in a list usually have the same type. Technically, it is possible to mix types in a list, but this is generally not a good idea for keeping your code organized and readable. If the need arises to use items of different types, it may be better to use a dictionary.


Ordered dictionaries
Tip: Python 2.7 and versions above 3.1.3 contain a new class called OrderedDict, which works just like an ordinary dictionary except that it remembers the order in which items were inserted. This class is not available in Sage 4.6.1 because Sage is still using Python 2.6, but it should be available soon.


Runtime errors
Tip: if statements are not ideal for catching runtime errors. Exceptions are a much more elegant way to deal with runtime errors.


Using exceptions correctly
Tip: The whole idea of using exceptions is to make it easier to identify and handle specific runtime errors in your programs. You defeat the purpose of using exceptions if you place too many lines of code in a try block, because then it's hard to tell which statement raised the exception. It's also a bad idea to have a bare except: statement that doesn't specify the exception type that is being caught. This syntax will catch any type of exception, including SystemExit and KeyboardInterrupt exceptions, making it hard to terminate a misbehaving program. It's also considered bad practice to catch an exception without properly handling it, as this practice can mask errors.


reload a module after making changes
Tip: Let's say you created a module called and used import tank to make its names available in a Sage script, or on the Sage command line. During testing, you found and fixed a bug, and saved the module file. However, Sage won't recognize that you changed anything unless you use the command reload(tank) to force it to reload the module. When working with multiple modules in a package, you may need to import a module on the command line (or in a worksheet cell) before reloading it.


Tip: Sage can be used with LaTeX to typeset complex mathematical formulae and save the results as PDF or DVI files. If you have set the SAGE_BROWSER environment variable to force Sage to use a particular web browser, you might have trouble viewing PDF or DVI files in an external viewer. If this occurs, unset SAGE_BROWSER, and change the default web browser for your operating system so that Sage will use the correct browser.


Optimizing innermost loops
Tip: Many numerical algorithms consist of nested loops. The statements in the innermost loop are executed more times than statements in the outer loops, so you will get the most "bang for your buck" by focusing your optimization efforts on the innermost loop. When loops are nested, the code in the innermost loop executes most often. When a calculation needs to run fast, you will get the greatest speed increase by optimizing the code in the innermost loop.



In this article we took a look at some tips and tricks for working with Sage and using Python more effectively.

Further resources on this subject:

Books to Consider

comments powered by Disqus

An Introduction to 3D Printing

Explore the future of manufacturing and design  - read our guide to 3d printing for free