Assignment, Equality, and ArithmeticΒΆ

With some minor exceptions, Sage uses the Python programming language, so most introductory books on Python will help you to learn Sage.

Sage uses = for assignment. It uses ==, <=, >=, < and > for comparison:

sage: a = 5
sage: a
sage: 2 == 2
sage: 2 == 3
sage: 2 < 3
sage: a == 5

Sage provides all of the basic mathematical operations:

sage: 2**3    #  ** means exponent
sage: 2^3     #  ^ is a synonym for ** (unlike in Python)
sage: 10 % 3  #  for integer arguments, % means mod, i.e., remainder
sage: 10/4
sage: 10//4   #  for integer arguments, // returns the integer quotient
sage: 4 * (10 // 4) + 10 % 4 == 10
sage: 3^2*4 + 2%5

The computation of an expression like 3^2*4 + 2%5 depends on the order in which the operations are applied; this is specified in the “operator precedence table” in Arithmetical binary operator precedence.

Sage also provides many familiar mathematical functions; here are just a few examples:

sage: sqrt(3.4)
sage: sin(5.135)
sage: sin(pi/3)

As the last example shows, some mathematical expressions return ‘exact’ values, rather than numerical approximations. To get a numerical approximation, use either the function n or the method n (and both of these have a longer name, numerical_approx, and the function N is the same as n)). These take optional arguments prec, which is the requested number of bits of precision, and digits, which is the requested number of decimal digits of precision; the default is 53 bits of precision.

sage: exp(2)
sage: n(exp(2))
sage: sqrt(pi).numerical_approx()
sage: sin(10).n(digits=5)
sage: N(sin(10),digits=10)
sage: numerical_approx(pi, prec=200)

Python is dynamically typed, so the value referred to by each variable has a type associated with it, but a given variable may hold values of any Python type within a given scope:

sage: a = 5   # a is an integer
sage: type(a)
<type 'sage.rings.integer.Integer'>
sage: a = 5/3  # now a is a rational number
sage: type(a)
<type 'sage.rings.rational.Rational'>
sage: a = 'hello'  # now a is a string
sage: type(a)
<type 'str'>

The C programming language, which is statically typed, is much different; a variable declared to hold an int can only hold an int in its scope.

A potential source of confusion in Python is that an integer literal that begins with a zero is treated as an octal number, i.e., a number in base 8.

sage: 011
sage: 8 + 1
sage: n = 011
sage: n.str(8)   # string representation of n in base 8

This is consistent with the C programming language.

Previous topic

A Guided Tour

Next topic

Getting Help

This Page