STAT218Lab1

932 days ago by pub

Sage Lab 1: Numbers, Sets and Maps

STAT 218 2009 S2: Computational Methods in Statistics

©2009 Jennifer Harlow, Dominic Lee and Raazesh Sainudiin.
Creative Commons Attribution-Noncommercial-Share Alike 3.0

Introduction

This is an interactive Sage worksheet from the Sage Notebook.

This lab will start by showing you some of the basic numeric capabilities of SAGE.   Then we will look at how SAGE can deal with two of the ideas we have discussed in lectures:   Sets, and Maps.

  1. A worksheet cell is the area enclosed by a gray rectangle. 
  2. You may type any expression you want to evaluate into a worksheet cell.   We have already put some expressions into this worksheet.
  3. When you are in a cell you can evaluate the expression in it by pressing <SHIFT><ENTER> or just by clicking the evaluate button below the cell. 

I. Numeric Operations in SAGE

To start with, we are going to be using SAGE like a hand-held calculator. Let's perform the basic arithmetic operations of addition, subtraction, multiplication, division, exponentiation, and remainder over the three standard number systems: Integers, Rational numbers and Real Numbers.  

Anything after a '#' symbol is a comment - comments are ignored by SAGE but help programmers to know what's going on.  

 

Example 1: Integer Arithmetic

Try evaluating the cell containing 1+2 below by placing the cursor in the cell and pressing  <SHIFT><ENTER>.  Next, modify the expression and evaluate it again.  Try 3+4, for instance.

1+2 # one is being added to 2 
       
3-4 # subtracting 4 from 3 
       

The multiplication operator is '*', the division operator is '/'.

2*6 # multiplying 2 by 6 
       
15/5 # dividing 15 by 5 
       

The exponentiation operator is '^'.

2^3 # exponentiating 2 by 3, i.e., raising 2 to the third power 
       

Being able to finding the remainder after a division is surprisingly useful in computer programming.

11%3 # remainder after 11 is divided by 3; i.e., 11=3*3+2 
       

Another way of referring to this is 11 modulus 3, which evaluates to 2.   '%' is the modulus operator.

Try typing in and evaluating some expressions of your own.

 
       

Example 2: Operator Precedence for Evaluating Arithmetic Expressions

Sometimes we want to perform more than one arithmetic operation with some given integers.  Suppose, we want to "divide 12 by 4 then add the product of 2 and 3 and finally subtract 1."  Perhaps this can be achieved by evaluating the expression "12/4+2*3-1"?

But could that also be interpreted as "divide 12 by the sum of 4 and 2 and multiply the result by the difference of 3 and 1"?

In programming, there are rules for the order in which arithmetic operations are carried out.  This is called the order of precedence.

The basic arithmetic operations are: +, -, *, %, /, ^. The order in which operations are evaluated are as follows:

  1. ^ Exponents are evaluated right to left
  2. *, %, / Then multiplication, remainder and division operations are evaluated left to right
  3. +, - Finally, addition and subtraction are evaluated left to right

Operator precedence can be forced using parenthesis.

(12/4) + (2*3) - 1 # divide 12 by 4 then add the product of 2 and 3 and finally subtract 1 
       
12/4+2*3-1 # due to operator precedence this expression evaluates identically to the parenthesized expression above 
       

Operator precedence can be forced using nested parentheses. When our expression has nested parenthesis, i.e., one pair of parentheses inside another pair, the expression inside the inner-most pair of parentheses is evaluated first.

(12/(4+2)) * (3-1) # divide 12 by the sum of 4 and 2 and multiply the result by the difference of 3 and 1 
       

Now you try one.

Try writing an expression which will subtract 3 from 5 and then raise the result to the power of 3.

 
       

 

Example 3: Rational Arithmetic

So far we have been dealing with integers. Integers are a type in SAGE.  Algebraically speaking, integers, rational numbers and real numbers form a ring.  This is something you will learn in a maths course in Group Theory or Abstract Algebra.

type(1) # find the data type of 1 
       

However, life with only integers is a bit limited. What about values like '1/2'?

This brings us to the rational numbers.

type(1/2) # data type of 1/2 is a sage.rings.rational.Rational 
       

Try evaluating the cell containing 1/2+2 below.  Next, modify the expression and evaluate it again.  Try 1/3+2/4, for instance.

1/2+2 # add one half to 2 or four halves to obtain the rational number 5/2 or five halves 
       

You can do arithmetic with rationals just as we did with integers.

3/4-1/4 # subtracting 3/4 from 1/4 
       
1/2*1/2 # multiplying 1/2 by 1/2 
       
(2/5) / (1/5) # dividing 2/5 by 1/5 
       
(1/2)^3 # exponentiating 1/2 by 3, i.e., raising 1/2 to the third power 
       

 

Example 4: Real Arithmetic (multi-precision floating-point arithmetic)

Recall that real numbers include integers, rational numbers irrational numbers like the square root of 2, pi and Euler's constant e.  Real numbers can be thought of as all the numbers in the real line between negative infinity and positive infinity.  Real numbers are represented in decimal format, for e.g. 234.4677878. 

We can do arithmetic with real numbers and can combine them with integer and rational types in SAGE.  Compare the results of evaluating the expressions below to the equivalent expressions using rationals above.

0.5+2 # one half as 0.5 is being added to 2 to obtain the real number 2.500..0 in SAGE 
       
0.75-0.25 # subtracting 0.75 from 0.25 is the same as subtracting 0.75 from 1/4 
       
0.5*0.5 # multiplying 0.5 by 0.5 is the same as 1/2 * 1/2 
       
(2/5.0) / 0.2 # dividing 2/5. by 0.2 is the same as (2/5) / (1/5) 
       
0.5^3.0 # exponentiating 0.5 by 3.0 is the same as (1/2)^3 
       
type(0.2) # data type of 0.2 is a sage.rings.real_mpfr.RealLiteral 
       

Technical note: Computers can be made to exactly compute in integer and rational arithmetic. But, because computers with finite memory (all computers today!) cannot represent the uncountably infinitely many real numbers inside themselves, they can only mimic or approximate arithmetic over real numbers using finitely many computer-representable floating-point numbers.

 

Example 5: Assignment and variables

In SAGE, the symbol = is the assignment operator.  You can assign a numerical value to a variable in SAGE using the assignment operator.  This is a good way to store values you want to use or modify later.

(If you have programmed before using a a language like C or C++ or Java, you'll see that SAGE is a bit different because in SAGE you don't have to say what type of value is going to be assigned to the variable.)

a = 1 # assign 1 to a variable named a a # disclose a 
       

Just typing the name of a variable to get the value works in the Sage Notebook, but if you are writing a program and you want to output the value of a variable, you'll probably want to use something like the print command

b = 2 c = 3 print a, b, c # print out the values of a and b and c 
       

Variables can be strings as well as numbers.  Anything you put inside quote marks will be treated as a string by SAGE.

myStr = "this is a string" # assign a string to the variable myStr myStr # disclose myStr 
       
type(myStr) # check the type for myStr 
       

You can reassign different values to variable names.  Using SAGE you can also change the type of the values assigned to the variable (not all programming languages allow you to do this)

print "Right now, a =", a, "and is of type", type(a) # using , and strings in double quotes print can be more flexible a = 1/3 # reassign 1/3 to the variable a print "Now, a =", a, "and is of type", type(a) # note the change in type 
       
f=(5-3)^(6/2)+3*(7-2) # assign the expression to f f # disclose f 
       

Variables in Sage have methods you can access using the dot operator. Sometimes you might need the numeric approximate of a variable instead of its exact value. One way is to use the dot operator and the .n() method.  The number of digits returned by the method can be specified explicitly.  The idea here is to tell the method .n() how many digits you want to see by assigning a value  to the paramenter digits.

x=2^(1/2) print x print x.n() print x.n(digits=30) 
       

Example 6: Truth statements and Boolean values

Consider statements like "Today is Friday" or "2 is greater than 1" or " 1 equals 1":   statements which are either true or not true (i.e., false).   SAGE has two values, True and False  which you'll meet in this situation.   These value are called Booleans values, or values of the type Boolean.

In SAGE, we can express statements like "2 is greater than 1" or " 1 equals 1" with relational operators, also known as value comparison operators.   Have a look at the list below.

Lets try some really simple truth statements.

1 < 1 # 1 is less than 1 
       

Try changing the numbers if you want to, or try different operators, like '>' instead of '<'.

1 <= 1 # 1 is less than or equal to 1 
       

We can use these operators on variables as well as on values.   Again, try assigning different values to x and y, or try using different operators, if you want to.

x = 1 # assign the value 1 to x y = 2 # assign the value 2 to y x == y # evaluate the truth statement "x is equal to y" 
       

Note that when we check if something equals something else, we use "==", a double equals sign. This is because '=', a single equals sign, is the assignment operator we talked about above.  Therefore, to test if x equals y we can't write 'x = y' because this would assign y to x, instead we use the equality operator '==' and write 'x == y'.

We can also assign a Boolean value to a variable.

# Using the same x and y as above myBoolean = (x == y) # assign the result of x == y to the variable myBoolean myBoolean # disclose myBoolean 
       
type(myBoolean) # check the type of myBoolean 
       

If we want to check if two things are not equal we use '!='.   As we would expect, it gives us the opposite of testing for equality

x != y # evaluate the truth statement "x is not equal to y" 
       

Example 7: Mathematical constants

Sage has reserved words that are defined as common mathematical constants.  For example, pi and e behave as you expect.  Numerical approximations can be obtained using the .n()method, as before.

print pi, "~", pi.n() # print a numerical approximation of the mathematical constant pi print e, "~", e.n() # print a numerical approximation of the mathematical constant e 
       

Example 8: Mathematical functions

Many familiar mathematical functions are also available directly in Sage as 'built-in' functions.  They can be evaluated using parenthesis (brackets).

print 'sin(pi) prints as', sin(pi) 
       
print 'cos(1/2) prints as', cos(1/2) print 'cos(1/2).n(digits=5) prints as', cos(1/2).n(digits=5) print 'float(cos(1/2)) prints as', float(cos(1/2)) print 'cos(0.5) prints as', cos(0.5) print 'exp(2*pi*e) prints as', exp(2*pi*e) print 'log(10) prints as', log(10) print 'log(10).n(digits=5) prints as', log(10).n(digits=5) print 'float(log(10)) prints as', float(log(10)) print 'log(10.0) prints as', log(10.0) 
       

You can find out what built-in functions are available for a particular variable by typing the variable name followed by a '.' and then pressing the TAB key.

x=-2 
       
# type x. and press TAB 
       

Try the abs function that evaluates the absolute value of x.

abs(x) 
       

If you want to know what a built-in function does, type the function name followed by a '?'.

abs?