$$ \def\CC{\bf C} \def\QQ{\bf Q} \def\RR{\bf R} \def\ZZ{\bf Z} \def\NN{\bf N} $$

Hacer está página una hoja de trabajo

Si esta mirando este documento con un explorador web como una página estática, usted puede ver todos los ejemplos sin embargo debe copiar y pegar cada línea de código para hacer experimentos. Utilice el botón Upload worksheet y copie y pegue este URL en esta página para obtener una copia editable en su cuaderno (notebook).

Si usted está navegando este document como parte de la documentación en vivo de Sage, usted puede manipular los ejemplos directamente aquiñ sin embargo sus cambios no seran guardados y se perderan una vez usted cierre la página. Utilice Copy worksheet desde el menu File... arriba de esta página para obtener una copia editable en su cuaderno.

En ambos el tutorial en vivo y en el cuaderno usted puede borrar todo el output seleccionando Delete All Output en el menu Action... al lado del menu File... arriba del cuaderno.

Insertando, Editando y Evaluando Input

Para evaluar código en el cuaderno de Sage, entre el còdigo en una celda de intput y presione shift-enter ó el link evaluate. Intente esto ahora con una expresión simple (e.g. 2+3).


In [ ]:
2 + 3

In [ ]:
# edit here

In [ ]:
# edit here

Para crear celdas de input nuevas, presione la linea azul que aparece entre las celdas cuando mueve su mouse entre las dos. Intente esto ahora

To create new input cells , click the blue line that appears betweencells when you move your mouse around. Try it now:


In [ ]:
1 + 1

In [ ]:
# edit here

Usted puede retroceder en cualquier celda presionando en el interior (o utilizando las flechas de su teclado para moverse arriba o abajo). Regrese a su ejemplo y cambie el 2+3 a 3+3 y reevaluelo. Una celda vacía puede ser borrada con la tecla de borrar.

Usted tambien puede editar los textos al hacer doble click sobre ellos. Usted puede incluir matemáticas como $\sin(x) - y^3$ utilizando los signos de dollar como en LaTeX.

Sistemas de ayuda

Hay varias maneras de obtener ayuda en Sage.

  • navegando a travez de la documentación (hay un link de Help ariba a la derecha en el cuaderno)
  • ¨tab completion" al presionar tab se completan los comandos
  • ayuda contextual

A continuación explicamos los ultimos dos ejemplos por medio de ejemplos.

Terminación con tab y documentación contextual

Comience a excribir y presione la tecla tab. La interface intenta completar el nombre del comando. Si hay más de una opción, entonces le mostrarán una lista. Recuerde que Sage es sensible a minúsculas y mayúsculas, i.e. diferencia entre estos dos tipos de letras. Por ejemplo ¨tab completion" (terminación por tab) de klein no le mostrará el comando KleinFourGroup que construye el grupo $\mathbb{Z}/2 \times \mathbb{Z}/2$ como un grupo de permutación. Intente esto en las siguientes celdas.

You can go back and edit any cell by clicking in it (or using thearrow keys on your keyboard to move up or down). Go back and changeyour 2+3 above to 3+3 and re-evaluate it. An empty cell can be deleted with backspace.

You can also edit this text right here by double clicking on it,which will bring up the TinyMCE Javascript text editor. You can evenput embedded mathematics like this $sin(x) - y^3$ by using dollar signsjust like in TeX or LaTeX.

Help systems

There are various ways of getting help in Sage.

  • navigate through the documentation (there is a link Help at the top rightof the worksheet),
  • tab completion,
  • contextual help.

We detail below the latter two methods through examples.

Completion and contextual documentation

Start typing something and press the tab key. The interface tries tocomplete it with a command name. If there is more than one completion, thenthey are all presented to you. Remember that Sage is case sensitive, i.e. itdifferentiates upper case from lower case. Hence the tab completion ofklein won’t show you the KleinFourGroup command that builds the groupZZ/2 times ZZ/2 as a permutation group. Try it on the next cells:


In [ ]:
klein

In [ ]:
Klein

To see documentation and examples for a command, type a question mark ? atthe end of the command name and press the tab key as in:

Para ver documentación y ejemplos para un comando, escriba el signo de interrogación ? al final del nombre del comando y presione la tecla tab como en la siguiente celda:


In [ ]:
KleinFourGroup?

In [ ]:
# edit here

Exercise A

What is the largest prime factor of 600851475143?


In [ ]:
factor?

In [ ]:
# edit here

En la manipulación anterior no hemos guardado ninguna información para utilizarla despues. Esto se puede hacer en Sage con el símbolo = como en el siguiente ejemplo:

In the above manipulations we have not stored any data forlater use. This can be done in Sage with the = symbol as in:


In [ ]:
a = 3
b = 2
print a+b

Esto se puede entender como una evaluación de Sage de la expresión a la derecha del signo de = y creando el objeto apropiado, y luego asociando el objeto con una etiqueta, dada por el lado izquierdo (vea el principio del siguiente tutorial para más detalles). Varias asignaciones se pueden hacer a la vez:

This can be understood as Sage evaluating the expression to the rightof the = sign and creating the appropriate object, and thenassociating that object with a label, given by the left-hand side (seethe foreword of Tutorial: Objects and Classes in Python and Sage fordetails). Multiple assignments can be done at once:


In [ ]:
a,b = 2,3
print a,b

Esto nos permite intercambiar los valores de dos variables directamente:

This allows us to swap the values of two variables directly:


In [ ]:
a,b = 2,3
a,b = b,a
print a,b

También podemos asignar un valor común a varias variables simultaneamente:

We can also assign a common value to several variables simultaneously:


In [ ]:
c = d = 1
c, d

In [ ]:
d = 2
c, d

Note that when we use the word variable in the computer-science sense wemean “a label attached to some data stored by Sage”. Once an object iscreated, some methods apply to it. This means functions but instead ofwriting f(my_object) you write my_object.f():

Note que cuando utiliar la palabra variable en el contexto de la informática queremos decir ¨una etiqueta sobre un pedazo de data guardado en Sage¨. Una vez un objeto es creado, algunos métodos se aplican a este. Esto quiere decir funciones pero en vez de escribir f(mi_objeto)escribimos mi_objeto.f():


In [ ]:
p = 17
p.is_prime()

Vea Tutorial: Objetos y Clases en Python y Sage para más detalles. Para saber todos los métodos de un objeto usted puede utilizar de nuevo ¨tab completion" terminación por tab. Escriba el nombre el objeto seguido por un punto y luego presione tab:

See Tutorial: Objects and Classes in Python and Sage for details.To know all methods of an object you can once more use tab-completion. Write thename of the object followed by a dot and then press tab :


In [ ]:
a.

In [ ]:
# edit here

Ejercicio B

Cree la permutación 51324 y asígnele la variable p.

Exercise B

Create the permutation 51324 and assign it to the variable p.


In [ ]:
Permutation?

In [ ]:
# edit here

Cual es la inversa de p?

What is the inverse of p?


In [ ]:
p.inv<tab>

In [ ]:
# edit here

Es que p contiene el patrón 123? Y el patrón 1234? Y 312? (aun si no sabe lo que es un patrón, usted debe poder encontrar el comando para hacer esto).

Does p have the pattern 123? What about 1234? And 312? (even if you don’tknow what a pattern is, you should be able to find a command that does this).


In [ ]:
p.pat<tab>

In [ ]:
# edit here

Algo de álgebra lineal

Ejercicio C

Utilice el comando matrix() para crear la siguiente matriz.

$$M = \begin{pmatrix} 10&4&1&1\\ 4&6&5&1\\ 1&5&6&4\\ 1&1&4&10 \end{pmatrix}.$$

Some linear algebra

Exercise C

Use the matrix() command to create the following matrix.

$$\begin{split}M = \left(\begin{array}{rrrr}10 & 4 & 1 & 1 \\4 & 6 & 5 & 1 \\1 & 5 & 6 & 4 \\1 & 1 & 4 & 10\end{array}\right)\end{split}$$

In [ ]:
matrix?

In [ ]:
# edit here

Luego utilice métodos de la matriz,

  1. Calcular el determiannte de la matriz.
  2. Calcular la forma escalonada de la matriz.
  3. Calcular los valores propios de la matriz.
  4. Calcular el kernel de la matriz.
  5. Calcular la descomposición LLL de la matriz (¡y busque la documentacion para saber que es LLL si es necesario!)

Then, using methods of the matrix,

  1. Compute the determinant of the matrix.
  2. Compute the echelon form of the matrix.
  3. Compute the eigenvalues of the matrix.
  4. Compute the kernel of the matrix.
  5. Compute the LLL decomposition of the matrix (and lookup thedocumentation for what LLL is if needed!)

In [ ]:
# edit here

In [ ]:
# edit here

Ahora que tiene acceso a varios métodos de la matriz

  1. Cree el vector $v=(1,-1,-1,1)$.
  2. Calcule el producto $M\cdot v$ y $v\cdot M$. Que operación matématica al límite está haciendo Sage implícitamente?

Now that you know how to access the different methods of matrices,

  1. Create the vector v = (1,-1,-1,1) .
  2. Compute the two products: Mcdot v and vcdot M . What mathematicallyborderline operation is Sage doing implicitly?

In [ ]:
vector?

In [ ]:
# edit here

Nota

Los vectores en Sage son vectores de fila. Un método como eigenspace puede que no entregue lo esperado, asi que es mejor especificar eigenspace_left ó eigenspace_right. Los mismo para el kernel (left_kernel ó right_kernel), ...

Algo sobre graficar

El comando plot() le permite dibujar las gráficas de funciones. Recerude que puede tener acceso a la documentación presionando la tecla tab despues de escribir plot? en una celda:

Note

Vectors in Sage are row vectors. A method such as eigenspaces might notreturn what you expect, so it is best to specify eigenspaces_left oreigenspaces_right instead. Same thing for kernel (left_kernel orright_kernel), and so on.

Some Plotting

The `plot() command allows you to draw plots of functions. Recall that you can access the documentation by typing plot? in a cell:


In [ ]:
plot?

In [ ]:
# edit here

Aquí hay un ejemplo simple:

Here is a simple example:


In [ ]:
var("x")   # make sure x is a symbolic variable

In [ ]:
plot(sin(x^2), (x,0,10))

Aquí hay una gráfica más complicada. Intente cambiar todos los inputs del comando de graficar de alguna manera, evaluando para ver que pasa:

Here is a more complicated plot. Try to change every single input to the plotcommand in some way, evaluating to see what happens:


In [ ]:
P = plot(sin(x^2), (x,-2,2), rgbcolor=(0.8,0,0.2), thickness=3, linestyle="--", fill="axis")
show(P, gridlines=True)

Arriba utilizamos el comando show() para mostrar la gráfica después de que fué creada. Usted puede también utilizar P.show.

Above we used the show() command to show a plot after it was created. You canalso use P.show instead:


In [ ]:
P.show(gridlines=True)

In [ ]:
P.show?

Graficar varis funciones al mismo tiempo es tan fácil como sumarlas:

Plotting multiple functions at once is as easy as adding them together:


In [ ]:
P1 = plot(sin(x), (x,0,2*pi))
P2 = plot(cos(x), (x,0,2*pi), rgbcolor="red")
P1 + P2

Expresiones Simbólicas

Aqui hay un ejemplo de una función simbólica:

Symbolic Expressions

Here is an example of a symbolic function:


In [ ]:
f(x) = x^4 - 8*x^2 - 3*x + 2
f(x)

In [ ]:
f(-3)

Este es un ejemplo de una función in la variable matemática $x$. Cuando Sage comienza, define el sìmbolo $x$ para ser una variable matemática. Si usted quiere utilizar otro símbolo como variable, debe definirlo antes:

This is an example of a function in the mathematical variable x. When Sagestarts, it defines the symbol x to be a mathematical variable. If you wantto use other symbols for variables, you must define them first:


In [ ]:
x^2

In [ ]:
u + v

In [ ]:
var("u v")

In [ ]:
u + v

De todas maneras es posible definir funciones simbólicas sin antes definir sus variables:

Still, it is possible to define symbolic functions without firstdefining their variables:


In [ ]:
f(w) = w^2
f(3)

En este caso las variables son definidas implícitamente:

In this case those variables are defined implicitly:


In [ ]:
w

Ejercicio D

Defina la función simbólica $f(x) = x \sin(x^2)$. Grafique $f$ en el dominio $[-3,3]$ y con color rojo. Utlice el método find_root() para aproximar numéricamente la raiz de $f$ en el intervalo $[1,2]$ :

Exercise D

Define the symbolic function f(x) = x sin(x^2). Plot f on thedomain [-3,3] and color it red. Use the find_root() _method to numerically approximate the root of f on the interval [1,2]:

::


In [ ]:


In [ ]:

Calcule la línea tangente a :math:$f\` en $x=1$ :

Compute the tangent line to f at x=1:


In [ ]:
# edit here

Grafique $f$ y la tangente a $f$ en $x=1$ en una sola imagen:

Plot f and the tangent line to f at x=1 in one image:


In [ ]:
# edit here

Ejercicio E (Avanzado)

Resuelva la siguiente ecuación para $y$ :

$y=1+xy^2$

Hay dos soluciones, tome la cual satisface $\lim_{x\to 0} y(x) =1$. (¡No se le olvide crear las variables $x$ y $y$!).

Exercise E (Advanced)

Solve the following equation for

$y = 1 + x y^2$

There are two solutions, take the one for which $\lim_{x\to 0} y(x) =1$.(Don’t forget to create the variables x and y!).


In [ ]:
# edit here

Expanda $y$ como una serie de Taylor truncada en $0$ y con $n=10$ términos.

Expand y as a truncated Taylor series around 0 and containingn=10 terms.


In [ ]:
# edit here

Es que usted reconoce los coeficientes de la serie de Taylor? Tal vez quiera utilizar la Enciclopedia de secuencias de Enteros (OEIS) o mejor aún, la clase OEIS de Sage que hace consultas a la enciclopedia:

Do you recognize the coefficients of the Taylor series expansion? You mightwant to use the On-Line Encyclopedia of Integer Sequences, or better yet, Sage’s class OEIS whichqueries the encyclopedia:


In [ ]:
oeis?

In [ ]:
# edit here

¡Felicitaciones por completar su primer tutorial de Sage!

Congratulations for completing your first Sage tutorial!


In [ ]: