Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Sage beginners guide - Finch Kraigh copy.pdf
Скачиваний:
13
Добавлен:
10.02.2015
Размер:
5.86 Mб
Скачать

Chapter 3

Working with code

The notebook interface also provides some shortcuts to make it easier to edit code in input cells:

Tab completion

Indent block of text

Comment a block of code

Uncomment a block of code

Close parenthesis

Start typing the name of a command, function, or object and press Tab to see possible completions.

Highlight block and press > to indent or < to unindent. In

Firefox, highlight block and press Tab to indent or Shift-Tab to unindent.

Highlight code and press Ctrl-.

Highlight code and press Ctrl-,

Press Ctrl-0 to automatically insert a closing parenthesis

(if needed). Press Ctrl-0 multiple times to close multiple parentheses.

Closingthenotebookinterface

When you are done with your worksheet, click Save & quit at the upper-right corner of the window. This will return you to the main screen of the notebook interface. Click Sign out (in the upper-right hand corner of the window) to exit. To return to the command line interface, click in the terminal window and press Ctrl-C to terminate the web server and resume using the command line.

Haveagohero–usingthenotebookinterface

We have just touched on a few aspects of the analysis of RC circuits. Using the Wikipedia article as a reference, add more text boxes to explain more about the calculations we just performed.

http://en.wikipedia.org/wiki/RC_circuit

[ 55 ]

Getting Started with Sage

Displayingresultsofcalculations

Before we go any further, we need to learn about the print function. print takes one argument, which is enclosed in parenthesis. print evaluates its argument and writes the result to either the interactive shell or an output cell in a worksheet. If the argument is a string, print simply prints the string. If the argument is another type, it will be converted to a string before being printed. By default, each call to the print function will result in a new line of output. For example, enter the following code in an input cell to see how print works in a worksheet:

print('This is a string') print(1.0)

print(sqrt)

The result looks like this:

We'll use print extensively to display the output from Sage calculations. In older Python code, you will often see print used as a statement instead of a function:

print 'This is a string'

Python versions 2.6 and later support using print as either a statement or a function. However, in Python 3 and later only the function syntax will be supported. Therefore,

we will use print as a function in order to make our code compatible with future versions of Python.

Operatorsandvariables

Operators and variables are two fundamental elements of numerical computing. Sage uses the Python programming language as the interface for all of its components, so writing code for Sage is very similar to writing Python code. Sage extends the Python language with additional types that are well suited for mathematical calculations. In this section, we'll learn more about how operators and variables work in Sage.

[ 56 ]

Chapter 3

Arithmetic operators

The following table lists the operators that are available in Sage:

Operator

Function

Operator

Function

=

Assignment

==

Equality

+

Addition

>

Greater than

-

Subtraction

>=

Greater than or equal to

*

Multiplication

<

Less than

/

Division

<=

Less than or equal to

** or ^

Power

!=

Not equal to

%Modulo (remainder)

//Integer quotient

Note that the assignment operator is a single equal sign, while the test for equality is a double equal sign. The following example illustrates the difference between the two:

sage: a = 4 # assigns the value 4 to a sage: a == 5 # tests whether a is equal to 5 False

When performing arithmetic, it is important to know which operations take precedence over others. Operations with higher precedence will be done first. The following table lists the operators in order from lowest to highest precedence:

or and not

in, not in is, is not

>, <=, >, >=, ==, !=, <> +, - *, /, % **, ^

If there is any ambiguity, use parenthesis to make it clear which operations should be done first. This will also make your code easier to read.

[ 57 ]

Getting Started with Sage

Popquiz–workingwithoperators

Try to figure out what answer Sage will give to the following math problems, and check your answers with Sage:

2 + 3^2

4 + 2 * 5

3 * 2 == 2 * 10

5 * 2 > 7 + 1

2 + 1 == 3 * 1 and 5 < 6 True and not False or True

Numericaltypes

Variables in Sage, like Python, are dynamically typed. Unlike traditional languages such as C or FORTRAN, Sage does not require you to declare variables before using them. A variable can be assigned a real number in one line of code, an integer in another line, and a string in the next. However, mathematical operations require numerical types to be defined with more accuracy. The results of a calculation can change, depending on the types of variables involved. In the following examples, we will use the type function to determine the type of any variable in Sage.

Integersandrationalnumbers

When you define a variable without using a decimal point or exponential notation, Sage assumes the variable is an integer. Operations on integers can result in integers, rational numbers, or symbolic expressions. Evaluate the following code in an input cell:

a = 10 print(a) print(type(a)) print(a / 3)

print(type(a / 3)) print(sqrt(a)) print(type(sqrt(a)))

[ 58 ]

Chapter 3

The result should look like this:

Realnumbers

A real number is any decimal number. Sage creates a real number when you define a variable using a decimal point or exponential notation. You can use the notation "1e9" to represent "one times ten to the power nine."

b = 10.0 print(b) print(type(b)) print(b / 3)

print(type(b / 3)) print(sqrt(b)) print(type(sqrt(b)))

The result should look like this:

Most operations in Sage can return real numbers with arbitrary precision. Later in the chapter, we'll see how to find out how many bits of precision are available for a real number. Note that the results of a floating-point calculation depend on how the floatingpoint operations are implemented on a particular type of processor. Therefore, floatingpoint numbers shown here may be slightly different when the calculations are repeated on different platforms.

[ 59 ]

Getting Started with Sage

Complexnumbers

Complex numbers consist of a real part and an imaginary part. Sage represents a complex number with a complex number type or a symbolic type, depending on how you define the number. If you define a complex number on the command line using the built-in constant I (or i) to represent the square root of -1, then the number is stored as a symbolic expression. Operations on integers and rational numbers will also return a symbolic expression. In contrast, the square root of a negative real number is stored as a complex number type.

c1 = sqrt(-1.0) print(c1) print(type(c1))

c2 = sqrt(-1) print(c2) print(type(c2))

c3 = 1.0 + i*sqrt(2.0) print(c3) print(type(c3))

The result should look like this:

Symbolicexpressions

In addition to numerical calculations, Sage has extensive capabilities to perform symbolic mathematics. We'll cover this subject in detail in Chapter 7. For now, we'll use the var function to declare symbolic variables.

var('x, y, z') print(x) print(type(x)) z = x + y print(z)

[ 60 ]

Chapter 3

The result should look like this:

var accepts a string argument with variable names separated by commas (we'll cover strings in a bit). It makes the code more readable if you use a space after each comma.

Definingvariablesonrings

For engineering and scientific computation, you will generally use real or complex numbers and ignore the other types. However, when working with symbolic mathematics or doing theoretical work, it may be very important to specify the correct ring for a variable. Sage allows you to specify the ring over which a number is defined. Four commonly used rings are as follows:

Ring

Constructor in Sage

Integers

ZZ

Rational numbers

QQ

Real numbers

RR

Complex numbers

CC

You can use rings to specify the type of a variable, as shown in this example:

integer_var = ZZ(4) rational_var = QQ(4/3) real_var = RR(4/3) complex_var = CC(sqrt(-1)) print(integer_var) print(rational_var) print(real_var) print(complex_var)

The result should look like this:

[ 61 ]

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]