CIRM Tutoriel 1 (français) system:sage

22 February 2010

Introduction à Sage

écrit par Franco Saliola, 22 février 2010

traduit en français par Sébastien Labbé le 4 mars 2010

 

L'aide en Sage

Il y a plusieurs façons d'obtenir de l'aide en Sage.

Manuel de référence

Cliquer sur le lien Help en haut à droite de cette page. Ceci vous amène à la documentation sur l'interface notebook ainsi qu'à un lien au manuel de référence.

{{{id=145| g = Graph({0:{1:'x',2:'z',3:'a'}, 2:{5:'out'}}); g /// Graph on 5 vertices }}} {{{id=146| show(g, edge_labels=True) /// }}} {{{id=1| matrix_plot(random_matrix(RDF, 50), cmap='Oranges_r') /// }}} {{{id=10| import matplotlib.cm matplotlib.cm.datad.keys() /// ['Spectral', 'summer', 'RdBu', 'gist_earth', 'Set1', 'Set2', 'Set3', 'Dark2', 'hot', 'PuOr_r', 'PuBuGn_r', 'RdPu', 'gist_ncar_r', 'gist_yarg_r', 'Dark2_r', 'YlGnBu', 'RdYlBu', 'hot_r', 'gist_rainbow_r', 'gist_stern', 'cool_r', 'cool', 'gray', 'copper_r', 'Greens_r', 'GnBu', 'gist_ncar', 'spring_r', 'gist_rainbow', 'RdYlBu_r', 'gist_heat_r', 'OrRd_r', 'bone', 'gist_stern_r', 'RdYlGn', 'Pastel2_r', 'spring', 'Accent', 'YlOrRd_r', 'Set2_r', 'PuBu', 'RdGy_r', 'spectral', 'flag_r', 'jet_r', 'RdPu_r', 'gist_yarg', 'BuGn', 'Paired_r', 'hsv_r', 'YlOrRd', 'Greens', 'PRGn', 'gist_heat', 'spectral_r', 'Paired', 'hsv', 'Oranges_r', 'prism_r', 'Pastel2', 'Pastel1_r', 'Pastel1', 'gray_r', 'PuRd_r', 'Spectral_r', 'BuGn_r', 'YlGnBu_r', 'copper', 'gist_earth_r', 'Set3_r', 'OrRd', 'PuBu_r', 'winter_r', 'jet', 'bone_r', 'BuPu', 'Oranges', 'RdYlGn_r', 'PiYG', 'YlGn', 'binary_r', 'gist_gray_r', 'BuPu_r', 'gist_gray', 'flag', 'RdBu_r', 'BrBG', 'Reds', 'summer_r', 'GnBu_r', 'BrBG_r', 'Reds_r', 'RdGy', 'PuRd', 'Accent_r', 'Blues', 'Greys', 'autumn', 'PRGn_r', 'Greys_r', 'pink', 'binary', 'winter', 'pink_r', 'prism', 'YlOrBr', 'Purples_r', 'PiYG_r', 'YlGn_r', 'Blues_r', 'YlOrBr_r', 'Purples', 'autumn_r', 'Set1_r', 'PuOr', 'PuBuGn'] }}} {{{id=9| /// }}}

Complétion automatique par la touche de tabulation TAB

Écrivez quelque chose et appuyez sur la touche TAB. L'interface essait de compléter ce que vous avez écrit par un nom de commande. S'il y a plus d'une possibilité, celles-ci vous seront offertes.

{{{id=57| /// }}} {{{id=55| /// }}}

? : Documentation et exemples

Pour voir la documentation et des exemples d'utilisation une commande, tapez ? à la fin de la commande et appuyez sur la touche TAB ou MAJ + ENTRÉE.

{{{id=144| matrix_plot?? ///

@options(cmap=’gray’,marker=’.’,frame=True) def matrix_plot(mat, **options):

r”“” A plot of a given matrix or 2D array.

If the matrix is dense, each matrix element is given a different color value depending on its relative size compared to the other elements in the matrix. If the matrix is sparse, colors only indicate whether an element is nonzero or zero, so the plot represents the sparsity pattern of the matrix.

The tick marks drawn on the frame axes denote the row numbers (vertical ticks) and the column numbers (horizontal ticks) of the matrix.

INPUT:

The following input must all be passed in as named parameters, if default not used:

EXAMPLES:

A matrix over \ZZ colored with different grey levels:

sage: matrix_plot(matrix([[1,3,5,1],[2,4,5,6],[1,3,5,7]]))

Here we make a random matrix over \RR and use cmap='hsv' to color the matrix elements different RGB colors:

sage: matrix_plot(random_matrix(RDF, 50), cmap='hsv')

Another random plot, but over \GF{389}:

sage: m = random_matrix(GF(389), 10)
sage: matrix_plot(m, cmap='Oranges')

It also works if you lift it to the polynomial ring:

sage: matrix_plot(m.change_ring(GF(389)['x']), cmap='Oranges')

Here we plot a random sparse matrix:

sage: sparse = matrix(dict([((randint(0, 10), randint(0, 10)), 1) for i in xrange(100)]))
sage: matrix_plot(sparse)
sage: A=random_matrix(ZZ,100000,density=.00001,sparse=True)
sage: matrix_plot(A,marker=',')

Plotting lists of lists also works:

sage: matrix_plot([[1,3,5,1],[2,4,5,6],[1,3,5,7]])

As does plotting of NumPy arrays:

sage: import numpy
sage: matrix_plot(numpy.random.rand(10, 10))

TESTS:

sage: P.<t> = RR[]
sage: matrix_plot(random_matrix(P, 3, 3))
...
TypeError: cannot coerce nonconstant polynomial to float
sage: matrix_plot([1,2,3])
...
TypeError: mat must be a Matrix or a two dimensional array
sage: matrix_plot([[sin(x), cos(x)], [1, 0]])
...
ValueError: can not convert array entries to floating point numbers

“”” import numpy as np import scipy.sparse as scipysparse from sage.plot.plot import Graphics from sage.matrix.all import is_Matrix from sage.rings.all import RDF

if is_Matrix(mat):

sparse = mat.is_sparse() if sparse:

entries = list(mat._dict().items()) data = np.asarray([d for _,d in entries]) positions = np.asarray([[row for (row,col),_ in entries],

[col for (row,col),_ in entries]], dtype=int)

mat = scipysparse.coo_matrix((data,positions), shape=(mat.nrows(), mat.ncols()))

else:
mat = mat.change_ring(RDF).numpy()
elif hasattr(mat, ‘tocoo’):
sparse = True
else:
sparse = False
try:
if sparse:
xy_data_array = mat
else:
xy_data_array = np.asarray(mat, dtype = float)
except TypeError:
raise TypeError, “mat must be a Matrix or a two dimensional array”
except ValueError:
raise ValueError, “can not convert array entries to floating point numbers”
if len(xy_data_array.shape) < 2:
raise TypeError, “mat must be a Matrix or a two dimensional array”

xrange = (0, xy_data_array.shape[1]) yrange = (0, xy_data_array.shape[0])

g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options)) g.add_primitive(MatrixPlot(xy_data_array, xrange, yrange, options)) return g

}}} {{{id=11| /// }}}

Exercices

Exercice A: Quel est le plus grand facteur premier de 600851475143?

{{{id=46| /// }}} {{{id=45| /// }}} {{{id=44| /// }}}

Exercice B: Créer la permutation 51324 et assigner la à la variable p.

  1. Quelle est l'inverse de p ?
  2. Est-ce que p possède le patron (pattern) 123 ?  1234 ? et 312 ?
{{{id=53| /// }}} {{{id=52| /// }}} {{{id=61| /// }}} {{{id=60| /// }}} {{{id=51| /// }}}

Exercice C: Utilisez la commande matrix pour créer la matrice suivante :

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

  1. Trouver le déterminant de la matrice.
  2. Trouver la forme échelonnée (echelon form) de la matrice.
  3. Trouver les valeurs propres (eigenvalues) de la matrice.
  4. Trouver le noyau (kernel) de la matrice.
  5. Trouver la décomposition LLL de la matrice.
{{{id=49| /// }}} {{{id=62| /// }}} {{{id=65| /// }}} {{{id=64| /// }}} {{{id=67| /// }}} {{{id=66| /// }}} {{{id=68| /// }}} {{{id=69| /// }}}

Calcul et dessin

 

Expressions symboliques.

Voici un exemple de fonction symbolique.

{{{id=70| f(x) = x^4 - 4*x^3 - 3*x^2 + 10*x + 8 /// }}} {{{id=130| /// }}} {{{id=129| /// }}}

Pour définir d'autres variables symboliques, utilisez la commande var.

{{{id=63| var('a,b,c') /// }}} {{{id=132| a*x^2 + b*x + c /// }}} {{{id=133| soln = solve(a*x^2 + b*x + c == 0, x) soln /// }}} {{{id=141| print soln /// }}} {{{id=101| show(soln) /// }}} {{{id=134| /// }}}

Exercices

Exercice D:

  1. Définir la fonction symbolique $f(x) = x \sin(x^2)$.
  2. Dessiner (plot) $f$ sur le domaine $[-3,3]$ et colorer la en rouge.
  3. Utiliser la méthode find_roots pour approximer numériquement la racine de $f$ sur l'intervalle $[1,3]$.
  4. Calculer la tangente de $f$ au point $x=1$.
  5. Dessiner (avec la command plot) $f$ et la tangente de $f$ au point $x=1$ en une image.
{{{id=100| /// }}} {{{id=99| /// }}} {{{id=97| /// }}} {{{id=98| /// }}} {{{id=96| /// }}} {{{id=95| /// }}} {{{id=94| /// }}}

Exercice E (Advancé):

  1. Résoudre l'équation $$y = 1 + x y^2$$ selon la variable $y$. Il y a deux solutions, choisissez celle telle que $y(0) = 1$. (N'oubliez pas de créer les variables $x$ et $y$!)
  2. Développer (Expand) $y$ les $n=10$ premiers termes de la série de Taylor au point $0$.
  3. Deviner la règle donnant les coefficients de la série de Taylor (indice: Sage possède une commande appelée sloane_find).
{{{id=93| /// }}} {{{id=135| /// }}} {{{id=92| /// }}} {{{id=89| /// }}} {{{id=88| /// }}} {{{id=87| /// }}} {{{id=86| /// }}} {{{id=85| /// }}}

Premiers pas vers la programmation

 

Définir une fonction

Pour définir une fonction en Sage, utiliser la commande def (et les deux points à la fin de la ligne qui commence par def !). Par exemple:

{{{id=140| def carre(x): return x^2 /// }}}

Noter que le corps de la fonction (la ligne return x^2) est indentée. L'indentation définit le corps de la fonction!


{{{id=139| /// }}} {{{id=84| /// }}} {{{id=138| /// }}} {{{id=83| /// }}} {{{id=107| /// }}}

Énoncés conditionnels

Voici la forme générale d'un énoncé if .

if <expression_conditionnelle>:
<bloc_de_code>
else:
<bloc_de_code>

Noter comment le premier et le deuxième bloc de l'énoncé sont indentés.

{{{id=82| def est_impair(x): if x % 2 == 1: return True else: return False /// }}} {{{id=81| /// }}} {{{id=105| /// }}}

Boucles: l'énoncé for

Voici un exemple de boucle for. Elle calcule la somme des entier impairs entre 1 et 99 (100 est exclu).

{{{id=80| s = 0 for i in range(1,100): if est_impair(i): s += i print s /// 2500 }}} {{{id=79| /// }}} {{{id=78| /// }}}

Exercices

Exercice F. Si on liste tous les nombres naturels plus petits que 10 qui sont multiples de 3 ou 5, on obtient 3, 5, 6 et 9. La somme de ces multiples est 23.

Trouver la somme de tous les multiples de 3 ou 5 plus petits que 1000.

{{{id=77| /// }}} {{{id=120| /// }}} {{{id=76| /// }}}

Exercice G. La fonction de Syracuse est définie sur les entiers positifs $n$ comme suit:

$$\text{syracuse(n)} = \begin{cases}\frac{n}{2}, & \text{si } n \text{ est pair} \\ 3n+1, & \text{si } n \text{ est impair}\end{cases}$$

Par exemple, syracuse(6) = 3 parce que 6 est pair; et syracuse(11) = 34 parce que 11 est impair.

Écrivez la fonction de Syracuse en Sage.

{{{id=75| /// }}} {{{id=74| /// }}} {{{id=73| /// }}}

Exercice H. On rappelle que le factoriel d'un entier positif $n$ est le produit $$n! = n \times (n-1) \times (n-2) \times \cdots \times 1$$ Écrire une fonction qui retourne le factoriel d'un entier $n$. Écrire la fonction de sorte qu'elle utilise une boucle.

{{{id=72| /// }}} {{{id=116| /// }}} {{{id=115| /// }}} {{{id=114| /// }}} {{{id=123| /// }}}

Exercice I: Si on commence avec 6 et que l'on applique la fonction de Syracuse, on obtient 3.  Si on applique la fonction de Syracuse à 3, alors on obtient 10. En l'appliquant à 10, on obtient 5. En continuant ainsi, on obtient la suite $$6, 3, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, \ldots$$ Noter que cette séquence a atteint la boucle $4 \mapsto 2 \mapsto 1 \mapsto 4$. La conjecture dit que c'est toujours le cas.

La conjecture $3n+1$: Pour tout $n$, la séquence atteindra toujours 1.

Écrire une fonction qui prend un entier positif et qui affiche les termes de la suite jusqu'à ce que le nombre 1 soit atteint. Par exemple avec 6, la fonction affichera

    6
    3
    10
    5
    16
    8
    4
    2
    1

La boucle while sera utile ici. Voici un exemple :

x = 0
while x < 7:
    x = x + 2
    print x

{{{id=122| /// }}} {{{id=143| /// }}} {{{id=142| /// }}}